@zuplo/runtime 7.12.6 → 7.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,10 +22,25 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as lr,$a as Dc,$b as jd,$c as ku,$e as ve,$f as nl,$g as Qe,Aa as mc,Ab as pd,Ac as Lo,Af as Cg,Ag as ul,B as Va,Ba as hc,Bb as md,Bc as tu,Bf as Tg,Bg as ll,Ca as fc,Cb as hd,Cc as ru,Cf as kg,Cg as ii,D as qo,Da as gc,Db as fd,Dc as nu,Df as Eg,Dg as pl,Ea as yc,Eb as gd,Ec as ou,Ef as Pg,Eg as ml,Fa as Sc,Fb as yd,Fc as su,Ff as Ag,Fg as ai,Ga as _c,Gb as Sd,Gc as iu,Gf as xg,Gg as hl,Ha as wc,Hb as _d,Hc as au,Hf as Ug,Hg as Lt,Ia as Rc,Ib as wd,Ic as cu,If as Og,Ig as fl,Ja as bc,Jb as Rd,Jc as du,Jf as Vu,Jg as Jn,Ka as vc,Kb as bd,Kc as uu,Kf as Ku,Kg as gl,La as Ic,Lb as vd,Lc as lu,Lf as Wu,Lg as Yo,Ma as Cc,Mb as Id,Mc as pu,Mf as Jo,Mg as Vn,Na as Tc,Nb as Cd,Nc as mu,Nf as Bn,Ng as yl,Oa as kc,Ob as Td,Oc as hu,Of as Zu,Og as Sl,Pa as Bs,Pb as kd,Pc as fu,Pf as Ir,Pg as _l,Q as Ka,Qa as Ec,Qb as Ed,Qc as gu,Qf as Yu,Qg as wl,Ra as Pc,Rb as Pd,Rc as yu,Rf as Qs,Rg as Rl,Sa as Ac,Sb as Ad,Sc as Su,Sf as Xu,Sg as bl,Ta as xc,Tb as xd,Tc as _u,Tf as Fn,Tg as vl,Ua as Uc,Ub as Ud,Uc as wu,Uf as Vo,Ug as Il,Va as Oc,Vb as Od,Vc as Ru,Vf as Qu,Vg as Xo,Wa as Mc,Wb as Md,Wc as bu,Wf as el,Wg as Cl,X as No,Xa as zc,Xb as zd,Xc as vu,Xf as tl,Xg as Tl,Y as Ds,Ya as qc,Yb as Fs,Yc as Iu,Yf as rl,Yg as N,Z as ur,Za as Nc,Zb as qd,Zc as Cu,Zf as Se,Zg as J,_ as Dn,_a as jc,_b as Nd,_c as Tu,_e as $u,_f as de,_g as me,aa as pr,ab as $c,ac as Dd,ad as Eu,af as Lu,ag as ol,ah as X,ba as $n,bb as Lc,bc as $d,bd as Pu,bf as Hu,bg as D,bh as Qo,ca as mr,cb as Hc,cc as Ld,cd as Au,cf as Y,cg as Ye,ch as Mg,da as Wa,db as Bc,dc as Hd,dd as xu,df as Bu,dg as Cr,dh as zg,ea as Za,eb as Fc,ec as Bd,ed as Uu,ef as yr,eg as pe,fa as Ya,fb as Gc,fc as Fd,fd as Ou,ff as Fu,fg as te,ga as Xa,gb as Jc,gc as Gd,gd as Mu,gf as Sr,gg as sl,ha as Qa,hb as Vc,hc as Jd,hd as hr,hf as C,hg as W,ia as ec,ib as Kc,ic as Vd,id as fr,if as _r,ig as il,ja as tc,jb as Wc,jc as Kd,jd as zu,jf as wr,jg as mt,ka as rc,kb as Zc,kc as Wd,kd as gr,kf as Ke,kg as ei,la as nc,lb as Yc,lc as Zd,ld as lt,lf as We,lg as Ko,m as Le,ma as oc,mb as Xc,mc as Yd,md as Xs,mf as Bo,mg as ti,na as sc,nb as Qc,nc as Gs,nd as Ho,nf as Rr,ng as Wo,oa as ic,ob as ed,oc as jo,od as qu,of as br,og as Gn,pa as ac,pb as td,pc as Do,pd as Hn,pf as vr,pg as Tr,qa as cc,qb as rd,qc as Js,qd as $t,qf as Fo,qg as al,ra as dc,rb as nd,rc as Vs,rd as Nu,rf as Gu,rg as Xe,sa as uc,sb as od,sc as Ks,sd as ju,sf as ze,sg as ri,t as jt,ta as Dt,tb as sd,tc as Xd,tf as Ju,tg as ni,u as Ga,ua as $s,ub as id,uc as Ws,uf as Ze,ug as cl,va as Ls,vb as ad,vc as Zs,vf as x,vg as Zo,w as B,wa as Ln,wb as cd,wc as Qd,wf as Go,wg as oi,xa as Hs,xb as dd,xc as eu,xf as le,xg as si,ya as lc,yb as ud,yc as Ys,yd as Du,yf as pt,yg as dl,za as pc,zb as ld,zc as $o,zf as Ig,zg as ne}from"../chunk-N2ZQITZD.js";import"../chunk-WIQFTAJL.js";import{a as kl}from"../chunk-6SNZ4DOC.js";import{a as Ja}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{$ as La,Ba as l,a as ye,aa as Oo,c as v,ca as qs,d as K,da as Nn,ea as Ha,fa as d,ga as Ba,ha as Fa,ia as b,ja as A,ka as Mo,ma as M,na as _,oa as m,pa as q,qa as E,ra as Ns,sa as jn,ta as T,ua as j,va as g,wa as z,xa as js,ya as zo}from"../chunk-RH345HSZ.js";import"../chunk-UKQQD2JN.js";import{a as n}from"../chunk-TYV53J3B.js";var qg=Object.create,es=Object.defineProperty,Ng=Object.getOwnPropertyDescriptor,jg=Object.getOwnPropertyNames,Dg=Object.getPrototypeOf,$g=Object.prototype.hasOwnProperty,El=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),Pl=n((e,t)=>{let r={};for(var o in e)es(r,o,{get:e[o],enumerable:!0});return t&&es(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Lg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=jg(t),i=0,c=s.length,a;i<c;i++)a=s[i],!$g.call(e,a)&&a!==r&&es(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=Ng(t,a))||o.enumerable});return e},"__copyProps"),Al=n((e,t,r)=>(r=e!=null?qg(Dg(e)):{},Lg(t||!e||!e.__esModule?es(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Hg=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function xl(e){return typeof e=="string"&&Hg.has(e.replace(/#$/,""))}n(xl,"declares2019Dialect");var mi=Symbol.for("mcp.sdk.errorBrands");function Ht(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,mi,{value:r,enumerable:!1,configurable:!0})}n(Ht,"stampErrorBrands");function Ie(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,mi)){let r=t[mi];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(Ie,"brandedHasInstance");var ue=(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})({}),ft=class Ll extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ie(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 Ie(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",Ht(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 Ll(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})({}),re=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ie(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 Ie(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Ht(this,new.target)}},ey=class extends re{static{n(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Hl(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Hl,"resourceUrlFromServerUrl");function ss({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(ss,"checkResourceAllowed");var ty="2026-07-28";function Bl(e){return e>=ty}n(Bl,"isModernProtocolVersion");function Fl(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(Fl,"appendTextFallbackForNonObject");var Gl=["task","inputRequests","requestState"];function ry(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Gl.some(t=>t in e)?e:{...e,content:[]}}n(ry,"normalizeContentlessToolResult");function ny(){let e=js(()=>E([d(),b(),A(),Mo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),s=m({ttl:b().optional()}),i=m({taskId:d()}),c=q({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=m({_meta:c.optional()}),u=a.extend({task:s.optional()}),p=m({method:d(),params:a.loose().optional()}),h=m({_meta:c.optional()}),f=m({method:d(),params:h.loose().optional()}),y=q({_meta:c.optional()}),S=E([d(),b().int()]),k=y.strict(),w=h.extend({requestId:S.optional(),reason:d().optional()}),I=f.extend({method:g("notifications/cancelled"),params:w}),U=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),O=m({icons:_(U).optional()}),H=m({name:d(),title:d().optional()}),F=H.extend({...H.shape,...O.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ee=jn(m({applyDefaults:A().optional()}),t),G=zo(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,jn(m({form:ee.optional(),url:t.optional()}),t.optional())),V=q({list:t.optional(),cancel:t.optional(),requests:q({sampling:q({createMessage:t.optional()}).optional(),elicitation:q({create:t.optional()}).optional()}).optional()}),Ge=q({list:t.optional(),cancel:t.optional(),requests:q({tools:q({call:t.optional()}).optional()}).optional()}),oe=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:G.optional(),roots:m({listChanged:A().optional()}).optional(),tasks:V.optional(),extensions:T(d(),t).optional()}),je=a.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),L=p.extend({method:g("initialize"),params:je}),Ue=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:A().optional()}).optional(),resources:m({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:m({listChanged:A().optional()}).optional(),tasks:Ge.optional(),extensions:T(d(),t).optional()}),Br=y.extend({protocolVersion:d(),capabilities:Ue,serverInfo:F,instructions:d().optional()}),Vt=f.extend({method:g("notifications/initialized"),params:h.optional()}),st=p.extend({method:g("ping"),params:a.optional()}),Ct=m({progress:b(),total:z(b()),message:z(d())}),De=m({...h.shape,...Ct.shape,progressToken:r}),it=f.extend({method:g("notifications/progress"),params:De}),Kt=a.extend({cursor:o.optional()}),Je=p.extend({params:Kt.optional()}),Ve=y.extend({nextCursor:o.optional()}),Wt=m({uri:d(),mimeType:z(d()),_meta:T(d(),M()).optional()}),Zt=Wt.extend({text:d()}),Tt=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yt=Wt.extend({blob:Tt}),$e=j(["user","assistant"]),Oe=m({audience:_($e).optional(),priority:b().min(0).max(1).optional(),lastModified:Nn.datetime({offset:!0}).optional()}),kt=m({...H.shape,...O.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:Oe.optional(),_meta:z(q({}))}),Fr=m({...H.shape,...O.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:Oe.optional(),_meta:z(q({}))}),Gr=Je.extend({method:g("resources/list")}),Jr=Ve.extend({resources:_(kt)}),at=Je.extend({method:g("resources/templates/list")}),Xt=Ve.extend({resourceTemplates:_(Fr)}),Et=a.extend({uri:d()}),Vr=Et,Kr=p.extend({method:g("resources/read"),params:Vr}),Wr=y.extend({contents:_(E([Zt,Yt]))}),Zr=f.extend({method:g("notifications/resources/list_changed"),params:h.optional()}),Yr=Et,Xr=p.extend({method:g("resources/subscribe"),params:Yr}),Qr=Et,en=p.extend({method:g("resources/unsubscribe"),params:Qr}),tn=h.extend({uri:d()}),rn=f.extend({method:g("notifications/resources/updated"),params:tn}),nn=m({name:d(),description:z(d()),required:z(A())}),on=m({...H.shape,...O.shape,description:z(d()),arguments:z(_(nn)),_meta:z(q({}))}),sn=Je.extend({method:g("prompts/list")}),an=Ve.extend({prompts:_(on)}),cn=a.extend({name:d(),arguments:T(d(),d()).optional()}),dn=p.extend({method:g("prompts/get"),params:cn}),Pt=m({type:g("text"),text:d(),annotations:Oe.optional(),_meta:T(d(),M()).optional()}),At=m({type:g("image"),data:Tt,mimeType:d(),annotations:Oe.optional(),_meta:T(d(),M()).optional()}),xt=m({type:g("audio"),data:Tt,mimeType:d(),annotations:Oe.optional(),_meta:T(d(),M()).optional()}),un=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),ct=m({type:g("resource"),resource:E([Zt,Yt]),annotations:Oe.optional(),_meta:T(d(),M()).optional()}),ln=kt.extend({type:g("resource_link")}),Pe=E([Pt,At,xt,ln,ct]),Qt=m({role:$e,content:Pe}),er=y.extend({description:d().optional(),messages:_(Qt)}),Ut=f.extend({method:g("notifications/prompts/list_changed"),params:h.optional()}),pn=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),tr=m({taskSupport:j(["required","optional","forbidden"]).optional()}),Ot=m({...H.shape,...O.shape,description:d().optional(),inputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(M()),outputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(M()).optional(),annotations:pn.optional(),execution:tr.optional(),_meta:T(d(),M()).optional()}),rr=Je.extend({method:g("tools/list")}),nr=Ve.extend({tools:_(Ot)}),or=y.extend({content:_(Pe),structuredContent:T(d(),M()).optional(),isError:A().optional()}),ae=u.extend({name:d(),arguments:T(d(),M()).optional()}),mn=p.extend({method:g("tools/call"),params:ae}),go=f.extend({method:g("notifications/tools/list_changed"),params:h.optional()}),sr=j(["debug","info","notice","warning","error","critical","alert","emergency"]),hn=a.extend({level:sr}),fn=p.extend({method:g("logging/setLevel"),params:hn}),gn=h.extend({level:sr,logger:d().optional(),data:M()}),yn=f.extend({method:g("notifications/message"),params:gn}),Sn=m({name:d().optional()}),_n=m({hints:_(Sn).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),wn=m({mode:j(["auto","required","none"]).optional()}),yo=m({type:g("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(Pe),structuredContent:m({}).loose().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),Rn=Ns("type",[Pt,At,xt]),dt=Ns("type",[Pt,At,xt,un,yo]),bn=m({role:$e,content:E([dt,_(dt)]),_meta:T(d(),M()).optional()}),vn=u.extend({messages:_(bn),modelPreferences:_n.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Ot).optional(),toolChoice:wn.optional()}),In=p.extend({method:g("sampling/createMessage"),params:vn}),Cn=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens"]).or(d())),role:$e,content:Rn}),Tn=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:$e,content:E([dt,_(dt)])}),kn=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),En=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),Pn=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),An=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),xn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),Un=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),On=E([An,xn]),Mt=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),zt=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),So=E([Mt,zt]),_o=E([Un,On,So]),Re=E([_o,kn,En,Pn]),be=u.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),Re),required:_(d()).optional()}).catchall(M())}),Mn=u.extend({mode:g("url"),message:d(),elicitationId:d(),url:d().url()}),Me=E([be,Mn]),wo=p.extend({method:g("elicitation/create"),params:Me}),Ro=h.extend({elicitationId:d()}),bo=f.extend({method:g("notifications/elicitation/complete"),params:Ro}),vo=y.extend({action:j(["accept","decline","cancel"]),content:zo(ce=>ce===null?void 0:ce,T(d(),E([d(),b(),A(),_(d())])).optional())}),Io=m({type:g("ref/resource"),uri:d()}),Co=m({type:g("ref/prompt"),name:d()}),To=a.extend({ref:E([Co,Io]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),zn=p.extend({method:g("completion/complete"),params:To}),ko=y.extend({completion:q({values:_(d()).max(100),total:z(b().int()),hasMore:z(A())})}),Eo=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),ir=p.extend({method:g("roots/list"),params:a.optional()}),qn=y.extend({roots:_(Eo)}),Po=f.extend({method:g("notifications/roots/list_changed"),params:h.optional()}),Ao=q({ttl:b().optional(),pollInterval:b().optional()}),xo=j(["working","input_required","completed","failed","cancelled"]),ut=m({taskId:d(),status:xo,ttl:E([b(),Mo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:z(b()),statusMessage:z(d())}),fe=y.extend({task:ut}),Uo=h.merge(ut),qt=f.extend({method:g("notifications/tasks/status"),params:Uo}),ar=p.extend({method:g("tasks/get"),params:a.extend({taskId:d()})}),cr=y.merge(ut),dr=p.extend({method:g("tasks/result"),params:a.extend({taskId:d()})}),zs=y.loose(),ge=Je.extend({method:g("tasks/list")}),Z=Ve.extend({tasks:_(ut)}),Nt=p.extend({method:g("tasks/cancel"),params:a.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:c,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:u,RequestSchema:p,NotificationsParamsSchema:h,NotificationSchema:f,ResultSchema:y,RequestIdSchema:S,EmptyResultSchema:k,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:I,IconSchema:U,IconsSchema:O,BaseMetadataSchema:H,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Ge,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:je,InitializeRequestSchema:L,ServerCapabilitiesSchema:Ue,InitializeResultSchema:Br,InitializedNotificationSchema:Vt,PingRequestSchema:st,ProgressSchema:Ct,ProgressNotificationParamsSchema:De,ProgressNotificationSchema:it,PaginatedRequestParamsSchema:Kt,PaginatedRequestSchema:Je,PaginatedResultSchema:Ve,ResourceContentsSchema:Wt,TextResourceContentsSchema:Zt,BlobResourceContentsSchema:Yt,RoleSchema:$e,AnnotationsSchema:Oe,ResourceSchema:kt,ResourceTemplateSchema:Fr,ListResourcesRequestSchema:Gr,ListResourcesResultSchema:Jr,ListResourceTemplatesRequestSchema:at,ListResourceTemplatesResultSchema:Xt,ResourceRequestParamsSchema:Et,ReadResourceRequestParamsSchema:Vr,ReadResourceRequestSchema:Kr,ReadResourceResultSchema:Wr,ResourceListChangedNotificationSchema:Zr,SubscribeRequestParamsSchema:Yr,SubscribeRequestSchema:Xr,UnsubscribeRequestParamsSchema:Qr,UnsubscribeRequestSchema:en,ResourceUpdatedNotificationParamsSchema:tn,ResourceUpdatedNotificationSchema:rn,PromptArgumentSchema:nn,PromptSchema:on,ListPromptsRequestSchema:sn,ListPromptsResultSchema:an,GetPromptRequestParamsSchema:cn,GetPromptRequestSchema:dn,TextContentSchema:Pt,ImageContentSchema:At,AudioContentSchema:xt,ToolUseContentSchema:un,EmbeddedResourceSchema:ct,ResourceLinkSchema:ln,ContentBlockSchema:Pe,PromptMessageSchema:Qt,GetPromptResultSchema:er,PromptListChangedNotificationSchema:Ut,ToolAnnotationsSchema:pn,ToolExecutionSchema:tr,ToolSchema:Ot,ListToolsRequestSchema:rr,ListToolsResultSchema:nr,CallToolResultSchema:or,CallToolRequestParamsSchema:ae,CallToolRequestSchema:mn,ToolListChangedNotificationSchema:go,LoggingLevelSchema:sr,SetLevelRequestParamsSchema:hn,SetLevelRequestSchema:fn,LoggingMessageNotificationParamsSchema:gn,LoggingMessageNotificationSchema:yn,ModelHintSchema:Sn,ModelPreferencesSchema:_n,ToolChoiceSchema:wn,ToolResultContentSchema:yo,SamplingContentSchema:Rn,SamplingMessageContentBlockSchema:dt,SamplingMessageSchema:bn,CreateMessageRequestParamsSchema:vn,CreateMessageRequestSchema:In,CreateMessageResultSchema:Cn,CreateMessageResultWithToolsSchema:Tn,BooleanSchemaSchema:kn,StringSchemaSchema:En,NumberSchemaSchema:Pn,UntitledSingleSelectEnumSchemaSchema:An,TitledSingleSelectEnumSchemaSchema:xn,LegacyTitledEnumSchemaSchema:Un,SingleSelectEnumSchemaSchema:On,UntitledMultiSelectEnumSchemaSchema:Mt,TitledMultiSelectEnumSchemaSchema:zt,MultiSelectEnumSchemaSchema:So,EnumSchemaSchema:_o,PrimitiveSchemaDefinitionSchema:Re,ElicitRequestFormParamsSchema:be,ElicitRequestURLParamsSchema:Mn,ElicitRequestParamsSchema:Me,ElicitRequestSchema:wo,ElicitationCompleteNotificationParamsSchema:Ro,ElicitationCompleteNotificationSchema:bo,ElicitResultSchema:vo,ResourceTemplateReferenceSchema:Io,PromptReferenceSchema:Co,CompleteRequestParamsSchema:To,CompleteRequestSchema:zn,CompleteResultSchema:ko,RootSchema:Eo,ListRootsRequestSchema:ir,ListRootsResultSchema:qn,RootsListChangedNotificationSchema:Po,TaskCreationParamsSchema:Ao,TaskStatusSchema:xo,TaskSchema:ut,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:Uo,TaskStatusNotificationSchema:qt,GetTaskRequestSchema:ar,GetTaskResultSchema:cr,GetTaskPayloadRequestSchema:dr,GetTaskPayloadResultSchema:zs,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:Nt,CancelTaskResultSchema:y.merge(ut),ClientRequestSchema:E([st,L,zn,fn,dn,sn,Gr,at,Kr,Xr,en,mn,rr,ar,dr,ge,Nt]),ClientNotificationSchema:E([I,it,Vt,Po,qt]),ClientResultSchema:E([k,Cn,Tn,vo,qn,cr,Z,fe]),ServerRequestSchema:E([st,In,wo,ir,ar,dr,ge,Nt]),ServerNotificationSchema:E([I,it,yn,rn,Zr,go,Ut,qt,bo]),ServerResultSchema:E([k,Br,ko,er,an,Jr,Xt,Wr,or,nr,cr,Z,fe]),CallToolResultWireSchema:M().superRefine((ce,vg)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let $a of Gl)if($a in ce){vg.addIssue({code:"custom",message:`content is required when the body carries '${$a}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(ry).pipe(or)}}n(ny,"build$1");var oy;function _i(){return oy??=ny()}n(_i,"buildSchemas2025");function Jl(e){return e.type!=="object"}n(Jl,"isNonObjectJsonSchemaRoot");var sy=new Set(["const","enum","default","examples"]),iy=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Ul(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(Ul,"establishesNewBase");function ay(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Ul(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=xl(e.$schema)&&e.$recursiveAnchor!==!0,o=n((s,i)=>{if(Array.isArray(s))return s.map(u=>o(u,!1));if(s===null||typeof s!="object"||!i&&Ul(s.$id))return s;let c={},a=!1;for(let[u,p]of Object.entries(s))i?c[u]=o(p,!1):(u==="$ref"||u==="$dynamicRef")&&typeof p=="string"?c[u]=p==="#"?"#/properties/result":p.startsWith("#/")?`#/properties/result${p.slice(1)}`:p:u==="$recursiveRef"&&p==="#"&&r?a=!0:sy.has(u)?c[u]=p:iy.has(u)?c[u]=o(p,!0):c[u]=o(p,!1);return a&&("$ref"in c?c.allOf=[...Array.isArray(c.allOf)?c.allOf:[],{$ref:"#/properties/result"}]:c.$ref="#/properties/result"),c},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(ay,"wrapOutputSchemaForLegacy");var Vl={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},Kl={"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},cy={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},ts;function is(){if(ts)return ts;let e=_i();return ts={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}},ts}n(is,"registryMaps");function dy(){is()}n(dy,"warmRegistryMaps2025");function Wl(e){return Object.prototype.hasOwnProperty.call(Vl,e)}n(Wl,"hasRequestMethod2025");function Zl(e){return Object.prototype.hasOwnProperty.call(Kl,e)}n(Zl,"hasNotificationMethod2025");function uy(e){return Object.prototype.hasOwnProperty.call(cy,e)}n(uy,"hasResultMethod");function ly(e){return uy(e)?is().resultSchemas[e]:void 0}n(ly,"getResultSchema");function py(e){return Wl(e)?is().requestSchemas[e]:void 0}n(py,"getRequestSchema");function my(e){return Zl(e)?is().notificationSchemas[e]:void 0}n(my,"getNotificationSchema");var UT=Object.keys(Vl),OT=Object.keys(Kl);function hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(hi,"isPlainObject$4");function rs(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(rs,"triState$1");var Ol={ok:!1,reason:"not-in-era"};function Ml(e){return hi(e)&&hi(e.outputSchema)&&Jl(e.outputSchema)}n(Ml,"toolNeedsLegacyWrap");var wi={era:"2025-11-25",hasRequestMethod:Wl,hasNotificationMethod:Zl,validateRequest:n((e,t)=>rs(py(e),t),"validateRequest"),validateResult:n((e,t)=>rs(ly(e),t),"validateResult"),validateNotification:n((e,t)=>rs(my(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>Ol,"validateInputRequest"),validateInputResponse:n(()=>Ol,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=_i();return rs(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Fl(e),o=r.structuredContent;if(o===void 0)return r;let s=typeof o!="object"||o===null||Array.isArray(o),i=t!==void 0&&Jl(t);return!s&&!i?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(hi(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=>Ml(o))?t:{...t,tools:r.map(o=>Ml(o)?{...o,outputSchema:ay(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function hy(){let e=js(()=>E([d(),b(),A(),Mo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),s=E([d(),b().int()]),i=j(["user","assistant"]),c=j(["debug","info","notice","warning","error","critical","alert","emergency"]),a=d().refine(Z=>{try{return atob(Z),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=m({ttl:b().optional()}),p=m({taskId:d()}),h=q({progressToken:r.optional(),"io.modelcontextprotocol/related-task":p.optional()}),f=m({_meta:h.optional()}),y=f.extend({task:u.optional()}),S=m({_meta:h.optional()}),k=m({method:d(),params:S.loose().optional()}),w=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),I=m({icons:_(w).optional()}),U=m({name:d(),title:d().optional()}),O=U.extend({...U.shape,...I.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),H=jn(m({applyDefaults:A().optional()}),t),F=zo(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,jn(m({form:H.optional(),url:t.optional()}),t.optional())),ee=q({list:t.optional(),cancel:t.optional(),requests:q({sampling:q({createMessage:t.optional()}).optional(),elicitation:q({create:t.optional()}).optional()}).optional()}),G=q({list:t.optional(),cancel:t.optional(),requests:q({tools:q({call:t.optional()}).optional()}).optional()}),V=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:F.optional(),roots:m({listChanged:A().optional()}).optional(),tasks:ee.optional(),extensions:T(d(),t).optional()}),Ge=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:A().optional()}).optional(),resources:m({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:m({listChanged:A().optional()}).optional(),tasks:G.optional(),extensions:T(d(),t).optional()}),oe=m({progress:b(),total:z(b()),message:z(d())}),je=m({...S.shape,...oe.shape,progressToken:r}),L=k.extend({method:g("notifications/progress"),params:je}),Ue=S.extend({level:c,logger:d().optional(),data:M()}),Br=k.extend({method:g("notifications/message"),params:Ue}),Vt=m({uri:d(),mimeType:z(d()),_meta:T(d(),M()).optional()}),st=Vt.extend({text:d()}),Ct=Vt.extend({blob:a}),De=m({audience:_(i).optional(),priority:b().min(0).max(1).optional(),lastModified:Nn.datetime({offset:!0}).optional()}),it=m({...U.shape,...I.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:De.optional(),_meta:z(q({}))}),Kt=m({...U.shape,...I.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:De.optional(),_meta:z(q({}))}),Je=k.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ve=S.extend({uri:d()}),Wt=k.extend({method:g("notifications/resources/updated"),params:Ve}),Zt=m({name:d(),description:z(d()),required:z(A())}),Tt=m({...U.shape,...I.shape,description:z(d()),arguments:z(_(Zt)),_meta:z(q({}))}),Yt=k.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),$e=m({type:g("text"),text:d(),annotations:De.optional(),_meta:T(d(),M()).optional()}),Oe=m({type:g("image"),data:a,mimeType:d(),annotations:De.optional(),_meta:T(d(),M()).optional()}),kt=m({type:g("audio"),data:a,mimeType:d(),annotations:De.optional(),_meta:T(d(),M()).optional()}),Fr=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),Gr=m({type:g("resource"),resource:E([st,Ct]),annotations:De.optional(),_meta:T(d(),M()).optional()}),Jr=it.extend({type:g("resource_link")}),at=E([$e,Oe,kt,Jr,Gr]),Xt=m({role:i,content:at}),Et=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),Vr=k.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),Kr=m({name:d().optional()}),Wr=m({hints:_(Kr).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Zr=m({mode:j(["auto","required","none"]).optional()}),Yr=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),Xr=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),Qr=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),en=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),tn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),rn=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),nn=E([en,tn]),on=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),sn=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),an=E([on,sn]),cn=E([rn,nn,an]),dn=E([cn,Yr,Xr,Qr]),Pt=y.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),dn),required:_(d()).optional()}).catchall(M())}),At=m({type:g("ref/resource"),uri:d()}),xt=m({type:g("ref/prompt"),name:d()}),un=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),ct=V.shape,ln=m({experimental:ct.experimental,sampling:ct.sampling,elicitation:ct.elicitation,roots:ct.roots,extensions:ct.extensions}),Pe=Ge.shape,Qt=m({experimental:Pe.experimental,logging:Pe.logging,completions:Pe.completions,prompts:Pe.prompts,resources:Pe.resources,tools:Pe.tools,extensions:Pe.extensions}),er=q({progressToken:r.optional(),[ur]:d(),[Dn]:O.optional(),[pr]:ln,[$n]:c.optional()}),Ut=m({...U.shape,...I.shape,description:d().optional(),inputSchema:q({$schema:d().optional(),type:g("object")}),outputSchema:q({$schema:d().optional()}).optional(),annotations:Et.optional(),_meta:T(d(),M()).optional()}),pn=m({type:g("tool_result"),toolUseId:d(),content:_(at),structuredContent:M().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),tr=E([$e,Oe,kt,Fr,pn]),Ot=m({role:i,content:E([tr,_(tr)]),_meta:T(d(),M()).optional()}),rr=d(),nr=q({[lr]:O.optional().catch(void 0)}),or=nr.optional();function ae(Z){return q({_meta:or,resultType:rr.default("complete"),...Z})}n(ae,"wireResult");let mn=ae({}),go=ae({nextCursor:o.optional()}),sr=ae({content:_(at),structuredContent:M().optional(),isError:A().optional()}),hn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Ut),nextCursor:o.optional()}),fn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Tt),nextCursor:o.optional()}),gn=ae({description:d().optional(),messages:_(Xt)}),yn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(it),nextCursor:o.optional()}),Sn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Kt),nextCursor:o.optional()}),_n=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([st,Ct]))}),wn=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:A().optional()}).loose()}),yo=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"])}),Rn=ae({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Qt,instructions:d().optional()}),dt=m({messages:_(Ot),modelPreferences:Wr.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Ut).optional(),toolChoice:Zr.optional()}),bn=m({method:g("sampling/createMessage"),params:dt}),vn=m({method:g("roots/list"),params:m({_meta:T(d(),M()).optional()}).optional()}),In=m({...Ot.shape,model:d(),stopReason:d().optional()}),Cn=m({roots:_(un)}),Tn=m({action:j(["accept","decline","cancel"]),content:T(d(),E([d(),b(),A(),_(d())])).optional()}),kn=m({mode:g("url"),message:d(),url:d().url()}),En=E([Pt,kn]),Pn=m({method:g("elicitation/create"),params:En}),An=E([bn,vn,Pn]),xn=E([In,Cn,Tn]),Un=T(d(),An),On=T(d(),xn),Mt=ae({inputRequests:Un.optional(),requestState:d().optional()}),zt={inputResponses:On.optional(),requestState:d().optional()},So=m({_meta:er,...zt}),_o=q({progressToken:r.optional()});function Re(Z,Nt){return m({method:g(Z),params:m({_meta:er,...Nt})})}n(Re,"wireRequest");function be(Z,Nt){return m({method:g(Z),params:m({_meta:_o.optional(),...Nt}).optional()})}n(be,"dispatchRequest");let Mn={name:d(),arguments:T(d(),M()).optional(),...zt},Me={cursor:o.optional()},wo=Re("tools/call",Mn),Ro=Re("tools/list",Me),bo=Re("prompts/list",Me),vo=Re("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...zt}),Io=Re("resources/list",Me),Co=Re("resources/templates/list",Me),To=Re("resources/read",{uri:d(),...zt}),zn={ref:E([xt,At]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},ko=Re("completion/complete",zn),Eo=Re("server/discover",{}),ir=m({toolsListChanged:A().optional(),promptsListChanged:A().optional(),resourcesListChanged:A().optional(),resourceSubscriptions:_(d()).optional()}),qn={notifications:ir},Po=Re("subscriptions/listen",qn),Ao=nr.extend({"io.modelcontextprotocol/subscriptionId":s}),xo=q({_meta:Ao,resultType:rr.default("complete")}),ut={"tools/call":be("tools/call",Mn),"tools/list":be("tools/list",Me),"prompts/get":be("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":be("prompts/list",Me),"resources/list":be("resources/list",Me),"resources/templates/list":be("resources/templates/list",Me),"resources/read":be("resources/read",{uri:d()}),"completion/complete":be("completion/complete",zn),"server/discover":be("server/discover",{}),"subscriptions/listen":be("subscriptions/listen",qn)};function fe(Z){return q({_meta:or,...Z})}n(fe,"liftedResult");let Uo={"tools/call":fe({content:_(at),structuredContent:M().optional(),isError:A().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Ut),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Xt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Tt),nextCursor:o.optional()}),"resources/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(it),nextCursor:o.optional()}),"resources/templates/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Kt),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([st,Ct]))}),"completion/complete":fe({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:A().optional()}).loose()}),"server/discover":fe({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Qt,instructions:d().optional()}),"subscriptions/listen":fe({})},qt=q({"io.modelcontextprotocol/subscriptionId":s.optional()}),ar=m({method:g("notifications/subscriptions/acknowledged"),params:m({_meta:qt.optional(),notifications:ir})}),cr=m({_meta:qt.optional(),requestId:s,reason:d().optional()}),dr=m({method:g("notifications/cancelled"),params:cr}),zs={"notifications/cancelled":dr,"notifications/progress":L,"notifications/message":Br,"notifications/resources/updated":Wt,"notifications/resources/list_changed":Je,"notifications/tools/list_changed":Vr,"notifications/prompts/list_changed":Yt,"notifications/subscriptions/acknowledged":ar},ge=n(Z=>m({jsonrpc:g("2.0"),id:E([d(),b().int()]),result:Z}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:c,TaskMetadataSchema:u,RelatedTaskMetadataSchema:p,RequestMetaSchema:h,BaseRequestParamsSchema:f,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:S,NotificationSchema:k,IconSchema:w,IconsSchema:I,BaseMetadataSchema:U,ImplementationSchema:O,ClientTasksCapabilitySchema:ee,ServerTasksCapabilitySchema:G,ClientCapabilitiesSchema:V,ServerCapabilitiesSchema:Ge,ProgressSchema:oe,ProgressNotificationParamsSchema:je,ProgressNotificationSchema:L,LoggingMessageNotificationParamsSchema:Ue,LoggingMessageNotificationSchema:Br,ResourceContentsSchema:Vt,TextResourceContentsSchema:st,BlobResourceContentsSchema:Ct,AnnotationsSchema:De,ResourceSchema:it,ResourceTemplateSchema:Kt,ResourceListChangedNotificationSchema:Je,ResourceUpdatedNotificationParamsSchema:Ve,ResourceUpdatedNotificationSchema:Wt,PromptArgumentSchema:Zt,PromptSchema:Tt,PromptListChangedNotificationSchema:Yt,TextContentSchema:$e,ImageContentSchema:Oe,AudioContentSchema:kt,ToolUseContentSchema:Fr,EmbeddedResourceSchema:Gr,ResourceLinkSchema:Jr,ContentBlockSchema:at,PromptMessageSchema:Xt,ToolAnnotationsSchema:Et,ToolListChangedNotificationSchema:Vr,ModelHintSchema:Kr,ModelPreferencesSchema:Wr,ToolChoiceSchema:Zr,BooleanSchemaSchema:Yr,StringSchemaSchema:Xr,NumberSchemaSchema:Qr,UntitledSingleSelectEnumSchemaSchema:en,TitledSingleSelectEnumSchemaSchema:tn,LegacyTitledEnumSchemaSchema:rn,SingleSelectEnumSchemaSchema:nn,UntitledMultiSelectEnumSchemaSchema:on,TitledMultiSelectEnumSchemaSchema:sn,MultiSelectEnumSchemaSchema:an,EnumSchemaSchema:cn,PrimitiveSchemaDefinitionSchema:dn,ElicitRequestFormParamsSchema:Pt,ResourceTemplateReferenceSchema:At,PromptReferenceSchema:xt,RootSchema:un,ClientCapabilities2026Schema:ln,ServerCapabilities2026Schema:Qt,RequestMetaEnvelopeSchema:er,ToolSchema:Ut,ToolResultContentSchema:pn,SamplingMessageContentBlockSchema:tr,SamplingMessageSchema:Ot,ResultTypeSchema:rr,ResultMetaSchema:nr,ResultSchema:mn,PaginatedResultSchema:go,CallToolResultSchema:sr,ListToolsResultSchema:hn,ListPromptsResultSchema:fn,GetPromptResultSchema:gn,ListResourcesResultSchema:yn,ListResourceTemplatesResultSchema:Sn,ReadResourceResultSchema:_n,CompleteResultSchema:wn,CacheableResultSchema:yo,DiscoverResultSchema:Rn,CreateMessageRequestParamsSchema:dt,CreateMessageRequestSchema:bn,ListRootsRequestSchema:vn,CreateMessageResultSchema:In,ListRootsResultSchema:Cn,ElicitResultSchema:Tn,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:En,ElicitRequestSchema:Pn,InputRequestSchema:An,InputResponseSchema:xn,InputRequestsSchema:Un,InputResponsesSchema:On,InputRequiredResultSchema:Mt,InputResponseRequestParamsSchema:So,CallToolRequestSchema:wo,ListToolsRequestSchema:Ro,ListPromptsRequestSchema:bo,GetPromptRequestSchema:vo,ListResourcesRequestSchema:Io,ListResourceTemplatesRequestSchema:Co,ReadResourceRequestSchema:To,CompleteRequestSchema:ko,DiscoverRequestSchema:Eo,SubscriptionFilterSchema:ir,SubscriptionsListenRequestSchema:Po,SubscriptionsListenResultMetaSchema:Ao,SubscriptionsListenResultSchema:xo,dispatchRequestSchemas:ut,dispatchResultSchemas:Uo,NotificationMetaSchema:qt,SubscriptionsAcknowledgedNotificationSchema:ar,CancelledNotificationParamsSchema:cr,CancelledNotificationSchema:dr,notificationSchemas2026:zs,JSONRPCResultResponseSchema:ge(mn),CallToolResultResponseSchema:ge(E([sr,Mt])),ListToolsResultResponseSchema:ge(hn),ListPromptsResultResponseSchema:ge(fn),GetPromptResultResponseSchema:ge(E([gn,Mt])),ListResourcesResultResponseSchema:ge(yn),ListResourceTemplatesResultResponseSchema:ge(Sn),ReadResourceResultResponseSchema:ge(E([_n,Mt])),CompleteResultResponseSchema:ge(wn),DiscoverResultResponseSchema:ge(Rn)}}n(hy,"build");var fy;function ht(){return fy??=hy()}n(ht,"buildSchemas2026");var gy=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function yy(e){return gy.includes(e)}n(yy,"isCacheableResultMethod");var Ri=Symbol("modelcontextprotocol.resultCacheHintFallback");function Sy(e){return e[Ri]}n(Sy,"cacheHintFallbackOf");function Yl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(Yl,"isValidCacheTtlMs");function Xl(e){return e==="public"||e==="private"}n(Xl,"isValidCacheScope");var P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),ie=class Ql extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ie(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 Ie(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",Ht(this,new.target)}static fromError(t,r,o){if(t===P.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new as(s.elicitations,r)}if(t===P.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new tp({supported:s.supported,requested:s.requested},r)}if(t===P.InvalidParams||t===P.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===P.ResourceNotFound||Object.keys(s).length===1))return new ep(s.uri,r)}if(t===P.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new rp({requiredCapabilities:s.requiredCapabilities},r)}return new Ql(t,r,o)}},ep=class extends ie{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(P.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},as=class extends ie{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(P.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},tp=class extends ie{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(P.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},rp=class extends ie{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(P.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},_y=0,wy="private",Ry=["tools/call","prompts/get","resources/read"];function by(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Ry.includes(e))return t;throw new ie(P.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(by,"stampResultType");function vy(e,t){let r=Sy(t);if(t.resultType!=="complete"||!yy(e))return r===void 0?t:Ey(t);let o=t,s=Yl(o.ttlMs)?o.ttlMs:Ty(r),i=Xl(o.cacheScope)?o.cacheScope:ky(r),c={...o,ttlMs:s,cacheScope:i};return delete c[Ri],c}n(vy,"fillCacheFields");function Iy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Iy,"isPlainObject$3");function Cy(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[lr]:t}}:!Iy(r)||r[lr]!==void 0?e:{...e,_meta:{...r,[lr]:t}}}n(Cy,"stampServerInfoMeta");function Ty(e){return e!==void 0&&Yl(e.ttlMs)?e.ttlMs:_y}n(Ty,"resolveTtlMs");function ky(e){return e!==void 0&&Xl(e.cacheScope)?e.cacheScope:wy}n(ky,"resolveCacheScope");function Ey(e){let t={...e};return delete t[Ri],t}n(Ey,"stripCacheHintFallback");var Py=["elicitation/create","sampling/createMessage","roots/list"],ns;function bi(){if(ns)return ns;let e=ht();return ns={request:{"elicitation/create":m({method:g("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:g("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:g("roots/list"),params:q({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ns}n(bi,"inputSchemaMaps");function Ay(){bi()}n(Ay,"warmInputSchemaMaps2026");function np(e){return Py.includes(e)}n(np,"isInputRequestMethod2026");function ci(e){return np(e)?bi().request[e]:void 0}n(ci,"getInputRequestSchema2026");function xy(e){return np(e)?bi().response[e]:void 0}n(xy,"getInputResponseSchema2026");var vi={"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},op={"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 sp(e){return Object.prototype.hasOwnProperty.call(vi,e)}n(sp,"hasRequestMethod2026");function ip(e){return Object.prototype.hasOwnProperty.call(op,e)}n(ip,"hasNotificationMethod2026");function Uy(e){return Object.prototype.hasOwnProperty.call(vi,e)}n(Uy,"hasResultMethod2026");function Oy(e){return sp(e)?ht().dispatchRequestSchemas[e]:void 0}n(Oy,"getRequestSchema2026");function My(e){return Uy(e)?ht().dispatchResultSchemas[e]:void 0}n(My,"getResultSchema2026");function zy(e){return ip(e)?ht().notificationSchemas2026[e]:void 0}n(zy,"getNotificationSchema2026");var MT=Object.keys(vi),zT=Object.keys(op);function Zn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Zn,"isPlainObject$2");function Kn(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(Kn,"triState");var qy={ok:!1,reason:"not-in-era"},Ny=[ur,pr];function jy(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(a=>Zn(a)&&"execution"in a)&&(s().tools=i.map(a=>{if(!Zn(a)||!("execution"in a))return a;let u={...a};return delete u.execution,u}));let c=t.capabilities;if(Zn(c)&&"tasks"in c){let a={...c};delete a.tasks,s().capabilities=a}return r}n(jy,"enforceDeletedFields");var Ii={era:"2026-07-28",hasRequestMethod:sp,hasNotificationMethod:ip,hasInputRequestMethod:n(e=>ci(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>Kn(Oy(e),t),"validateRequest"),validateResult:n((e,t)=>Kn(My(e),t),"validateResult"),validateNotification:n((e,t)=>Kn(zy(e),t),"validateNotification"),validateInputRequest:n((e,t)=>Kn(ci(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>Kn(xy(e),t),"validateInputResponse"),samplingResultVariant:n(()=>qy,"samplingResultVariant"),outboundEnvelope(e){return{[ur]:e.protocolVersion,[Dn]:e.clientInfo,[pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[$n]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Ny)o in e||t.push({key:o,problem:"missing"});let r=ht().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(c=>c.key===i&&c.problem==="missing")||t.push({key:i,problem:o.message})}return t},projectCallToolResult:n(e=>Fl(e),"projectCallToolResult"),inputRequestSchema:ci,decodeResult(e,t){if(!Zn(t))return{kind:"invalid",error:new re(se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new re(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 re(se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let c=t.inputRequests,a=Zn(c)?c:{},u=t.requestState;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new re(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:a,...typeof u=="string"&&{requestState:u}}}if(r!=="complete")return{kind:"invalid",error:new re(se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=ap(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let c=s.safeParse(t);if(!c.success)return{kind:"invalid",error:new re(se.InvalidResult,`Invalid result for ${e}: ${c.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return Cy(vy(e,by(e,jy(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=ht().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("; ")}`}},os;function ap(){if(os)return os;let e=ht();return os={"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},os}n(ap,"getWireResultSchemas");function Dy(){ap()}n(Dy,"warmWireResultSchemas2026");var Ci="2026-07-28";function Xn(e){return e!==void 0&&Bl(e)?Ii:wi}n(Xn,"codecForVersion");function zl(e){return e.revision!==void 0?Xn(e.revision).era:e.era==="modern"?Ii.era:wi.era}n(zl,"classifiedWireEra");function di(e){return cp.some(t=>t.hasRequestMethod(e))}n(di,"isSpecRequestMethod");function ui(e){return cp.some(t=>t.hasNotificationMethod(e))}n(ui,"isSpecNotificationMethod");var cp=[wi,Ii],$y=Pl({AnnotationsSchema:n(()=>Dc,"AnnotationsSchema"),AudioContentSchema:n(()=>Sd,"AudioContentSchema"),BaseMetadataSchema:n(()=>yc,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>nc,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>Nc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Gs,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>Od,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Md,"CallToolRequestSchema"),CallToolResultSchema:n(()=>xd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>ku,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>Eu,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>mc,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>hc,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Rc,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>Au,"ClientNotificationSchema"),ClientRequestSchema:n(()=>Pu,"ClientRequestSchema"),ClientResultSchema:n(()=>xu,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>_c,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>Ud,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>cu,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>du,"CompleteRequestSchema"),CompleteResultSchema:n(()=>uu,"CompleteResultSchema"),ContentBlockSchema:n(()=>bd,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Kd,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Wd,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Zd,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>Yd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Su,"CreateTaskResultSchema"),CursorSchema:n(()=>Qa,"CursorSchema"),DiscoverRequestSchema:n(()=>kc,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Bs,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>$o,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>tu,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>ru,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Lo,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>su,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>nu,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>ou,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>wd,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>pc,"EmptyResultSchema"),EnumSchemaSchema:n(()=>eu,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>hd,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>fd,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>Id,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>vu,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>Iu,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Ru,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>bu,"GetTaskResultSchema"),IconSchema:n(()=>fc,"IconSchema"),IconsSchema:n(()=>gc,"IconsSchema"),ImageContentSchema:n(()=>yd,"ImageContentSchema"),ImplementationSchema:n(()=>Sc,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>bc,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>vc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>Cc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>Tc,"InitializedNotificationSchema"),JSONArraySchema:n(()=>Ya,"JSONArraySchema"),JSONObjectSchema:n(()=>Za,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Ln,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>Hs,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>$s,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Dt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>lc,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Ls,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Wa,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Ks,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>Fs,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>pd,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>md,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>Fc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>Gc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Hc,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Bc,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>pu,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>mu,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>Cu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>Tu,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>Pd,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>Ad,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>qd,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Dd,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>$d,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Ld,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Hd,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Qd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>ac,"NotificationSchema"),NotificationsParamsSchema:n(()=>ic,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>Do,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>Uc,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>Oc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Mc,"PaginatedResultSchema"),PingRequestSchema:n(()=>Ec,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>Ys,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>Ac,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>xc,"ProgressNotificationSchema"),ProgressSchema:n(()=>Pc,"ProgressSchema"),ProgressTokenSchema:n(()=>Xa,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>ud,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>Cd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>vd,"PromptMessageSchema"),PromptReferenceSchema:n(()=>au,"PromptReferenceSchema"),PromptSchema:n(()=>ld,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Vc,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Kc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Wc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>tc,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>uc,"RequestIdSchema"),RequestMetaSchema:n(()=>rc,"RequestMetaSchema"),RequestSchema:n(()=>sc,"RequestSchema"),ResourceContentsSchema:n(()=>zc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Rd,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Zc,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Jc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>$c,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>iu,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Lc,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>cd,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>dd,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>cc,"ResultMetaObjectSchema"),ResultSchema:n(()=>dc,"ResultSchema"),RoleSchema:n(()=>jc,"RoleSchema"),RootSchema:n(()=>lu,"RootSchema"),RootsListChangedNotificationSchema:n(()=>hu,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>Gd,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Jd,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Vd,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>Ic,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>Ou,"ServerNotificationSchema"),ServerRequestSchema:n(()=>Uu,"ServerRequestSchema"),ServerResultSchema:n(()=>Mu,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>wc,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>Nd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>jd,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Xd,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>jo,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>Yc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Xc,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>td,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>od,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>sd,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>rd,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>nd,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>id,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>ad,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>oc,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>fu,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>ec,"TaskMetadataSchema"),TaskSchema:n(()=>yu,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>_u,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>wu,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>gu,"TaskStatusSchema"),TextContentSchema:n(()=>gd,"TextContentSchema"),TextResourceContentsSchema:n(()=>qc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Zs,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Vs,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>Td,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Bd,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>kd,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>zd,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>Fd,"ToolResultContentSchema"),ToolSchema:n(()=>Ed,"ToolSchema"),ToolUseContentSchema:n(()=>_d,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Qc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>ed,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ws,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Js,"UntitledSingleSelectEnumSchemaSchema")});var dp=n(e=>Dt.safeParse(e).success,"isJSONRPCRequest"),up=n(e=>$s.safeParse(e).success,"isJSONRPCNotification"),fi=n(e=>Ls.safeParse(e).success,"isJSONRPCResultResponse"),lp=n(e=>Ln.safeParse(e).success,"isJSONRPCErrorResponse");var Yn=-32020,qT=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[P.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Yn,P.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[P.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[P.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[P.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Yn],conformance:["http-header-validation"],rationale:"SEP-2243 standard `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 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. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[P.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Yn],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."}],NT={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Yn]:400};function Ti(e,t){return Ha(e,t)}n(Ti,"parseSchema");function Wn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Wn,"shapeKeys");function gi(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}n(gi,"isStandardSchema");var ql=!1,yi="draft-2020-12";function Ly(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:yi});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().");ql||(ql=!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=qs(e,{target:yi,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:pp(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(Ly,"standardSchemaToJsonSchema");function pp(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"||pp(o)))}return!1}n(pp,"isProvablyObjectShapedRoot");function Hy(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Hy,"formatIssue");async function li(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Hy(o)).join(", ")}:{success:!0,data:r.value}}n(li,"validateStandardSchema");function By(e){let t=qs(e,{target:yi,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(By,"zodEmittedPattern");var Fy=/\\\.\\d\{(\d+)\}/;function Gy(e){let t=Fy.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=>Nn.datetime({local:o,offset:s,precision:i}))))}n(Gy,"datetimeReferenceSchemas");function Jy(e,t){let r;switch(e){case"email":r=[Ba()];break;case"uri":r=[Fa()];break;case"date":r=[Nn.date()];break;case"date-time":r=Gy(t);break}return new Set(r.map(o=>By(o)).filter(o=>o!==void 0))}n(Jy,"referencePatternsForFormat");function Vy(e,t,r){return r!=="zod"?!0:Jy(e,t).has(t)}n(Vy,"isLibraryFormatPattern");function Qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Qn,"isJsonObject");function Ky(e){try{return Ly(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ie(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(Ky,"convertStandardElicitationSchema");var Wy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function ki(e){return Wy.has(e)||e.startsWith("x-")}n(ki,"isAnnotationOnlyJsonSchemaKeyword");var Zy=new Set(["$schema",...Object.keys($o.shape.requestedSchema.shape)]),Nl={string:Wn([jo,Js,Vs,Ks]),number:Wn([Do]),integer:Wn([Do]),boolean:Wn([Gs]),array:Wn([Ws,Zs])},Yy=new Set(jo.shape.format.unwrap().options);function Xy(e,t,r,o){if(!Qn(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Nl,e.type)?Nl[e.type]:void 0;if(s===void 0)return e;let i={};for(let[c,a]of Object.entries(e))s.has(c)||ki(c)?i[c]=a:c==="pattern"&&e.type==="string"&&typeof e.format=="string"?Yy.has(e.format)?(typeof a!="string"||!Vy(e.format,a,r))&&o.push(`${t}.${c}`):i[c]=a:o.push(`${t}.${c}`);return i}n(Xy,"walkProperty");function Qy(e,t){let r={},o=[];for(let[s,i]of Object.entries(e))s==="properties"&&Qn(i)?r[s]=Object.fromEntries(Object.entries(i).map(([c,a])=>[c,Xy(a,`properties.${c}`,t,o)])):Zy.has(s)?r[s]=i:ki(s)||o.push(s);if(o.length>0)throw new ie(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(Qy,"walkRequestedSchema");function eS(e,t){if(!Qn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Ti(Ys,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(eS,"describeUnsupportedProperties");function Si(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Si(o,t[s],`${r}[${s}]`)):!Qn(e)||!Qn(t)?[]:Object.entries(e).flatMap(([o,s])=>{let i=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Si(s,t[o],i):ki(o)?[]:[i]})}n(Si,"findDroppedConstraintPaths");function tS(e){if(!gi(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Qy(Ky(e.requestedSchema),t),o=Ti($o.shape.requestedSchema,r);if(!o.success)throw new ie(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${eS(r,o.error.message)}`);let s=Si(r,o.data);if(s.length>0)throw new ie(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(o.data.required??[]).filter(c=>!Object.prototype.hasOwnProperty.call(o.data.properties,c));if(i.length>0)throw new ie(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(tS,"normalizeElicitInputParams");function rS(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(rS,"buildInputRequired");var jT=Object.assign(rS,{elicit(e){try{return{method:"elicitation/create",params:tS(e)}}catch(t){throw t instanceof ie?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 nS=["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"],oS={IdJagTokenExchangeResponseSchema:Xs,OAuthClientInformationFullSchema:$t,OAuthClientInformationSchema:Hn,OAuthClientMetadataSchema:qu,OAuthClientRegistrationErrorSchema:Nu,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:fr,OAuthProtectedResourceMetadataSchema:hr,OAuthTokenRevocationRequestSchema:ju,OAuthTokensSchema:lt,OpenIdProviderDiscoveryMetadataSchema:gr,OpenIdProviderMetadataSchema:zu},mp={},hp={};function fp(e,t){let r=e.slice(0,-6);mp[r]=t,hp[r]=o=>t.safeParse(o).success}n(fp,"register");for(let e of nS)fp(e,$y[e]);for(let[e,t]of Object.entries(oS))fp(e,t);var sS=Object.freeze(mp),iS=Object.freeze(hp);function aS(e){switch(e){case"initialize":case"notifications/initialized":return Xn(void 0);case"server/discover":return Xn(Ci);default:return}}n(aS,"bootstrapOutboundCodec");var gp=6e4,cS=[ur,Dn,pr,$n],dS=["inputResponses","requestState"];function jl(e,t){let r=e.params;if(!pi(r))return{message:e,lifted:{}};let o=r._meta,s=pi(o)?cS.filter(u=>u in o):[],i=t==="request"?dS.filter(u=>u in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let c={},a={...r};if(s.length>0&&pi(o)){let u={},p={...o};for(let h of s)u[h]=o[h],delete p[h];c.envelope=u,Object.keys(p).length>0?a._meta=p:delete a._meta}for(let u of i)u==="inputResponses"&&(c.inputResponses=a[u]),u==="requestState"&&(c.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:c}}n(jl,"liftWireOnlyMaterial");function Dl(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(Dl,"codecResultValidator");function yp(e){return()=>e}n(yp,"requestStateAccessor");var uS=yp(void 0),lS,pS=class{static{n(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{lS=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ds,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 re(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&&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 re(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 o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),fi(s)||lp(s)?this._onresponse(s):dp(s)?this._onrequest(s,i):up(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 re(se.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}=jl(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let c=zl(t.classification);if(c!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${c} but this instance serves ${o.era}`));return}}if(ui(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(c=>this._onerror(new Error(`Uncaught error in notification handler: ${c}`)))}_onrequest(e,t){let{message:r,lifted:o}=jl(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,c=n((w,I,U)=>{let O={jsonrpc:"2.0",id:r.id,error:{code:w,message:I,...U!==void 0&&{data:U}}};i?.send(O).catch(H=>this._onerror(new Error(`Failed to send an error response: ${H}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=zl(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 I=t.classification.revision??w;c(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${I}`,{supported:this._supportedProtocolVersions,requested:I});return}}if(di(r.method)&&!s.hasRequestMethod(r.method)){c(P.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){c(P.MethodNotFound,"Method not found");return}let u=s.checkInboundEnvelope(o);if(u!==void 0){c(P.InvalidParams,u);return}let p=n((w,I)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...I,relatedRequestId:r.id}),"sendNotification"),h=n((w,I,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,I,{...U,relatedRequestId:r.id}),"sendRequest"),f=new AbortController;this._requestHandlerAbortControllers.set(r.id,f);let y=o.inputResponses===void 0?void 0:mS(o.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:o.requestState===void 0?uS:yp(o.requestState),signal:f.signal,send:n(((w,I,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),gi(I))return h(w,I,U);let H=Dl(O,w.method);if(H===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 h(w,H,I)}),"send"),notify:p},http:t?.authInfo?{authInfo:t.authInfo}:void 0},k=this.buildContext(S,t);Promise.resolve().then(()=>a(r,k)).then(async w=>{if(f.signal.aborted)return;let I;try{I=s.encodeResult(r.method,w,this._outboundServerInfo())}catch(O){this._onerror(new Error(`Failed to encode result for ${r.method}: ${O}`)),c(P.InternalError,"Internal error");return}let U={result:I,jsonrpc:"2.0",id:r.id};await i?.send(U)},async w=>{if(f.signal.aborted)return;let I=Number.isSafeInteger(w.code)?w.code:P.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(I),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await i?.send(U)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===f&&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),c=this._timeoutInfo.get(o);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),fi(e)?r(e):r(ie.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(this._assertOutboundRequestInEra(o,e.method),gi(t))return this._requestWithSchemaViaCodec(o,e,t,r);let s=Dl(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 Xn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=aS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(di(t)&&!e.hasRequestMethod(t))throw new re(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 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:c,headers:a}=o??{},u=Date.now(),p,h;return new Promise((f,y)=>{let S=n(G=>{y(G)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(G){S(G);return}if(o?.signal?.aborted){let G=o.signal.reason;throw G instanceof re?G:new re(se.RequestTimeout,String(G))}let k=e.era===Ci&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;h=w;let I={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),I.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let U=this._envelopeOutbound(I),O=!1,H=n(G=>{O||(this._progressHandlers.delete(w),k===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(G)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),y(G instanceof re?G:new re(se.RequestTimeout,String(G))))},"cancel");this._responseHandlers.set(w,G=>{if(o?.signal?.aborted)return;if(O=!0,G instanceof Error)return y(G);let V;try{V=e.decodeResult(t.method,G.result)}catch(oe){return y(oe instanceof Error?oe:new Error(String(oe)))}if(V.kind==="invalid")return y(V.error);if(V.kind==="input_required"){if(o?.allowInputRequired===!0)return f(hS(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((je,L)=>this._requestWithSchemaViaCodec(e,je===void 0?{method:t.method}:{method:t.method,params:je},r,L),"retry")};return f(this._resolveNonCompleteResult(V,oe))}let Ge=V.result;li(r,Ge).then(oe=>{oe.success?f(oe.data):y(new re(se.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},y)}),p=n(()=>H(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??gp,ee=n(()=>H(new re(se.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,ee,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c,headers:a,requestSignal:k?.signal}).catch(G=>{this._progressHandlers.delete(w),y(G)})}).finally(()=>{p&&o?.signal?.removeEventListener("abort",p),h!==void 0&&(this._responseHandlers.delete(h),this._cleanupTimeout(h))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new re(se.NotConnected,"Not connected");if(ui(t.method)&&!e.hasNotificationMethod(t.method))throw new re(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 o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,r).catch(s=>this._onerror(s))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!di(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((s,i)=>{let c=this._negotiatedWireCodec(),a=c.validateRequest(e,s);if(!a.ok&&a.reason==="not-in-era"&&(a=c.validateInputRequest(e,s)),!a.ok)throw a.reason==="not-in-era"?new ie(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,i))},"stored")}else if(r)o=n(async(s,i)=>{let c=await li(t.params,{...s.params});if(!c.success)throw new ie(P.InvalidParams,`Invalid params for ${e}: ${c.error}`);return r(c.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.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(!ui(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 ie(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await li(t.params,{...o.params});if(!s.success)throw new ie(P.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function pi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(pi,"isPlainObject$1");function $l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n($l,"isPlainObject");function mS(e){let t={},r=[];if(!$l(e))return{accepted:t,droppedKeys:r};for(let[o,s]of Object.entries(e)){if(!$l(s)||"method"in s||"result"in s){r.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:r}}n(mS,"partitionInputResponses");function hS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(hS,"manualInputRequiredValue");var fS=El((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(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?i(a):a;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var p=u.indexOf(";"),h=p!==-1?u.slice(0,p).trim():u.trim();if(!o.test(h))throw new TypeError("invalid media type");var f=new c(h.toLowerCase());if(p!==-1){var y,S,k;for(t.lastIndex=p;S=t.exec(u);){if(S.index!==p)throw new TypeError("invalid parameter format");p+=S[0].length,y=S[1].toLowerCase(),k=S[2],k.charCodeAt(0)===34&&(k=k.slice(1,-1),k.indexOf("\\")!==-1&&(k=k.replace(r,"$1"))),f.parameters[y]=k}if(p!==u.length)throw new TypeError("invalid parameter format")}return f}n(s,"parse");function i(a){var u;if(typeof a.getHeader=="function"?u=a.getHeader("content-type"):typeof a.headers=="object"&&(u=a.headers&&a.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}n(i,"getcontenttype");function c(a){this.parameters=Object.create(null),this.type=a}n(c,"ContentType")})),DT=Al(fS(),1);var gS=10*1024*1024;function Ei(){_i(),ht(),dy(),Ay(),Dy()}n(Ei,"preloadSchemas");var YT=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 yS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,SS=[0,31,28,31,30,31,30,31,31,30,31,30,31],_S=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,wS=/^(?=.{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,RS=/^(?:[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,bS=/^(?:(?:[^\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,vS=/^(?:(?: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,IS=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,CS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,TS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,kS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ES=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"),PS=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,AS=/^((([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,xS=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 He(e){return e.test.bind(e)}n(He,"bind");var XT={date:Sp,time:_p.bind(void 0,!1),"date-time":MS,duration:xS,uri:NS,"uri-reference":He(RS),"uri-template":He(bS),url:He(vS),email:ES,hostname:He(wS),ipv4:He(PS),ipv6:He(AS),regex:DS,uuid:He(IS),"json-pointer":He(CS),"json-pointer-uri-fragment":He(TS),"relative-json-pointer":He(kS)};function US(e){return e%4===0&&(e%100!==0||e%400===0)}n(US,"isLeapYear");function Sp(e){let t=e.match(yS);if(!t)return!1;let r=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o==2&&US(r)?29:SS[o])}n(Sp,"date");function _p(e,t){let r=t.match(_S);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],c=!!r[5];return(o<=23&&s<=59&&i<=59||o==23&&s==59&&i==60)&&(!e||c)}n(_p,"time");var OS=/t|\s/i;function MS(e){let t=e.split(OS);return t.length==2&&Sp(t[0])&&_p(!0,t[1])}n(MS,"date_time");var zS=/\/|:/,qS=/^(?:[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 NS(e){return zS.test(e)&&qS.test(e)}n(NS,"uri");var jS=/[^\\]\\Z/;function DS(e){if(jS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(DS,"regex");Ei();var wp=!1;var Pi;Pi=globalThis.crypto;async function LS(e){return(await Pi).getRandomValues(new Uint8Array(e))}n(LS,"getRandomValues");async function HS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let s=await LS(e-o.length);for(let i of s)i<r&&(o+=t[i%t.length])}return o}n(HS,"random");async function BS(e){return await HS(e)}n(BS,"generateVerifier");async function FS(e){let t=await(await Pi).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(FS,"generateChallenge");async function Ai(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await BS(e),r=await FS(t);return{code_verifier:t,code_challenge:r}}n(Ai,"pkceChallenge");var to=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ie(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 Ie(this,e)}constructor(e){super(e),this.name=new.target.name,Ht(this,new.target)}},eo=class extends to{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}},zi=class extends to{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}},ds=class extends to{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 / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},xi=class extends to{static{n(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},Dk=class extends to{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 Rp(e,t,r){if(e!==void 0)return e.issuer===void 0?(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):Ip(e.issuer,t)?e:void 0}n(Rp,"discardIfIssuerMismatch");function Ip(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(Ip,"issuersMatch");var $k=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ie(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 Ie(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Ht(this,new.target)}};function Cp(e){return e?.authorization_response_iss_parameter_supported===!0}n(Cp,"isIssParameterSupported");function Tp({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new eo("authorization_response",t,void 0);return}if(e!==t)throw new eo("authorization_response",t,e)}}n(Tp,"validateAuthorizationResponseIssuer");function GS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(GS,"isClientAuthMethod");var Ui="code",Oi="S256";function JS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&GS(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(JS,"selectClientAuthMethod");function VS(e,t,r,o){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":KS(s,i,r);return;case"client_secret_post":WS(s,i,o);return;case"none":ZS(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(VS,"applyClientAuthentication");function KS(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(KS,"applyBasicAuth");function WS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(WS,"applyPostAuth");function ZS(e,t){t.set("client_id",e)}n(ZS,"applyPublicAuth");function kp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(kp,"isLoopbackHost");function YS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!kp(t.hostname))throw new ds(t.href);return t}n(YS,"assertSecureTokenEndpoint");function XS(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||kp(r.hostname))return"native"}return"web"}n(XS,"deriveApplicationType");function QS(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??XS(t.redirect_uris)}}n(QS,"resolveClientMetadata");async function bp(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return ft.fromResponse(o)}catch(o){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ft(ue.ServerError,s)}}n(bp,"parseErrorResponse");async function qi(e,t){try{return await Mi(e,t)}catch(r){if(r instanceof ft){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Mi(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await Mi(e,t)}throw r}}n(qi,"auth");function e_(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(e_,"determineScope");async function Mi(e,{serverUrl:t,authorizationCode:r,iss:o,scope:s,resourceMetadataUrl:i,fetchFn:c,skipIssuerMetadataValidation:a,forceReauthorization:u}){let p=QS(e),h=await e.discoveryState?.(),f,y,S,k,w=i;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(y=h.authorizationServerUrl,f=h.resourceMetadata,S=h.authorizationServerMetadata??await xp(y,{fetchFn:c,skipIssuerValidation:a}),!f)try{f=await Pp(t,{resourceMetadataUrl:w},c)}catch(L){if(L instanceof TypeError)throw L}(S!==h.authorizationServerMetadata||f!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S})}else{let L=await i_(t,{resourceMetadataUrl:w,fetchFn:c,skipIssuerMetadataValidation:a});y=L.authorizationServerUrl,S=L.authorizationServerMetadata,f=L.resourceMetadata,k={authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S}}let I=S?.issuer??String(y),U={issuer:I};if(await e.saveAuthorizationServerUrl?.(I),r!==void 0){let L=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if(L===void 0){if(e.saveDiscoveryState!==void 0)throw new xi("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",I);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(!Ip(L,I))throw new xi(L,I)}k&&await e.saveDiscoveryState?.(k);let O=await t_(t,e,f);O&&await e.saveResourceUrl?.(String(O));let H=e_({requestedScope:s,resourceMetadata:f,authServerMetadata:S,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),ee=Rp(F,I,{canPersistStamp:e.saveClientInformation!==void 0});if(ee===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new xi(F.issuer,I);if(ee&&ee.issuer===void 0&&(ee={...ee,issuer:I},await e.saveClientInformation?.(ee,U)),!ee){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let L=S?.client_id_metadata_document_supported===!0,Ue=e.clientMetadataUrl;if(Ue&&!Ni(Ue))throw new ft(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ue}`);if(L&&Ue)ee={client_id:Ue,issuer:I},await e.saveClientInformation?.(ee,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");ee={...await l_(y,{metadata:S,clientMetadata:p,scope:H,fetchFn:c}),issuer:I},await e.saveClientInformation(ee,U)}}let G=!e.redirectUrl;if(r!==void 0||G){r!==void 0&&Tp({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Cp(S)});let L=await u_(e,y,{metadata:S,resource:O,authorizationCode:r,iss:o,scope:H,fetchFn:c});return await e.saveTokens({...L,issuer:I},U),"AUTHORIZED"}let V=Rp(await e.tokens(U),I);if(V&&V.issuer===void 0&&(V={...V,issuer:I},await e.saveTokens(V,U)),V?.refresh_token&&!u)try{let L=await d_(y,{metadata:S,clientInformation:ee,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:c});return await e.saveTokens({...L,issuer:I},U),"AUTHORIZED"}catch(L){if(L instanceof ds||!(!(L instanceof ft)||L.code===ue.ServerError))throw L}let Ge=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:je}=await a_(y,{metadata:S,clientInformation:ee,state:Ge,redirectUrl:e.redirectUrl,scope:H,resource:O});return await e.saveCodeVerifier(je),await e.redirectToAuthorization(oe),"REDIRECT"}n(Mi,"authInternal");function Ni(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Ni,"isHttpsUrl");async function t_(e,t,r){let o=Hl(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ss({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(t_,"selectResourceURL");function Ep(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let s=cs(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let c=cs(e,"scope")||void 0,a=cs(e,"error")||void 0,u=cs(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:c,error:a,errorDescription:u}}n(Ep,"extractWWWAuthenticateParams");function cs(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(cs,"extractFieldFromWwwAuth");async function Pp(e,t,r=fetch){let o=await o_(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 hr.parse(await o.json())}n(Pp,"discoverOAuthProtectedResourceMetadata");async function Ap(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!wp)throw o;if(t)try{return await r(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}n(Ap,"fetchWithCorsRetry");function r_(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(r_,"buildWellKnownPath");async function vp(e,t,r=fetch){return await Ap(e,{"MCP-Protocol-Version":t},r)}n(vp,"tryMetadataDiscovery");function n_(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(n_,"shouldAttemptFallback");async function o_(e,t,r,o){let s=new URL(e),i=o?.protocolVersion??No,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=r_(t,s.pathname);c=new URL(u,o?.metadataServerUrl??s),c.search=s.search}let a=await vp(c,i,r);return!o?.metadataUrl&&n_(a,s.pathname)&&(a=await vp(new URL(`/.well-known/${t}`,s),i,r)),a}n(o_,"discoverMetadataWithFallback");function s_(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(s_,"buildDiscoveryUrls");async function xp(e,{fetchFn:t=fetch,protocolVersion:r=No,skipIssuerValidation:o=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=s_(e);for(let{url:c,type:a}of i){let u=await Ap(c,s,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status>=400&&u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${c}`)}let p=a==="oauth"?fr.parse(await u.json()):gr.parse(await u.json());if(!o){let h=typeof e=="string"?e:e.href;if(!(p.issuer===h||h.endsWith("/")&&p.issuer===h.slice(0,-1)))throw new eo("metadata",h,p.issuer)}return p}}n(xp,"discoverAuthorizationServerMetadata");async function i_(e,t){let r,o;try{r=await Pp(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 xp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:s,resourceMetadata:r}}n(i_,"discoverOAuthServerInfo");async function a_(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:s,state:i,resource:c}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ui))throw new Error(`Incompatible auth server: does not support response type ${Ui}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Oi))throw new Error(`Incompatible auth server: does not support code challenge method ${Oi}`)}else a=new URL("/authorize",e);let u=await Ai(),p=u.code_verifier,h=u.code_challenge;return a.searchParams.set("response_type",Ui),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",Oi),a.searchParams.set("redirect_uri",String(o)),i&&a.searchParams.set("state",i),s&&a.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),c&&a.searchParams.set("resource",c.href),{authorizationUrl:a,codeVerifier:p}}n(a_,"startAuthorization");function c_(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(c_,"prepareAuthorizationCodeRequest");async function Up(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:s,resource:i,fetchFn:c}){let a=YS(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",i.href),s?await s(u,r,a,t):o&&VS(JS(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=await(c??fetch)(a,{method:"POST",headers:u,body:r});if(!p.ok)throw await bp(p);let h=await p.json();try{return lt.parse(h)}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await bp(JSON.stringify(h)):f}}n(Up,"executeTokenRequest");async function d_(e,{metadata:t,clientInformation:r,refreshToken:o,resource:s,addClientAuthentication:i,fetchFn:c}){return{refresh_token:o,...await Up(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:s,fetchFn:c})}}n(d_,"refreshAuthorization");async function u_(e,t,{metadata:r,resource:o,authorizationCode:s,iss:i,scope:c,fetchFn:a}={}){s!==void 0&&Tp({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Cp(r)});let u=c??e.clientMetadata.scope,p;if(e.prepareTokenRequest&&(p=await e.prepareTokenRequest(u)),!p){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");p=c_(s,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return Up(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(u_,"fetchToken");async function l_(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 c={...r,...o===void 0?{}:{scope:o}},a=await(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new zi({status:a.status,body:await a.text(),submittedMetadata:c});return $t.parse(await a.json())}n(l_,"registerClient");var Lk=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ie(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 Ie(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Ht(this,new.target)}};function p_(e){let t=Dt.safeParse(e);return t.success?t.data.id:void 0}n(p_,"parseJsonRpcRequestId");function Op(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return p_(t)}catch{return}}n(Op,"readJsonRpcRequestIdFromBody");function us(e){return Ln.parse({jsonrpc:mr,...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(us,"jsonRpcErrorResponse");function Mp(e){return new as([Lo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Mp,"urlElicitationRequiredError");var ps=l.record(l.string(),l.unknown()),m_=l.record(l.string(),l.unknown()),yt=l.array(l.string().min(1)).min(1).optional(),h_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:m_.optional(),_meta:ps.optional(),roles:yt,groups:yt,public:l.boolean().optional()}).strict(),f_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:ps.optional(),roles:yt,groups:yt,public:l.boolean().optional()}).strict(),g_=l.object({uri:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ps.optional(),roles:yt,groups:yt,public:l.boolean().optional()}).strict(),y_=l.object({uriTemplate:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ps.optional(),roles:yt,groups:yt,public:l.boolean().optional()}).strict(),S_=l.array(l.union([l.string(),h_])),__=l.array(l.union([l.string(),f_])),w_=l.array(l.union([l.string(),g_])),R_=l.array(l.union([l.string(),y_])),b_=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),v_=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:b_.optional()}).strict(),I_=l.object({tools:S_.optional(),prompts:__.optional(),resources:w_.optional(),resourceTemplates:R_.optional(),accessControl:v_.optional()}).strict(),gt=[{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"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function C_(e,t){return Lu(I_,e,`MCP capability filter policy "${t}"`)}n(C_,"parseMcpCapabilityFilterOptions");function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(_e,"isRecord");function ro(e){return typeof e.method=="string"?e.method:void 0}n(ro,"messageMethod");function zp(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(zp,"correlationKey");function qp(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(qp,"asStringArray");function Np(e,t){if(!_e(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,s)=>_e(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(Np,"readClaimValues");function $i(e,t){if(typeof e=="string")return{key:e,public:!1};if(!_e(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:qp(e.roles),groups:qp(e.groups),public:e.public===!0}}n($i,"normalizeEntry");function T_(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(T_,"isCallerAllowed");function ls(e,t,r,o){if(e===void 0)return;let s=[];for(let i of e){let c=$i(i,t);c!==void 0&&T_(c,r,o)&&s.push(c.key)}return s}n(ls,"allowedKeys");var $p=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(Np(e.user?.data,o)),c=new Set(Np(e.user?.data,s));return{tools:ls(r.tools,"name",i,c),prompts:ls(r.prompts,"name",i,c),resources:ls(r.resources,"uri",i,c),resourceTemplates:ls(r.resourceTemplates,"uriTemplate",i,c)}},"claimsCapabilityResolver");function k_(e,t){let r=[];for(let o of gt){let s=e[o.option];if(s!==void 0)for(let i of s){let c=$i(i,o.itemProperty);if(c===void 0)continue;let a=(c.roles?.length??0)>0||(c.groups?.length??0)>0;c.public&&a&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`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(k_,"assertNoConflictingMarkup");function E_(e,t){let r=[];for(let o of gt){let s=e[o.option];if(s!==void 0)for(let i of s){let c=$i(i,o.itemProperty);c!==void 0&&((c.roles?.length??0)>0||(c.groups?.length??0)>0||c.public)&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`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(E_,"assertNoMarkup");function P_(e,t){let r=e.identifier;if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=o;return async(i,c,a)=>{let u=await s(i,c,a);if(u==null)throw new v(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof u!="object"||Array.isArray(u))throw new v(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return u}}n(P_,"buildCustomResolver");function A_(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return P_(r,t)}if(o==="rolesAndGroups")return k_(e,t),$p;E_(e,t)}n(A_,"buildCapabilityResolver");function x_(e){let t={};for(let r of gt){let o=e[r.option];if(o===void 0)continue;let s=new Map;for(let i of o){let c=q_(i,r.itemProperty);c!==void 0&&s.set(c.key,c)}t[r.option]=s}return t}n(x_,"buildProjectionMaps");function ji(e){return e===void 0?void 0:gt.find(t=>t.listMethod===e)}n(ji,"findListRule");function U_(e){return e===void 0?void 0:gt.find(t=>t.directMethods.includes(e))}n(U_,"findDirectRule");function O_(e){switch(e.method){case"tools/call":return{option:"tools",target:e.params.name};case"prompts/get":return{option:"prompts",target:e.params.name};case"resources/read":return{option:"resources",target:e.params.uri};default:return}}n(O_,"directCapabilityAccess");function M_(e){let t=U_(ro(e));if(t===void 0||!_e(e.raw))return;let r=e.raw.params;if(!_e(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(M_,"rawDirectCapabilityAccess");function z_(e){return Response.json(us({...e==null?{}:{id:e},error:{code:P.MethodNotFound,message:"Method not found"}}))}n(z_,"methodNotFoundResponse");function q_(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!_e(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(q_,"buildProjection");function jp(e){let t=e.base[e.property],r=e.overlay[e.property];return _e(r)?_e(t)?{...t,...r}:r:t}n(jp,"mergeRecordProperty");function N_(e,t){let r={...e,...t.overlay},o=jp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let s=jp({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}n(N_,"applyProjection");function Dp(e,t,r,o){if(!_e(e))return e;let s=e.result;if(!_e(s))return e;let i=s[t.resultProperty];return!Array.isArray(i)||!i.every(c=>_e(c)&&typeof c[t.itemProperty]=="string")?e:{...e,result:{...s,[t.resultProperty]:i.flatMap(c=>{if(!_e(c))return[];let a=c[t.itemProperty];if(typeof a!="string")return[];if(o!==void 0&&!o.has(a))return[];let u=r.get(a);return u===void 0?[]:[N_(c,u)]})}}}n(Dp,"filterAndProjectItems");function j_(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:s}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let p of t.messages){let h=ji(ro(p)),f=h===void 0?void 0:zp(p.id);h!==void 0&&f!==void 0&&u.set(f,h)}return u.size===0?r:r.map(p=>{if(!_e(p)||"error"in p)return p;let h=zp(p.id),f=h===void 0?void 0:u.get(h),y=f===void 0?void 0:o[f.option];return f===void 0||y===void 0?p:Dp(p,f,y,s?.[f.option])})}if(t.shape!=="single"||!_e(r)||"error"in r)return r;let i=t.messages[0],c=ji(i===void 0?void 0:ro(i)),a=c===void 0?void 0:o[c.option];return c===void 0||a===void 0?r:Dp(r,c,a,s?.[c.option])}n(j_,"filterResponseBody");function D_(e){return e.headers.get("content-type")?.includes("json")??!1}n(D_,"isJsonResponse");var Di=class extends qo{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=C_(t,r);super(o,r),this.#r=r,this.#e=x_(o),this.#t=A_(o,r)}async handler(t,r){let o=await kl(t);if(o===null)return t;let s=this.#t!==void 0&&this.#n(o)?await this.#s(t,r):void 0;for(let c of o.messages){let a=c.type==="request"?O_(c):M_(c);if(a===void 0)continue;let u=this.#e[a.option];if(u===void 0)continue;let p=s?.[a.option];if(!u.has(a.target)||p!==void 0&&!p.has(a.target))return z_(c.type==="request"?c.id:c.id??void 0)}if(!this.#o(o))return t;let i=this.#e;return r.addResponseSendingHook(async c=>{if(!D_(c))return c;let a;try{a=await c.clone().json()}catch{return c}let u=j_({envelope:o,responseBody:a,projectionMaps:i,allowedSets:s});if(u===a)return c;let p=new Headers(c.headers);return p.delete("content-length"),new Response(JSON.stringify(u),{status:c.status,statusText:c.statusText,headers:p})}),t}#n(t){return t.messages.some(r=>{let o=ro(r);return o===void 0?!1:gt.some(s=>this.#e[s.option]===void 0?!1:s.listMethod===o||s.directMethods.includes(o))})}#o(t){return t.messages.some(r=>{let o=ji(ro(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#s(t,r){let o=this.#t;if(o===void 0)return{};let s;try{s=await o(t,r,this.options)}catch(c){r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; denying configured capabilities`,c);let a={};for(let u of gt)this.#e[u.option]!==void 0&&(a[u.option]=new Set);return a}let i={};for(let c of gt){let a=this.#e[c.option];if(a===void 0)continue;let u=s[c.option];if(u===void 0)continue;let p=new Set;if(Array.isArray(u))for(let h of u)typeof h=="string"&&a.has(h)&&p.add(h);i[c.option]=p}return i}};var Li="zuplo.com",$_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),L_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Lp(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Lp,"s2FaviconHref");function H_(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(H_,"strictFaviconHref");var Hp=Lp(Li);function Hi(e){let t=e.toLowerCase();return t===Li||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Lp(Li):H_(e)}n(Hi,"resolveIconHref");function B_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(B_,"hostnameFromHost");function F_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(F_,"isLocalOrAddressHost");function G_(e){let t=B_(e).toLowerCase().replace(/\.$/,"");if(F_(t)||L_.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=$_.has(o)?3:2;return r.slice(-s).join(".")}n(G_,"inferFaviconDomain");function Bi(e){return{src:Hi(G_(e)),mimeType:"image/png",sizes:["128x128"]}}n(Bi,"resolveMcpFaviconIcon");function ms(e){try{return Bi(new URL(e).host)}catch{return}}n(ms,"resolveMcpFaviconIconFromUrl");function St(e){let t=Se().connectionsById.get(e);if(!t)throw new K(`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(St,"getUpstreamServerConfig");function hs(e){let t=Se().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new K(`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(hs,"getUpstreamAuthConfig");function kr(e,t){let r=hs({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new K(`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(kr,"requireUpstreamOAuthConfig");function Bp(e,t){let r=hs({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new K(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(Bp,"requireUpstreamIdJagConfig");function Fp(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(Fp,"mergeAbortSignals");async function J_(e){try{await e.cancel()}catch{}}n(J_,"cancelReader");async function fs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],s=0,i=await r.read();for(;!i.done;){let u=i.value;if(s+=u.byteLength,s>t.maxBytes)throw await J_(r),t.createLimitError();o.push(u),i=await r.read()}let c=new Uint8Array(s),a=0;for(let u of o)c.set(u,a),a+=u.byteLength;return c}n(fs,"readBoundedByteStream");var V_=2,K_=1024*1024,W_=1e4,Z_=new Set([301,302,303,307,308]),Y_=["authorization","proxy-authorization","cookie","cookie2"];function Fi(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Fi,"readRequestUrl");function Er(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Er,"readRequestMethod");function X_(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 v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}})}n(X_,"assertContentLengthWithinLimit");async function Q_(e,t,r){return X_(e,t,r),fs(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}}),"createLimitError")})}n(Q_,"readBoundedResponseBody");function ew(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(ew,"responseFromBufferedBody");function tw(e,t){if(!Z_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(tw,"resolveRedirectUrl");function Gp(e,t){try{return t.validateUrl(e)}catch(r){throw new v({message:"Outbound URL was not allowed.",extensionMembers:{[C]:t.problemCode}},{cause:r})}}n(Gp,"validateOutboundUrl");function rw(e,t){throw e instanceof v&&Fo(e.extensionMembers?.[C])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[C]:t}},{cause:e})}n(rw,"normalizeFetchError");function no(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&&pe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(no,"logOutboundFailure");async function nw(e,t,r,o,s,i,c){let a=Er(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";no(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:a,host:te(i),error:u,extra:{abortReason:c()}}),rw(u,s)}}n(nw,"fetchWithNormalizedError");function ow(e){if(e.redirects>=e.maxRedirects)throw new v({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[C]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new v({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[C]:e.problemCode}})}n(ow,"assertRedirectAllowed");function sw(e,t){let r=new Headers(e);for(let o of Y_)r.delete(o);for(let o of t)r.delete(o);return r}n(sw,"stripCrossOriginHeaders");function iw(e,t,r,o,s){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=sw(e.headers,s)),i}n(iw,"buildRedirectInit");function aw(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(aw,"buildInitialRequestInit");function cw(e){let t=Er(e.currentInput,e.currentInit);ow({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Gp(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:iw(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(cw,"followRedirect");async function Gi(e,t,r){let o=r.problemCode??"invalid_request",s=r.maxRedirects??V_,i=r.maxResponseBytes??K_,c=r.timeoutMs??W_,a=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,f=Fp(h,t.signal),y=!1,S=setTimeout(()=>{y=!0,h.abort()},c),k=e,w=aw(e,t,h.signal),I;try{I=Gp(Fi(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw no(p,{event:"outbound_url_blocked",problemCode:o,method:Er(e,t),host:te(Fi(e)),error:O}),clearTimeout(S),f?.(),O}let U=0;try{for(;;){let O=await nw(p,a,k,w,o,I,()=>y?`timeout_after_${c}ms`:void 0),H=tw(O,I);if(H!==void 0)try{let F=cw({currentInput:k,currentInit:w,currentUrl:I,redirectUrl:H,redirects:U,maxRedirects:s,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});k=F.currentInput,w=F.currentInit,I=F.currentUrl,U=F.redirects;continue}catch(F){throw no(p,{event:"outbound_redirect_blocked",problemCode:o,method:Er(k,w),host:te(I),error:F,extra:{redirects:U,maxRedirects:s,redirectTargetHost:te(H)}}),F}try{return ew(O,await Q_(O,i,o))}catch(F){throw no(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Er(k,w),host:te(I),error:F,extra:{maxResponseBytes:i,status:O.status}}),F}}}finally{clearTimeout(S),f?.()}}n(Gi,"runSafeOutboundExchange");async function oo(e,t,r){let o=await Gi(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(s){throw no(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Er(e,t),host:te(Fi(e)),error:s,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new v({message:"Outbound JSON response could not be parsed.",extensionMembers:{[C]:r.problemCode??"invalid_request"}},{cause:s})}}n(oo,"runSafeOutboundJsonExchange");function Jp(e,t={},r={}){return Gi(e,t,{...r,validateUrl:Jn})}n(Jp,"fetchConfiguredOutbound");function Vp(e,t={},r={}){return oo(e,t,{...r,validateUrl:Jn})}n(Vp,"fetchConfiguredOutboundJson");function gs(e,t={},r={}){return oo(e,t,{...r,validateUrl:gl})}n(gs,"fetchIdentityProviderJson");function Kp(e,t={},r={}){return oo(e,t,{...r,validateUrl:Yo})}n(Kp,"fetchCimdClientMetadataJson");function Wp(e,t={},r={}){return oo(e,t,{...r,validateUrl:Vn})}n(Wp,"fetchCimdClientJwksJson");import{errors as tm,jwtVerify as rm,SignJWT as nm}from"jose";var we="zuplo-mcp-gateway",Ce=we,Te="HS256";import{base64url as dw}from"jose";var uw=new TextEncoder,lw="MCP gateway could not initialize secure key material.",pw=32,Zp=new Map,Yp=new Map,mw;function hw(){return mw??La.instance.authPrivateKey}n(hw,"readAuthPrivateKey");function Xp(e){return new ye(lw,e===void 0?void 0:{cause:e})}n(Xp,"createGeneratedKeyMaterialError");function Qp(e,t){let r=dw.decode(t);if(r.byteLength!==pw)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Qp,"decodeJwkKeyField");function fw(e){let t=hw();if(!t)throw Xp();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=Qp("d",r.d);Qp("x",r.x);let s=uw.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 Xp(r)}}n(fw,"decodeGeneratedKeyMaterial");function gw(e){let t=Zp.get(e);return t||(t=fw(e),Zp.set(e,t)),t}n(gw,"getMasterKeyMaterial");async function Be(e){let t=Yp.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(gw(e.keyMaterialPurpose));return Yp.set(e.purpose,r),r}n(Be,"readCachedDerivedKey");var yw="SHA-256",Sw=32,_w="zuplo-mcp-gateway:",ww=new TextEncoder,em=new WeakMap;async function _t(e,t){let r=em.get(e);r||(r=new Map,em.set(e,r));let o=r.get(t);if(o)return o;let s=await Rw(e,t);return r.set(t,s),s}n(_t,"deriveGatewaySigningKey");async function Rw(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=ww.encode(`${_w}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:yw,salt:new Uint8Array,info:me(s)},o,Sw*8);return new Uint8Array(i)}n(Rw,"hkdfExpand");var om=900,bw=900,vw=Xu.extend({id:Rl}),Iw=vw.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),sm=Qs.extend({id:bl,purpose:l.literal("browser_connect")}),Cw=Qs.extend({purpose:l.literal("browser_connect")}),Tw=sm.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),im=om*1e3;async function am(){return Be({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>_t(e,"oauth-state"),"derive")})}n(am,"getOAuthStateKey");async function cm(){return Be({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>_t(e,"browser-connect"),"derive")})}n(cm,"getBrowserConnectKey");async function dm(e){let t=Math.floor(Date.now()/1e3)+om;return new nm(e).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await am())}n(dm,"signOAuthState");async function ys(e){try{let{payload:t}=await rm(e,await am(),{algorithms:[Te],issuer:we,audience:Ce});return Iw.parse(t)}catch(t){throw t instanceof tm.JWTExpired?new v({message:"OAuth state has expired",extensionMembers:{[C]:"oauth_state_expired"}},{cause:t}):new v({message:"OAuth state could not be verified",extensionMembers:{[C]:"oauth_state_invalid"}},{cause:t})}}n(ys,"verifyOAuthState");async function um(e){let t=Math.floor(Date.now()/1e3)+bw,r=Cw.parse(e),o=sm.parse({...r,id:Tl()});return new nm(o).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await cm())}n(um,"signBrowserConnectTicket");async function lm(e){try{let{payload:t}=await rm(e,await cm(),{algorithms:[Te],issuer:we,audience:Ce});return Tw.parse(t)}catch(t){throw t instanceof tm.JWTExpired?new v({message:"Browser connect ticket has expired",extensionMembers:{[C]:"oauth_state_expired"}},{cause:t}):new v({message:"Browser connect ticket could not be verified",extensionMembers:{[C]:"oauth_state_invalid"}},{cause:t})}}n(lm,"verifyBrowserConnectTicket");async function pm(e){if((await N().consumeBrowserConnectTicket({id:e.id,expiresAt:D(new Date(e.exp*1e3)),now:D(new Date)})).kind==="consumed")throw new v({message:"Browser connect ticket has already been used",extensionMembers:{[C]:"oauth_state_reused"}})}n(pm,"consumeBrowserConnectTicket");function kw(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(kw,"buildConnectRequiredMessage");async function Ew(e){let t=Y(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 um({...Fn(e),purpose:"browser_connect"})),r.toString()}n(Ew,"buildGatewayBrowserTicketUrl");function Pw(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Pw,"buildGatewayConnectPath");async function Ji(e){return Ew({...e,path:Pw(e.upstreamServerId),redirect:!0})}n(Ji,"buildGatewayConnectUrl");async function Ss(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 Ji(t),message:kw(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ss,"buildRedirectConnectRequiredResponse");function mm(e){return Aw({...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(mm,"buildAdminConnectRequiredResponse");function Aw(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(Aw,"buildAdminSetupRequiredResponse");var hm=12;async function fm(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(fm,"sha256Hex");async function Bt(e){if(e)return(await fm(e)).slice(0,hm)}n(Bt,"fingerprintSecret");async function Pr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await fm(t)).slice(0,hm)}n(Pr,"fingerprintConnectionIdentity");var xw=6e4;function Ar(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(Ar,"credentialGenerationChanged");function he(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()+xw)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var gm=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function Uw(e,t){return e&&e.length>0?e.join(t):void 0}n(Uw,"joinOAuthScopes");function Ow(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of gm)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Ow,"sanitizeAuthorizationServerMetadata");function ym(e){let t=Ow(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(ym,"sanitizeOAuthDiscoveryState");function Sm(e){let t=new URL(e);for(let r of gm){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Sm,"dedupeSingletonAuthorizationRequestParams");function _s(e){let t=new URL(e);return ve(t)&&$u(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(_s,"normalizeLoopbackOAuthRedirectUri");function _m(e){return Uw(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(_m,"readProtectedResourceMetadataScope");function Mw(e){return`Zuplo MCP Gateway - ${e}`}n(Mw,"buildGatewayOAuthClientName");function zw(e,t){return e&&e.length>0?e.join(t):void 0}n(zw,"joinOAuthScopeList");function qw(e){if(e.clientRegistration.mode!=="auto")return zw(e.scopes,e.scopeDelimiter)}n(qw,"readPublicClientMetadataScope");function Vi(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Vi,"buildOAuthClientMetadataDocumentUrl");function Ki(e){let t=St(e.upstreamServerId);return{client_name:Mw(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(Ki,"buildGatewayOAuthClientMetadata");function wm(e,t,r){let o=kr(t,r),s=qw(o);return{client_id:Vi({origin:e,upstreamServerId:t}),...Ki({origin:e,upstreamServerId:t,redirectUri:_s(new URL(o.redirectPath,e)).toString(),scope:s})}}n(wm,"buildOAuthClientMetadataDocument");import{base64url as wt}from"jose";var Nw="SHA-256",xr="AES-GCM",jw=12,Zi="zuplo-secret",Yi=1,Rm="generated:auth_private_key:token-encryption",Dw=l.object({version:l.literal(Yi),keyId:l.literal(Rm),algorithm:l.literal(xr),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Wi(){return Be({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Nw,me(e));return crypto.subtle.importKey("raw",t,{name:xr},!1,["encrypt","decrypt"])},"derive")})}n(Wi,"getEncryptionKey");function bm(e){return me(new TextEncoder().encode(`${Zi}:v${e.version}:${e.keyId}`))}n(bm,"getAssociatedData");function $w(e){return`${Zi}:v${e.version}:${wt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n($w,"encodeEnvelope");function Lw(e){let t=`${Zi}:v${Yi}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(wt.decode(r));return Dw.parse(JSON.parse(o))}n(Lw,"decodeEnvelope");async function et(e){let t=await Wi(),r=crypto.getRandomValues(new Uint8Array(jw)),o={version:Yi,keyId:Rm},s=await crypto.subtle.encrypt({name:xr,iv:r,additionalData:bm(o)},t,new TextEncoder().encode(e));return $w({...o,algorithm:xr,iv:wt.encode(r),ciphertext:wt.encode(new Uint8Array(s))})}n(et,"encryptSecret");async function tt(e){let t=Lw(e);if(t){let c=await Wi(),a=await crypto.subtle.decrypt({name:xr,iv:me(wt.decode(t.iv)),additionalData:bm(t)},c,me(wt.decode(t.ciphertext)));return new TextDecoder().decode(a)}let[r,o]=e.split(".");if(!r||!o)throw new ye("Encrypted payload is malformed");let s=await Wi(),i=await crypto.subtle.decrypt({name:xr,iv:me(wt.decode(r))},s,me(wt.decode(o)));return new TextDecoder().decode(i)}n(tt,"decryptSecret");var vm={issuer:l.string().min(1).optional()},Hw=l.union([$t.extend(vm),Hn.extend(vm)]),Im=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:hr.optional(),authorizationServerMetadata:l.union([fr,gr]).optional()}).passthrough(),Bw="Bearer",Fw="__zuplo_refresh_only_upstream_access_token__";function Xi(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Xi,"splitScopes");function Qi(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Qi,"scopesCover");function Gw(e){return Sr.parse(e)}n(Gw,"parsePkceCodeVerifier");function Jw(e){if(typeof e.expires_in=="number")return D(new Date(Date.now()+e.expires_in*1e3))}n(Jw,"readTokenExpiry");async function Cm(e){if(e!==void 0)return et(JSON.stringify(e))}n(Cm,"encryptJson");async function Tm(e,t){if(!e)return;let r=await tt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new v({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[C]:"oauth_state_invalid"}},{cause:o})}}n(Tm,"decryptJson");function Vw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Vw,"clientInformationAllowsRedirectUri");function Kw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Kw,"clientInformationMatchesCurrentClientMetadataUrl");function Ww(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Ww,"isUrlBasedClientInformation");function Zw(e,t){return t===void 0?e:{...e,scope:t}}n(Zw,"applyOAuthClientMetadataScope");function Yw(e,t){return _m({state:e,delimiter:t})}n(Yw,"readResourceMetadataScope");function Xw(e,t){return e&&e.length>0?e.join(t):void 0}n(Xw,"joinOAuthScopeList");function Qw(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new K(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return $t.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Qw,"buildManualOAuthClientInformation");function eR(e,t){let r=Vi({origin:new URL(t).origin,upstreamServerId:e});return Ni(r)?r:void 0}n(eR,"buildClientMetadataUrl");function tR(e){for(let t of e)if(t!==void 0)return t}n(tR,"firstDefined");function rR(e){let t=kr(e.target.upstreamServerId,e.target.authProfileId),r=Xw(t.scopes,t.scopeDelimiter),o=Ki({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:Qw({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=eR(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}n(rR,"buildInitialOAuthClientSetup");function nR(e,t){if(t===void 0)return tR([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(nR,"readEncryptedClientInformation");function oR(e){return e.pendingState?.encryptedDiscoveryState}n(oR,"readEncryptedDiscoveryState");function ea(e,t){return t===void 0?e:{...e,issuer:t}}n(ea,"applyIssuerStamp");var Rt=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;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=rR({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,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=nR(t,this.configuredClientInformation),this.encryptedDiscoveryState=oR(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=Xi(this.configuredScope??r??this.readEffectiveScope());return Qi(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&he(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=W();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 Pr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Bt(await tt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await N().conditionalUpsertUpstreamConnection(t,r)}catch(o){let s=W();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 Zw(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return dm({id:t.id,...Fn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?ea(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,W()?.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"),!Ww({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cm(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ss({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=ym(Im.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Cm(r),await this.syncPendingState(!1),W()?.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=Yw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let s=Xi(this.configuredScope).filter(i=>!o.includes(i));s.length>0&&W()?.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 ea(r,t?.issuer)}async saveTokens(t){let r=lt.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,c=r.refresh_token?await et(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:lt.parse({...r,refresh_token:await tt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:s?.id??Xo(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await et(r.access_token),encryptedRefreshToken:c,scopes:Xi(r.scope??this.readEffectiveScope()),expiresAt:Jw(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},u=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},p=await this.conditionalUpsertCredential(a,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Qi(p.connection.scopes,a.scopes)||!Ar(s,p.connection))){h=!0;let y=p.connection,S={id:y.id,ownerMode:y.ownerMode,subjectId:y.subjectId,upstreamServerId:y.upstreamServerId,authProfileId:y.authProfileId,status:"active",encryptedAccessToken:a.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?y.encryptedRefreshToken:a.encryptedRefreshToken,scopes:a.scopes,expiresAt:a.expiresAt,metadata:y.metadata};W()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:y.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:y.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),p=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:y.updatedAt})}if(p.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=p.kind,p.kind==="persisted"?(this.credentialState.currentConnection=p.connection,this.credentialState.peerAdoption=void 0):p.kind==="precondition_failed"&&p.connection!==void 0?(this.credentialState.currentConnection=p.connection,Ar(s,p.connection)&&he(p.connection)==="usable"&&Qi(p.connection.scopes,a.scopes)?this.adoptPeerConnection(p.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),h){let y=p.kind==="persisted"?"succeeded":p.kind==="precondition_failed"?"lost":"exhausted";W()?.info({event:`upstream_oauth_bounded_rebase_${y}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${y}`)}let f=p.kind==="persisted"?p.connection:void 0;W()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!c,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Bt(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:a.scopes.length,expiresAt:a.expiresAt,outcome:p.kind,rebaseAttempted:h,resultingUpdatedAt:f?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:f?.scopes.length??this.credentialState.currentConnection?.scopes.length},f?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Sm(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:Gw(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new v({message:"OAuth code verifier is missing",extensionMembers:{[C]:"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:Cl(),...Fn({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:D(new Date(Date.now()+im)),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 N().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 Tm(this.encryptedClientInformation,Hw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!Vw(r,this.redirectUriValue)||!Kw({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=ea(Hn.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 Tm(this.encryptedDiscoveryState,Im)}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"){W()?.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 tt(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await tt(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let s=W();this.usedRefreshTokenFingerprintValue=s?await Bt(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=lt.parse({access_token:r??Fw,token_type:Bw,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 c=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});c.kind==="persisted"?(this.credentialState.currentConnection=c.connection,this.credentialState.peerAdoption=void 0):c.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):c.connection!==void 0&&(this.credentialState.currentConnection=c.connection,Ar(r,c.connection)&&he(c.connection)==="usable"&&this.connectionSatisfiesRequestedScope(c.connection)?this.adoptPeerConnection(c.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let a=W();if(a){let u=c.kind==="missing"?void 0:c.connection,p={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:u?.id,clearedTokens:t,priorStatus:o,newStatus:u?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:c.kind};c.kind==="precondition_failed"?a.warn({...p,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?a.warn(p,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(p,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var sR=3e4,iR=256*1024,aR=2,cR="does not support dynamic client registration",dR=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],uR=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],lR=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],pR="Protected resource ",mR=" does not match expected ",hR=["HTTP 403 Forbidden","Access Denied","permission to access"],fR=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function gR(e){return e instanceof Error&&e.message.includes(cR)}n(gR,"isDynamicClientRegistrationUnsupported");function yR(e){return e instanceof Error&&dR.some(t=>e.message.includes(t))}n(yR,"isProtectedResourceMetadataUnavailable");function SR(e){return e instanceof Error&&uR.some(t=>e.message.includes(t))}n(SR,"isAuthorizationServerMetadataUnavailable");function _R(e){return e instanceof Error&&lR.some(t=>e.message.includes(t))}n(_R,"isAuthorizationServerIncompatible");function wR(e){return e instanceof Error&&e.message.includes(pR)&&e.message.includes(mR)}n(wR,"isProtectedResourceMismatch");function RR(e){return e instanceof Error&&hR.some(t=>e.message.includes(t))}n(RR,"isUpstreamProviderAccessDenied");function bR(e){return e instanceof ft&&fR.has(e.code)}n(bR,"isStoredConnectionReconsentError");function rt(e){let t=e.diagnostics??{};return new v({message:e.message,extensionMembers:{[C]:e.code,[Bo]:e.upstreamServerId,[Rr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[We]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[Ke]:t.httpStatus},...t.providerError===void 0?{}:{[br]:t.providerError},...t.providerErrorDescription===void 0?{}:{[vr]:t.providerErrorDescription}}},{cause:e.cause})}n(rt,"buildUpstreamSetupProblem");function vR(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(vR,"describeIssuerMetadataMismatch");var IR=128,CR=256;function km(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(km,"truncateProviderDetail");function TR(e){let{error:t,errorDescription:r}=Pm(e.body),o=km(t,IR),s=km(r,CR);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...s===void 0?{}:{providerErrorDescription:s}}}n(TR,"readRegistrationRejectionDiagnostics");function kR(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(kR,"describeRegistrationRejection");function ER(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(ER,"readDiscoveryEndpointUrl");function PR(e){if(e.error instanceof v&&e.error.extensionMembers?.[C]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(gR(e.error))return rt({...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 zi){let r=TR(e.error);return rt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${kR(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 eo&&e.error.kind==="metadata")return rt({...t,code:"upstream_oauth_issuer_mismatch",message:vR(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ds)return rt({...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(_R(e.error))return rt({...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(SR(e.error)){let r=ER(e.error.message);return rt({...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(wR(e.error))return rt({...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(yR(e.error))return rt({...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(RR(e.error))return rt({...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(PR,"mapUpstreamOAuthSetupError");function AR(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(AR,"readOAuthFetchRequest");function xR(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(xR,"readOAuthFetchMethod");function UR(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(UR,"responseLooksJson");function OR(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(OR,"responseLooksHtml");var MR=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function zR(e){return MR.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(zR,"isMetadataDiscoveryRequest");function qR(e,t,r){return e!=="GET"||!zR(t)?!1:r>=400&&r<500||r===502}n(qR,"sdkRetriesDiscoveryCandidate");function NR(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new v({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[C]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[Ke]:e.response.status,[_r]:r,[We]:e.request.url.toString(),[wr]:e.body}})}n(NR,"throwUpstreamHtmlError");function Pm(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(Pm,"readUpstreamOAuthErrorBody");function jR(e){let{error:t,errorDescription:r}=Pm(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:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(jR,"logUpstreamOAuthHttpError");function Am(e){return async(t,r)=>{let o=AR(t),s=xR(t,r),i=W(),c=Date.now(),a=await Jp(t,r,{maxRedirects:aR,maxResponseBytes:iR,problemCode:"upstream_token_exchange_failed",timeoutMs:sR}),u=await a.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:te(o.url),path:o.url.pathname,status:a.status,durationMs:Date.now()-c,responseChars:u.length},"Upstream OAuth HTTP request completed"),a.ok||jR({log:i,upstreamServerId:e,method:s,request:o,response:a,body:u}),qR(s,o.url,a.status)||(!a.ok&&OR(a,u)&&NR({upstreamServerId:e,request:o,response:a,body:u}),!UR(a,u)))return a;try{JSON.parse(u)}catch(p){throw new v({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[C]:"upstream_token_exchange_failed"}},{cause:p})}return a}}n(Am,"createUpstreamOAuthFetch");function xm(e){W()?.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(xm,"logUpstreamOAuthFlowStarted");function Um(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 v?e.error.extensionMembers?.[C]:void 0;typeof o=="string"&&(t.code=o),pe(t,"error",e.error),W()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Um,"logUpstreamOAuthFlowFailed");function Om(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Om,"readAuthorizationRequestScope");async function Mm(e,t){e.applyChallengeScope(t.requestedScope),xm({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Am(t.upstreamServerId)},o=Om(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await qi(e,r)}catch(r){Um({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=PR({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Mm,"runUpstreamOAuth");async function DR(e,t){e.applyChallengeScope(t.requestedScope),xm({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Am(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Om(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await qi(e,r)}catch(s){throw Um({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}n(DR,"exchangeUpstreamAuthorizationCode");async function Em(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await N().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||he(r)!=="usable"||!Ar(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(Em,"adoptPeerCredentialAtResolutionBoundary");async function zm(e,t){let r=await Mm(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new v({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}}):new v({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}})}n(zm,"requireUpstreamAuthorizationRedirect");async function qm(e){let t=he(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=W(),i=s?await Pr({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 c;try{c=await Mm(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(a){if(e.connection===void 0||!bR(a))throw a;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:a.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 Em({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 ta({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(c==="AUTHORIZED"){let a=e.provider.readUsablePeerAdoption(e.requestedScope);return a!==void 0&&await e.provider.adoptConnectionForDirectResolution(a,"cas_loss"),!e.provider.tokenWriteWasPersisted&&a===void 0?{kind:"connect_required",payload:await ta({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(c!=="REDIRECT")throw new v({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${c}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new v({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}});return await Em({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 ta({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(qm,"authorizeUpstreamOAuthSession");async function $R(e){let t=await ys(e.stateToken),r=await N().consumeUpstreamOAuthState({id:t.id,now:D(new Date)}),o=LR(r);return HR({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),BR(o),o}n($R,"consumeStoredCallbackState");function LR(e){switch(e.kind){case"consumed":throw new v({message:"OAuth state has already been used",extensionMembers:{[C]:"oauth_state_reused"}});case"missing":throw new v({message:"OAuth state is missing or expired",extensionMembers:{[C]:"oauth_state_expired"}});case"available":return e.record}}n(LR,"readConsumedCallbackState");function HR(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 v({message:"OAuth callback did not match the initiating request",extensionMembers:{[C]:"oauth_callback_mismatch"}})}n(HR,"assertStoredCallbackStateMatches");function BR(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[C]:"oauth_state_expired"}})}n(BR,"assertStoredCallbackStateFresh");async function ta(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),mm(r)}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),Ss(t)}n(ta,"buildOAuthConnectRequiredResponse");async function Nm(e){let t=await $R({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Vo(t),[o]=await N().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 Rt(s),c=await DR(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(c==="AUTHORIZED"){let a=i.readUsablePeerAdoption();if(a!==void 0&&await i.adoptConnectionForDirectResolution(a,"cas_loss"),!i.tokenWriteWasPersisted&&a===void 0)throw new v({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[C]:"upstream_token_exchange_failed"}});return t}throw c!=="REDIRECT"?new v({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}}):new v({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[C]:"upstream_token_exchange_failed"}})}n(Nm,"finishUpstreamOAuthCallback");import{importPKCS8 as FR,SignJWT as GR}from"jose";var Dm=1e4,$m=64*1024,Lm=2,JR=300,qe=l.string().min(1),VR=l.object({access_token:qe,issued_token_type:l.literal(ti),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:qe.optional()}).passthrough(),KR=l.object({id_token:qe,token_type:qe.optional(),expires_in:l.number().int().positive().optional(),refresh_token:qe.optional(),scope:qe.optional()}).passthrough(),WR=l.object({access_token:qe,token_type:qe,expires_in:l.number().int().positive().optional(),scope:qe.optional(),resource:qe.optional(),refresh_token:qe.optional()}).passthrough();function jm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(jm,"formEncodeClientCredential");function ZR(e){return e.replaceAll("\\n",`
26
- `)}n(ZR,"normalizePem");async function YR(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??JR,o=await FR(ZR(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new GR({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(YR,"createPrivateKeyJwtClientAssertion");async function XR(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=jm(e.clientAuth.clientId),r=jm(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",Wo),e.form.set("client_assertion",await YR({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(XR,"appendClientAuthentication");async function ra(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await XR({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(ra,"buildFormRequest");function Hm(e){return(t,r)=>gs(t,r,{context:e,maxRedirects:Lm,maxResponseBytes:$m,problemCode:"upstream_token_exchange_failed",timeoutMs:Dm})}n(Hm,"defaultIdpFetchJson");function QR(e){return(t,r)=>Vp(t,r,{context:e,maxRedirects:Lm,maxResponseBytes:$m,problemCode:"upstream_token_exchange_failed",timeoutMs:Dm})}n(QR,"defaultResourceAsFetchJson");function ws(e){let t={[C]:e.code,[We]:e.tokenUrl};return e.response!==void 0&&(t[Ke]=e.response.status),new v({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(ws,"runtimeError");function na(e){if(!e.response.ok)throw ws({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(na,"assertTokenEndpointSucceeded");function eb(e){let t=KR.safeParse(e.json);if(!t.success)throw ws({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(eb,"parseIdpRefreshTokenResponse");function tb(e){let t=VR.safeParse(e.json);if(!t.success)throw ws({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(tb,"parseIdJagTokenExchangeResponse");function rb(e){let t=WR.safeParse(e.json);if(!t.success)throw ws({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(rb,"parseAccessTokenResponse");async function Bm(e){let t=new URLSearchParams({grant_type:Ko,requested_token_type:ti,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??Hm(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await ra({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return na({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),tb({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Bm,"requestIdJag");async function Fm(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Hm(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await ra({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return na({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),eb({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Fm,"refreshIdpSubjectToken");async function Gm(e){let t=new URLSearchParams({grant_type:mt,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??QR(e.context),{response:o,json:s}=await r(e.resourceAs.tokenUrl,await ra({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return na({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),rb({json:s,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Gm,"exchangeIdJagForAccessToken");function nb(e){return he(e)==="usable"}n(nb,"hasUsableAccessToken");function ob(e){if(e.tokenType.toLowerCase()!=="bearer")throw new v({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[C]:"upstream_token_response_invalid"}})}n(ob,"assertBearerToken");function Jm(e,t){if(t===Tr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Jm,"hasExpiredSubjectToken");async function sb(e){let t=await tt(e.encryptedSubjectToken);if(e.subjectTokenType!==Tr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Fm({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:Gn};let o=await N().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 et(r.refreshToken),idpSubjectTokenType:Tr,idpSubjectTokenExpiresAt:void 0}});return W()?.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 Bt(t),newSubjectRefreshTokenFingerprint:await Bt(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:Gn}}n(sb,"resolveIdJagSubjectToken");async function Vm(e){let t="preloadedConnection"in e?e.preloadedConnection:(await N().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=he(t),o=!!e.forceRefresh,s=!o&&r==="usable",i=W(),c=i?await Pr({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:c,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&&nb(t))return{kind:"authorized",credential:{type:"bearer_token",token:await tt(t.encryptedAccessToken)}};let a=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||a===void 0||u===void 0||Jm(t,u))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:a!==void 0,subjectTokenType:u,subjectTokenExpired:u!==void 0&&Jm(t,u)},"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 p=St(e.upstreamServerId),h=Bp(e.upstreamServerId,e.authProfileId),f=h.resourceAs.resource??p.transport.baseUrl,y=e.requestedScope??(h.scopes.length===0?void 0:h.scopes.join(h.scopeDelimiter)),S=await sb({connection:t,connectionFingerprint:c,encryptedSubjectToken:a,subjectTokenType:u,idp:{tokenUrl:h.idp.tokenUrl},clientAuth:h.idp.clientAuth,context:e.context}),k=await Bm({idp:{tokenUrl:h.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:h.resourceAs.audience,resource:f,scope:y,clientAuth:h.idp.clientAuth,context:e.context}),w=k.scope??y,I=await Gm({resourceAs:{tokenUrl:h.resourceAs.tokenUrl},assertion:k.assertion,resource:f,scope:w,clientAuth:h.resourceAs.clientAuth,context:e.context});if(ob(I),t!==void 0){let O=(I.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],H=I.expiresIn===void 0?void 0:D(new Date(Date.now()+I.expiresIn*1e3)),F=await N().upsertUpstreamConnection({id:S.connection.id,ownerMode:S.connection.ownerMode,subjectId:S.connection.subjectId,upstreamServerId:S.connection.upstreamServerId,authProfileId:S.connection.authProfileId,status:"active",encryptedAccessToken:await et(I.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:O,expiresAt:H,metadata:S.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:F.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:O.length,expiresAt:H},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:I.accessToken}}}n(Vm,"authorizeUpstreamIdJagRequest");var Rs=new Map;function ib(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(ib,"normalizeRefreshFlightScope");function ab(e){return _s(new URL(e.callbackPath,Y(e.requestUrl,e.requestHeaders))).toString()}n(ab,"buildGatewayOAuthRedirectUri");async function oa(e){let t=St(e.upstreamServerId),r=kr(e.upstreamServerId,e.authProfileId),o=ab({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await N().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:Y(e.request.url,e.request.headers)}}}n(oa,"prepareUpstreamOAuthRequest");async function Km(e){let t=await oa(e),r=new Rt({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return zm(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Km,"startUpstreamConnect");async function Wm(e){let t=await oa(e),r=new Rt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>qm({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&&he(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o();let s=vl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,ib(r.configuredAuthorizationScope??e.requestedScope)]),c=Rs.get(i);if(c!==void 0){W()?.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 p=await c;if(p.kind==="usable"&&r.connectionSatisfiesRequestedScope(p.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(p.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:h,...f}=e;if(t=await oa(f),r=new Rt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&he(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o()}let a=o(),u;return u=a.then(()=>{let p=r.currentConnection;return p!==void 0&&he(p)==="usable"?{kind:"usable",connection:p}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{Rs.get(i)===u&&Rs.delete(i)}),Rs.set(i,u),a}n(Wm,"authorizeUpstreamRequest");async function Ur(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Wm({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 Vm({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 ye(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Ur,"resolveUpstreamCredentialForRoute");async function Zm(e){if(e.connectRequest.authMode==="id-jag")throw new ye(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Km({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});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Zm,"startUpstreamConnectForRequest");async function Ym(e){let r=(await ys(e.callbackRequest.state)).authProfileId;if(hs({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new ye(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return Nm({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:St(e.callbackRequest.upstreamServerId)})}n(Ym,"finishUpstreamCallbackForRequest");function cb(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(cb,"buildRouteAuthBaseFromConnection");function Xm(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Qu(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Xm,"buildRouteAuthBaseFromPolicyOptions");function bs(e,t){let o=Se().byOperationId.get(t);if(!o)throw new K(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new K(`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 K(`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 cb({connection:o.connection,operationId:t})}n(bs,"resolveRouteAuthBase");function sa(e,t){switch(e){case"user":return Ir(t);case"shared":return Yu()}}n(sa,"buildOwnerForSubject");function Or(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:sa("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:sa("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:sa("user",t),initiatedBySubjectId:t}}}n(Or,"resolveRouteAuthForSubject");var db=P.InvalidRequest;function ub(e,t){return{credentialType:e.type,forceRefresh:t}}n(ub,"buildCredentialResolvedAttributes");function lb(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(lb,"connectRequiredReasonCode");function Qm(e){J(e.context,{eventType:B.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:ub(e.credential,e.forceRefresh===!0)})}n(Qm,"emitCredentialResolvedAnalyticsEvent");function eh(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(J(e.context,{eventType:B.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){J(e.context,{eventType:B.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}J(e.context,{eventType:B.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:lb(e.payload.state),reasonClass:"auth",attributes:t})}n(eh,"emitCredentialMissingAnalyticsEvents");function pb(e){let t=e.route.raw();return Jo.parse(t?.operationId)}n(pb,"readOperationId");async function mb(e,t,r,o){let s=await Ur({request:e,context:o,routeAuth:t});if(s.kind==="connect_required")return eh({context:o,payload:s.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:s.payload};let i=s.credential;if(Qm({context:o,credential:i,routeBinding:t}),i.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${i.token}`]]};let c=await i.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"),Response.json({error:"no_upstream_tokens"},{status:401}))}n(mb,"buildCredentialHeaders");var hb=new Set(["authorization","cookie","cookie2"]);function fb(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(fb,"readJsonRequestMethod");function gb(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(gb,"isJsonResponse");function ia(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ia,"isRecord");function yb(e){return Array.isArray(e)&&e.length>0}n(yb,"hasIconList");function Sb(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=ms(Vu(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Sb,"readFallbackServerIcons");function _b(e){if(!ia(e.body))return e.body;let t=e.body.result;if(!ia(t))return e.body;let r=t.serverInfo;return!ia(r)||yb(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(_b,"addMissingServerIcons");function wb(e,t){let r=th(e);for(let o of hb)r.delete(o);for(let[o,s]of t)r.set(o,s);return new Ja(e,{headers:r})}n(wb,"applyUpstreamHeaders");function th(e){let t=new Headers(e.headers);return Ka(t),t}n(th,"buildProxyHeaders");async function Rb(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Rb,"readRetryBody");function rh(e,t){let r=t.authUrl===void 0?void 0:Mp({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(us({id:Op(e),error:{code:r?.code??db,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(rh,"connectRequiredJsonRpcResponse");async function bb(e){let{scope:t}=Ep(e.upstreamResponse),r=await Ur({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return eh({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),s=r.credential;if(Qm({context:e.context,credential:s,routeBinding:e.routeAuth,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:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}n(bb,"applyRefreshedCredentialHeaders");function vb(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await bb({request:e.request,context:e.context,headers:th(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return rh(e.requestBody,o.payload);if(o.kind==="response")return o.response;let s=Ku({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Oo.fetch(s.url,s.init)})}n(vb,"installUpstreamAuthRetryHook");function Ib(e){if(fb(e.requestBody)!=="initialize")return;let t=Sb({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!gb(r))return r;let o;try{o=await r.clone().json()}catch{return r}let s=_b({body:o,icons:t});if(s===o)return r;let i=new Headers(r.headers);return i.delete("content-length"),new Response(JSON.stringify(s),{status:r.status,statusText:r.statusText,headers:i})})}n(Ib,"installInitializeIconHook");async function aa(e,t,r){let o=pb(t),s=await Rb(e),i=Xm({connection:r,operationId:o}),c=Lt(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),sl(t,c);let a=Or(i,c.subjectId),u=await mb(e,a,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return rh(s,u.payload);if(u instanceof Response)return u;let p=wb(e,u.headers);return vb({request:p,context:t,requestBody:s,routeAuth:a}),Ib({context:t,requestBody:s,connection:r}),p}n(aa,"mcpTokenExchangePolicy");var ca=class extends qo{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=el(t,r);super(o,r),this.#e=o}async handler(t,r){return aa(t,r,this.#e)}};var nh=Symbol("Html");function Cb(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Cb,"escapeHtml");function Tb(e){return e===null||typeof e!="object"?!1:e[nh]===!0}n(Tb,"isHtml");function vs(e){return e==null||e===!1?"":Array.isArray(e)?e.map(vs).join(""):Tb(e)?e.value:Cb(String(e))}n(vs,"renderValue");function Ae(e){return{[nh]:!0,value:e}}n(Ae,"trustedHtml");var xe=Ae("");function $(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=vs(t[o]),r+=e[o+1]??"";return Ae(r)}n($,"html");function Mr(e,t=xe){let r=vs(t),o="",s=!0;for(let i of e)s||(o+=r),o+=vs(i),s=!1;return Ae(o)}n(Mr,"joinHtml");function zr(e){return e.value}n(zr,"renderHtml");function oh(e){return $`<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(oh,"renderBrowserErrorPage");var sh=Ae('<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>'),ih=Ae('<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>'),qr=Ae('*,: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 Nr(e){return $`<!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>
25
+ import{$ as Zn,$a as Wd,$b as Ku,$c as Nl,$f as fs,$g as Np,Aa as vd,Ab as bu,Ac as as,Af as We,Ag as Ss,Ba as Cd,Bb as vu,Bc as cs,Bf as ap,Bg as Rp,C as nd,Ca as Id,Cb as Cu,Cc as pl,Cf as ot,Cg as _s,Da as Td,Db as Iu,Dc as ml,Df as M,Dg as qi,E as ns,Ea as Ed,Eb as Tu,Ec as hl,Ef as ms,Eg as ws,Fa as kd,Fb as Eu,Fc as fl,Fd as Ql,Ff as ve,Fg as bp,Ga as Ad,Gb as ku,Gc as gl,Gf as bt,Gg as ue,Ha as Pd,Hb as Au,Hc as yl,Hf as VS,Hg as vp,Ia as xd,Ib as Pu,Ic as Sl,If as KS,Ig as Cp,Ja as Od,Jb as xu,Jc as _l,Jf as WS,Jg as zi,Ka as Ud,Kb as Ou,Kc as wl,Kf as ZS,Kg as Ip,La as Md,Lb as Uu,Lc as Rl,Lf as YS,Lg as Tp,Ma as qd,Mb as Mu,Mc as bl,Mf as XS,Mg as Ni,Na as zd,Nb as qu,Nc as vl,Nf as QS,Ng as Ep,O as od,Oa as Nd,Ob as zu,Oc as Cl,Of as e_,Og as Yt,Pa as jd,Pb as Nu,Pc as Il,Pf as t_,Pg as kp,Qa as Ri,Qb as ju,Qc as Tl,Qf as r_,Qg as so,R as sd,Ra as Dd,Rb as Du,Rc as El,Rf as cp,Rg as Ap,Sa as $d,Sb as $u,Sc as kl,Sf as dp,Sg as Rs,Ta as Ld,Tb as Lu,Tc as Al,Tf as hs,Tg as io,Ua as Hd,Ub as Hu,Uc as Pl,Uf as to,Ug as Pp,Va as Bd,Vb as Bu,Vc as xl,Vf as ro,Vg as xp,Wa as Jd,Wb as Ju,Wc as Ol,Wf as Mr,Wg as Op,Xa as Fd,Xb as Fu,Xc as Ul,Xf as up,Xg as Up,Y as os,Ya as Gd,Yb as Gu,Yc as Ml,Yf as xi,Yg as Mp,Z as yi,Za as Vd,Zb as bi,Zc as ql,Zf as lp,Zg as qp,_ as wr,_a as Kd,_b as Vu,_c as zl,_f as no,_g as zp,aa as Rr,ab as Zd,ac as Wu,ad as jl,ag as pp,ah as bs,b as td,ba as br,bb as Yd,bc as Zu,bd as Dl,bg as mp,bh as jp,ca as Yn,cb as Xd,cc as Yu,cd as $l,cg as hp,ch as Dp,da as vr,db as Qd,dc as Xu,dd as Ll,dg as fp,dh as H,ea as id,eb as eu,ec as Qu,ed as Hl,eg as _e,eh as X,fa as ad,fb as tu,fc as el,fd as Bl,ff as ep,fg as me,fh as $p,ga as cd,gb as ru,gc as tl,gd as Jl,gf as qe,gg as gp,gh as he,ha as dd,hb as nu,hc as rl,hd as Fl,hf as tp,hg as yp,hh as at,ia as ud,ib as ou,ic as nl,id as Cr,if as rp,ig as J,ih as oe,ja as ld,jb as su,jc as ol,jd as Ir,jf as np,jg as st,jh as vs,ka as pd,kb as iu,kc as sl,kd as Gl,kf as ne,kg as qr,kh as Lp,la as md,lb as au,lc as il,ld as Tr,lf as op,lg as Ce,lh as n_,ma as hd,mb as cu,mc as al,md as Rt,mf as Er,mg as ce,mh as o_,n as Qe,na as fd,nb as du,nc as cl,nd as Pi,nf as sp,ng as Sp,oa as gd,ob as uu,oc as vi,od as ds,of as kr,og as te,pa as yd,pb as lu,pc as ss,pd as Vl,pf as E,pg as _p,qa as Sd,qb as pu,qc as is,qd as Qn,qf as Ar,qg as vt,ra as _d,rb as mu,rc as Ci,rd as Zt,rf as Pr,rg as Oi,sa as wd,sb as hu,sc as Ii,sd as Kl,sf as rt,sg as gs,ta as Rd,tb as fu,tc as Ti,td as Wl,tf as nt,tg as Ui,u as He,ua as Wt,ub as gu,uc as dl,ud as eo,uf as ls,ug as ys,v as rd,va as Si,vb as yu,vc as Ei,vd as Zl,vf as xr,vg as oo,wa as _i,wb as Su,wc as ki,wd as Yl,wf as Or,wg as zr,x as F,xa as Xn,xb as _u,xc as ul,xd as Xl,xf as Ur,xg as wp,ya as wi,yb as wu,yc as ll,yd as us,yf as ps,yg as it,za as bd,zb as Ru,zc as Ai,zf as ip,zg as Mi}from"../chunk-3CVOCJ3Y.js";import"../chunk-ZCJ5QBVD.js";import{a as Hp,b as Bp}from"../chunk-7FFIW3HF.js";import{a as _r}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{$ as es,Ba as p,a as be,aa as Yc,c as T,ca as hi,d as Y,da as Kn,ea as Xc,fa as u,ga as Qc,ha as ed,ia as C,ja as z,ka as ts,ma as D,na as b,oa as g,pa as L,qa as U,ra as fi,sa as Wn,ta as P,ua as B,va as _,wa as $,xa as gi,ya as rs}from"../chunk-FQIUJWH2.js";import"../chunk-UKQQD2JN.js";import{a as n}from"../chunk-TYV53J3B.js";var s_=Object.create,Cs=Object.defineProperty,i_=Object.getOwnPropertyDescriptor,a_=Object.getOwnPropertyNames,c_=Object.getPrototypeOf,d_=Object.prototype.hasOwnProperty,Jp=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),Fp=n((e,t)=>{let r={};for(var o in e)Cs(r,o,{get:e[o],enumerable:!0});return t&&Cs(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),u_=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=a_(t),i=0,a=s.length,c;i<a;i++)c=s[i],!d_.call(e,c)&&c!==r&&Cs(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(o=i_(t,c))||o.enumerable});return e},"__copyProps"),Gp=n((e,t,r)=>(r=e!=null?s_(c_(e)):{},u_(t||!e||!e.__esModule?Cs(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var l_=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Vp(e){return typeof e=="string"&&l_.has(e.replace(/#$/,""))}n(Vp,"declares2019Dialect");var Bi=Symbol.for("mcp.sdk.errorBrands");function Xt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let s=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof s=="string"&&r.add(s),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,Bi,{value:r,enumerable:!1,configurable:!0})}n(Xt,"stampErrorBrands");function ze(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Bi)){let r=t[Bi];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(ze,"brandedHasInstance");var le=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Ct=class om extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return ze(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",Xt(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new om(t.error,t.error_description??t.error,t.error_uri)}},fe=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),de=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return ze(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",Xt(this,new.target)}},v_=class extends de{static{n(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function sm(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(sm,"resourceUrlFromServerUrl");function Wi(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}n(Wi,"withoutIssuer");function As({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(i)}n(As,"checkResourceAllowed");var C_="2026-07-28";function im(e){return e>=C_}n(im,"isModernProtocolVersion");function am(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}n(am,"appendTextFallbackForNonObject");var cm=["task","inputRequests","requestState"];function I_(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||cm.some(t=>t in e)?e:{...e,content:[]}}n(I_,"normalizeContentlessToolResult");function T_(){let e=gi(()=>U([u(),C(),z(),ts(),P(u(),e),b(e)])),t=P(u(),e),r=U([u(),C().int()]),o=u(),s=g({ttl:C().optional()}),i=g({taskId:u()}),a=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),l=g({method:u(),params:c.loose().optional()}),m=g({_meta:a.optional()}),h=g({method:u(),params:m.loose().optional()}),y=L({_meta:a.optional()}),f=U([u(),C().int()]),R=y.strict(),S=m.extend({requestId:f.optional(),reason:u().optional()}),w=h.extend({method:_("notifications/cancelled"),params:S}),x=g({src:u(),mimeType:u().optional(),sizes:b(u()).optional(),theme:B(["light","dark"]).optional()}),I=g({icons:b(x).optional()}),O=g({name:u(),title:u().optional()}),N=O.extend({...O.shape,...I.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),we=Wn(g({applyDefaults:z().optional()}),t),q=rs(Se=>Se&&typeof Se=="object"&&!Array.isArray(Se)&&Object.keys(Se).length===0?{form:{}}:Se,Wn(g({form:we.optional(),url:t.optional()}),t.optional())),ie=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),pe=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),A=g({experimental:P(u(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:q.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:ie.optional(),extensions:P(u(),t).optional()}),K=c.extend({protocolVersion:u(),capabilities:A,clientInfo:N}),j=l.extend({method:_("initialize"),params:K}),W=g({experimental:P(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:z().optional()}).optional(),resources:g({subscribe:z().optional(),listChanged:z().optional()}).optional(),tools:g({listChanged:z().optional()}).optional(),tasks:pe.optional(),extensions:P(u(),t).optional()}),Z=y.extend({protocolVersion:u(),capabilities:W,serverInfo:N,instructions:u().optional()}),De=h.extend({method:_("notifications/initialized"),params:m.optional()}),Oe=l.extend({method:_("ping"),params:c.optional()}),$e=g({progress:C(),total:$(C()),message:$(u())}),G=g({...m.shape,...$e.shape,progressToken:r}),ae=h.extend({method:_("notifications/progress"),params:G}),ke=c.extend({cursor:o.optional()}),ee=l.extend({params:ke.optional()}),Ge=y.extend({nextCursor:o.optional()}),or=g({uri:u(),mimeType:$(u()),_meta:P(u(),D()).optional()}),sr=or.extend({text:u()}),Nt=u().refine(Se=>{try{return atob(Se),!0}catch{return!1}},{message:"Invalid Base64 string"}),ir=or.extend({blob:Nt}),Xe=B(["user","assistant"]),Ve=g({audience:b(Xe).optional(),priority:C().min(0).max(1).optional(),lastModified:Kn.datetime({offset:!0}).optional()}),jt=g({...O.shape,...I.shape,uri:u(),description:$(u()),mimeType:$(u()),size:$(C()),annotations:Ve.optional(),_meta:$(L({}))}),en=g({...O.shape,...I.shape,uriTemplate:u(),description:$(u()),mimeType:$(u()),annotations:Ve.optional(),_meta:$(L({}))}),tn=ee.extend({method:_("resources/list")}),rn=Ge.extend({resources:b(jt)}),yt=ee.extend({method:_("resources/templates/list")}),ar=Ge.extend({resourceTemplates:b(en)}),Dt=c.extend({uri:u()}),nn=Dt,on=l.extend({method:_("resources/read"),params:nn}),sn=y.extend({contents:b(U([sr,ir]))}),an=h.extend({method:_("notifications/resources/list_changed"),params:m.optional()}),cn=Dt,dn=l.extend({method:_("resources/subscribe"),params:cn}),un=Dt,ln=l.extend({method:_("resources/unsubscribe"),params:un}),pn=m.extend({uri:u()}),mn=h.extend({method:_("notifications/resources/updated"),params:pn}),hn=g({name:u(),description:$(u()),required:$(z())}),fn=g({...O.shape,...I.shape,description:$(u()),arguments:$(b(hn)),_meta:$(L({}))}),gn=ee.extend({method:_("prompts/list")}),yn=Ge.extend({prompts:b(fn)}),Sn=c.extend({name:u(),arguments:P(u(),u()).optional()}),_n=l.extend({method:_("prompts/get"),params:Sn}),$t=g({type:_("text"),text:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Lt=g({type:_("image"),data:Nt,mimeType:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Ht=g({type:_("audio"),data:Nt,mimeType:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),wn=g({type:_("tool_use"),name:u(),id:u(),input:P(u(),D()),_meta:P(u(),D()).optional()}),St=g({type:_("resource"),resource:U([sr,ir]),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Rn=jt.extend({type:_("resource_link")}),Le=U([$t,Lt,Ht,Rn,St]),cr=g({role:Xe,content:Le}),dr=y.extend({description:u().optional(),messages:b(cr)}),Bt=h.extend({method:_("notifications/prompts/list_changed"),params:m.optional()}),bn=g({title:u().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),ur=g({taskSupport:B(["required","optional","forbidden"]).optional()}),Jt=g({...O.shape,...I.shape,description:u().optional(),inputSchema:g({type:_("object"),properties:P(u(),e).optional(),required:b(u()).optional()}).catchall(D()),outputSchema:g({type:_("object"),properties:P(u(),e).optional(),required:b(u()).optional()}).catchall(D()).optional(),annotations:bn.optional(),execution:ur.optional(),_meta:P(u(),D()).optional()}),lr=ee.extend({method:_("tools/list")}),pr=Ge.extend({tools:b(Jt)}),mr=y.extend({content:b(Le),structuredContent:P(u(),D()).optional(),isError:z().optional()}),ye=d.extend({name:u(),arguments:P(u(),D()).optional()}),vn=l.extend({method:_("tools/call"),params:ye}),jo=h.extend({method:_("notifications/tools/list_changed"),params:m.optional()}),hr=B(["debug","info","notice","warning","error","critical","alert","emergency"]),Cn=c.extend({level:hr}),In=l.extend({method:_("logging/setLevel"),params:Cn}),Tn=m.extend({level:hr,logger:u().optional(),data:D()}),En=h.extend({method:_("notifications/message"),params:Tn}),kn=g({name:u().optional()}),An=g({hints:b(kn).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Pn=g({mode:B(["auto","required","none"]).optional()}),Do=g({type:_("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:b(Le),structuredContent:g({}).loose().optional(),isError:z().optional(),_meta:P(u(),D()).optional()}),xn=fi("type",[$t,Lt,Ht]),_t=fi("type",[$t,Lt,Ht,wn,Do]),On=g({role:Xe,content:U([_t,b(_t)]),_meta:P(u(),D()).optional()}),Un=d.extend({messages:b(On),modelPreferences:An.optional(),systemPrompt:u().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:b(u()).optional(),metadata:t.optional(),tools:b(Jt).optional(),toolChoice:Pn.optional()}),Mn=l.extend({method:_("sampling/createMessage"),params:Un}),qn=y.extend({model:u(),stopReason:$(B(["endTurn","stopSequence","maxTokens"]).or(u())),role:Xe,content:xn}),zn=y.extend({model:u(),stopReason:$(B(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:Xe,content:U([_t,b(_t)])}),Nn=g({type:_("boolean"),title:u().optional(),description:u().optional(),default:z().optional()}),jn=g({type:_("string"),title:u().optional(),description:u().optional(),minLength:C().optional(),maxLength:C().optional(),format:B(["email","uri","date","date-time"]).optional(),default:u().optional()}),Dn=g({type:B(["number","integer"]),title:u().optional(),description:u().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),$n=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),default:u().optional()}),Ln=g({type:_("string"),title:u().optional(),description:u().optional(),oneOf:b(g({const:u(),title:u()})),default:u().optional()}),Hn=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),enumNames:b(u()).optional(),default:u().optional()}),Bn=U([$n,Ln]),Ft=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({type:_("string"),enum:b(u())}),default:b(u()).optional()}),Gt=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({anyOf:b(g({const:u(),title:u()}))}),default:b(u()).optional()}),$o=U([Ft,Gt]),Lo=U([Hn,Bn,$o]),Ue=U([Lo,Nn,jn,Dn]),Me=d.extend({mode:_("form").optional(),message:u(),requestedSchema:g({type:_("object"),properties:P(u(),Ue),required:b(u()).optional()}).catchall(D())}),Jn=d.extend({mode:_("url"),message:u(),elicitationId:u(),url:u().url()}),Ke=U([Me,Jn]),Ho=l.extend({method:_("elicitation/create"),params:Ke}),Bo=m.extend({elicitationId:u()}),Jo=h.extend({method:_("notifications/elicitation/complete"),params:Bo}),Fo=y.extend({action:B(["accept","decline","cancel"]),content:rs(Se=>Se===null?void 0:Se,P(u(),U([u(),C(),z(),b(u())])).optional())}),Go=g({type:_("ref/resource"),uri:u()}),Vo=g({type:_("ref/prompt"),name:u()}),Ko=c.extend({ref:U([Vo,Go]),argument:g({name:u(),value:u()}),context:g({arguments:P(u(),u()).optional()}).optional()}),Fn=l.extend({method:_("completion/complete"),params:Ko}),Wo=y.extend({completion:L({values:b(u()).max(100),total:$(C().int()),hasMore:$(z())})}),Zo=g({uri:u().startsWith("file://"),name:u().optional(),_meta:P(u(),D()).optional()}),fr=l.extend({method:_("roots/list"),params:c.optional()}),Gn=y.extend({roots:b(Zo)}),Yo=h.extend({method:_("notifications/roots/list_changed"),params:m.optional()}),Xo=L({ttl:C().optional(),pollInterval:C().optional()}),Vn=B(["working","input_required","completed","failed","cancelled"]),wt=g({taskId:u(),status:Vn,ttl:U([C(),ts()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:$(C()),statusMessage:$(u())}),Ae=y.extend({task:wt}),Qo=m.merge(wt),Vt=h.extend({method:_("notifications/tasks/status"),params:Qo}),gr=l.extend({method:_("tasks/get"),params:c.extend({taskId:u()})}),yr=y.merge(wt),Sr=l.extend({method:_("tasks/result"),params:c.extend({taskId:u()})}),mi=y.loose(),Re=ee.extend({method:_("tasks/list")}),re=Ge.extend({tasks:b(wt)}),Kt=l.extend({method:_("tasks/cancel"),params:c.extend({taskId:u()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:l,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:y,RequestIdSchema:f,EmptyResultSchema:R,CancelledNotificationParamsSchema:S,CancelledNotificationSchema:w,IconSchema:x,IconsSchema:I,BaseMetadataSchema:O,ImplementationSchema:N,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:pe,ClientCapabilitiesSchema:A,InitializeRequestParamsSchema:K,InitializeRequestSchema:j,ServerCapabilitiesSchema:W,InitializeResultSchema:Z,InitializedNotificationSchema:De,PingRequestSchema:Oe,ProgressSchema:$e,ProgressNotificationParamsSchema:G,ProgressNotificationSchema:ae,PaginatedRequestParamsSchema:ke,PaginatedRequestSchema:ee,PaginatedResultSchema:Ge,ResourceContentsSchema:or,TextResourceContentsSchema:sr,BlobResourceContentsSchema:ir,RoleSchema:Xe,AnnotationsSchema:Ve,ResourceSchema:jt,ResourceTemplateSchema:en,ListResourcesRequestSchema:tn,ListResourcesResultSchema:rn,ListResourceTemplatesRequestSchema:yt,ListResourceTemplatesResultSchema:ar,ResourceRequestParamsSchema:Dt,ReadResourceRequestParamsSchema:nn,ReadResourceRequestSchema:on,ReadResourceResultSchema:sn,ResourceListChangedNotificationSchema:an,SubscribeRequestParamsSchema:cn,SubscribeRequestSchema:dn,UnsubscribeRequestParamsSchema:un,UnsubscribeRequestSchema:ln,ResourceUpdatedNotificationParamsSchema:pn,ResourceUpdatedNotificationSchema:mn,PromptArgumentSchema:hn,PromptSchema:fn,ListPromptsRequestSchema:gn,ListPromptsResultSchema:yn,GetPromptRequestParamsSchema:Sn,GetPromptRequestSchema:_n,TextContentSchema:$t,ImageContentSchema:Lt,AudioContentSchema:Ht,ToolUseContentSchema:wn,EmbeddedResourceSchema:St,ResourceLinkSchema:Rn,ContentBlockSchema:Le,PromptMessageSchema:cr,GetPromptResultSchema:dr,PromptListChangedNotificationSchema:Bt,ToolAnnotationsSchema:bn,ToolExecutionSchema:ur,ToolSchema:Jt,ListToolsRequestSchema:lr,ListToolsResultSchema:pr,CallToolResultSchema:mr,CallToolRequestParamsSchema:ye,CallToolRequestSchema:vn,ToolListChangedNotificationSchema:jo,LoggingLevelSchema:hr,SetLevelRequestParamsSchema:Cn,SetLevelRequestSchema:In,LoggingMessageNotificationParamsSchema:Tn,LoggingMessageNotificationSchema:En,ModelHintSchema:kn,ModelPreferencesSchema:An,ToolChoiceSchema:Pn,ToolResultContentSchema:Do,SamplingContentSchema:xn,SamplingMessageContentBlockSchema:_t,SamplingMessageSchema:On,CreateMessageRequestParamsSchema:Un,CreateMessageRequestSchema:Mn,CreateMessageResultSchema:qn,CreateMessageResultWithToolsSchema:zn,BooleanSchemaSchema:Nn,StringSchemaSchema:jn,NumberSchemaSchema:Dn,UntitledSingleSelectEnumSchemaSchema:$n,TitledSingleSelectEnumSchemaSchema:Ln,LegacyTitledEnumSchemaSchema:Hn,SingleSelectEnumSchemaSchema:Bn,UntitledMultiSelectEnumSchemaSchema:Ft,TitledMultiSelectEnumSchemaSchema:Gt,MultiSelectEnumSchemaSchema:$o,EnumSchemaSchema:Lo,PrimitiveSchemaDefinitionSchema:Ue,ElicitRequestFormParamsSchema:Me,ElicitRequestURLParamsSchema:Jn,ElicitRequestParamsSchema:Ke,ElicitRequestSchema:Ho,ElicitationCompleteNotificationParamsSchema:Bo,ElicitationCompleteNotificationSchema:Jo,ElicitResultSchema:Fo,ResourceTemplateReferenceSchema:Go,PromptReferenceSchema:Vo,CompleteRequestParamsSchema:Ko,CompleteRequestSchema:Fn,CompleteResultSchema:Wo,RootSchema:Zo,ListRootsRequestSchema:fr,ListRootsResultSchema:Gn,RootsListChangedNotificationSchema:Yo,TaskCreationParamsSchema:Xo,TaskStatusSchema:Vn,TaskSchema:wt,CreateTaskResultSchema:Ae,TaskStatusNotificationParamsSchema:Qo,TaskStatusNotificationSchema:Vt,GetTaskRequestSchema:gr,GetTaskResultSchema:yr,GetTaskPayloadRequestSchema:Sr,GetTaskPayloadResultSchema:mi,ListTasksRequestSchema:Re,ListTasksResultSchema:re,CancelTaskRequestSchema:Kt,CancelTaskResultSchema:y.merge(wt),ClientRequestSchema:U([Oe,j,Fn,In,_n,gn,tn,yt,on,dn,ln,vn,lr,gr,Sr,Re,Kt]),ClientNotificationSchema:U([w,ae,De,Yo,Vt]),ClientResultSchema:U([R,qn,zn,Fo,Gn,yr,re,Ae]),ServerRequestSchema:U([Oe,Mn,Ho,fr,gr,Sr,Re,Kt]),ServerNotificationSchema:U([w,ae,En,mn,an,jo,Bt,Vt,Jo]),ServerResultSchema:U([R,Z,Wo,dr,yn,rn,ar,sn,mr,pr,yr,re,Ae]),CallToolResultWireSchema:D().superRefine((Se,GS)=>{if(!(typeof Se!="object"||Se===null||Array.isArray(Se)||Se.content!==void 0)){for(let Zc of cm)if(Zc in Se){GS.addIssue({code:"custom",message:`content is required when the body carries '${Zc}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(I_).pipe(mr)}}n(T_,"build$1");var E_;function Zi(){return E_??=T_()}n(Zi,"buildSchemas2025");function dm(e){return e.type!=="object"}n(dm,"isNonObjectJsonSchemaRoot");var k_=new Set(["const","enum","default","examples"]),A_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Kp(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(Kp,"establishesNewBase");function P_(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Kp(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Vp(e.$schema)&&e.$recursiveAnchor!==!0,o=n((s,i)=>{if(Array.isArray(s))return s.map(d=>o(d,!1));if(s===null||typeof s!="object"||!i&&Kp(s.$id))return s;let a={},c=!1;for(let[d,l]of Object.entries(s))i?a[d]=o(l,!1):(d==="$ref"||d==="$dynamicRef")&&typeof l=="string"?a[d]=l==="#"?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:d==="$recursiveRef"&&l==="#"&&r?c=!0:k_.has(d)?a[d]=l:A_.has(d)?a[d]=o(l,!0):a[d]=o(l,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(P_,"wrapOutputSchemaForLegacy");var um={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},lm={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},x_={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Is;function Ps(){if(Is)return Is;let e=Zi();return Is={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Is}n(Ps,"registryMaps");function O_(){Ps()}n(O_,"warmRegistryMaps2025");function pm(e){return Object.prototype.hasOwnProperty.call(um,e)}n(pm,"hasRequestMethod2025");function mm(e){return Object.prototype.hasOwnProperty.call(lm,e)}n(mm,"hasNotificationMethod2025");function U_(e){return Object.prototype.hasOwnProperty.call(x_,e)}n(U_,"hasResultMethod");function M_(e){return U_(e)?Ps().resultSchemas[e]:void 0}n(M_,"getResultSchema");function q_(e){return pm(e)?Ps().requestSchemas[e]:void 0}n(q_,"getRequestSchema");function z_(e){return mm(e)?Ps().notificationSchemas[e]:void 0}n(z_,"getNotificationSchema");var NP=Object.keys(um),jP=Object.keys(lm);function Ji(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ji,"isPlainObject$5");function Ts(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(Ts,"triState$1");var Wp={ok:!1,reason:"not-in-era"};function Zp(e){return Ji(e)&&Ji(e.outputSchema)&&dm(e.outputSchema)}n(Zp,"toolNeedsLegacyWrap");var Yi={era:"2025-11-25",hasRequestMethod:pm,hasNotificationMethod:mm,validateRequest:n((e,t)=>Ts(q_(e),t),"validateRequest"),validateResult:n((e,t)=>Ts(M_(e),t),"validateResult"),validateNotification:n((e,t)=>Ts(z_(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>Wp,"validateInputRequest"),validateInputResponse:n(()=>Wp,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=Zi();return Ts(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=am(e),o=r.structuredContent;if(o===void 0)return r;let s=typeof o!="object"||o===null||Array.isArray(o),i=t!==void 0&&dm(t);return!s&&!i?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(Ji(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(o=>Zp(o))?t:{...t,tools:r.map(o=>Zp(o)?{...o,outputSchema:P_(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function N_(){let e=gi(()=>U([u(),C(),z(),ts(),P(u(),e),b(e)])),t=P(u(),e),r=U([u(),C().int()]),o=u(),s=U([u(),C().int()]),i=B(["user","assistant"]),a=B(["debug","info","notice","warning","error","critical","alert","emergency"]),c=u().refine(re=>{try{return atob(re),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:C().optional()}),l=g({taskId:u()}),m=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=g({_meta:m.optional()}),y=h.extend({task:d.optional()}),f=g({_meta:m.optional()}),R=g({method:u(),params:f.loose().optional()}),S=g({src:u(),mimeType:u().optional(),sizes:b(u()).optional(),theme:B(["light","dark"]).optional()}),w=g({icons:b(S).optional()}),x=g({name:u(),title:u().optional()}),I=x.extend({...x.shape,...w.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),O=Wn(g({applyDefaults:z().optional()}),t),N=rs(re=>re&&typeof re=="object"&&!Array.isArray(re)&&Object.keys(re).length===0?{form:{}}:re,Wn(g({form:O.optional(),url:t.optional()}),t.optional())),we=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),q=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),ie=g({experimental:P(u(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:we.optional(),extensions:P(u(),t).optional()}),pe=g({experimental:P(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:z().optional()}).optional(),resources:g({subscribe:z().optional(),listChanged:z().optional()}).optional(),tools:g({listChanged:z().optional()}).optional(),tasks:q.optional(),extensions:P(u(),t).optional()}),A=g({progress:C(),total:$(C()),message:$(u())}),K=g({...f.shape,...A.shape,progressToken:r}),j=R.extend({method:_("notifications/progress"),params:K}),W=f.extend({level:a,logger:u().optional(),data:D()}),Z=R.extend({method:_("notifications/message"),params:W}),De=g({uri:u(),mimeType:$(u()),_meta:P(u(),D()).optional()}),Oe=De.extend({text:u()}),$e=De.extend({blob:c}),G=g({audience:b(i).optional(),priority:C().min(0).max(1).optional(),lastModified:Kn.datetime({offset:!0}).optional()}),ae=g({...x.shape,...w.shape,uri:u(),description:$(u()),mimeType:$(u()),size:$(C()),annotations:G.optional(),_meta:$(L({}))}),ke=g({...x.shape,...w.shape,uriTemplate:u(),description:$(u()),mimeType:$(u()),annotations:G.optional(),_meta:$(L({}))}),ee=R.extend({method:_("notifications/resources/list_changed"),params:f.optional()}),Ge=f.extend({uri:u()}),or=R.extend({method:_("notifications/resources/updated"),params:Ge}),sr=g({name:u(),description:$(u()),required:$(z())}),Nt=g({...x.shape,...w.shape,description:$(u()),arguments:$(b(sr)),_meta:$(L({}))}),ir=R.extend({method:_("notifications/prompts/list_changed"),params:f.optional()}),Xe=g({type:_("text"),text:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),Ve=g({type:_("image"),data:c,mimeType:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),jt=g({type:_("audio"),data:c,mimeType:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),en=g({type:_("tool_use"),name:u(),id:u(),input:P(u(),D()),_meta:P(u(),D()).optional()}),tn=g({type:_("resource"),resource:U([Oe,$e]),annotations:G.optional(),_meta:P(u(),D()).optional()}),rn=ae.extend({type:_("resource_link")}),yt=U([Xe,Ve,jt,rn,tn]),ar=g({role:i,content:yt}),Dt=g({title:u().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),nn=R.extend({method:_("notifications/tools/list_changed"),params:f.optional()}),on=g({name:u().optional()}),sn=g({hints:b(on).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),an=g({mode:B(["auto","required","none"]).optional()}),cn=g({type:_("boolean"),title:u().optional(),description:u().optional(),default:z().optional()}),dn=g({type:_("string"),title:u().optional(),description:u().optional(),minLength:C().optional(),maxLength:C().optional(),format:B(["email","uri","date","date-time"]).optional(),default:u().optional()}),un=g({type:B(["number","integer"]),title:u().optional(),description:u().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),ln=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),default:u().optional()}),pn=g({type:_("string"),title:u().optional(),description:u().optional(),oneOf:b(g({const:u(),title:u()})),default:u().optional()}),mn=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),enumNames:b(u()).optional(),default:u().optional()}),hn=U([ln,pn]),fn=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({type:_("string"),enum:b(u())}),default:b(u()).optional()}),gn=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({anyOf:b(g({const:u(),title:u()}))}),default:b(u()).optional()}),yn=U([fn,gn]),Sn=U([mn,hn,yn]),_n=U([Sn,cn,dn,un]),$t=y.extend({mode:_("form").optional(),message:u(),requestedSchema:g({type:_("object"),properties:P(u(),_n),required:b(u()).optional()}).catchall(D())}),Lt=g({type:_("ref/resource"),uri:u()}),Ht=g({type:_("ref/prompt"),name:u()}),wn=g({uri:u().startsWith("file://"),name:u().optional(),_meta:P(u(),D()).optional()}),St=ie.shape,Rn=g({experimental:St.experimental,sampling:St.sampling,elicitation:St.elicitation,roots:St.roots,extensions:St.extensions}),Le=pe.shape,cr=g({experimental:Le.experimental,logging:Le.logging,completions:Le.completions,prompts:Le.prompts,resources:Le.resources,tools:Le.tools,extensions:Le.extensions}),dr=L({progressToken:r.optional(),[wr]:u(),[Zn]:I.optional(),[br]:Rn,[Yn]:a.optional()}),Bt=g({...x.shape,...w.shape,description:u().optional(),inputSchema:L({$schema:u().optional(),type:_("object")}),outputSchema:L({$schema:u().optional()}).optional(),annotations:Dt.optional(),_meta:P(u(),D()).optional()}),bn=g({type:_("tool_result"),toolUseId:u(),content:b(yt),structuredContent:D().optional(),isError:z().optional(),_meta:P(u(),D()).optional()}),ur=U([Xe,Ve,jt,en,bn]),Jt=g({role:i,content:U([ur,b(ur)]),_meta:P(u(),D()).optional()}),lr=u(),pr=L({[Rr]:I.optional().catch(void 0)}),mr=pr.optional();function ye(re){return L({_meta:mr,resultType:lr.default("complete"),...re})}n(ye,"wireResult");let vn=ye({}),jo=ye({nextCursor:o.optional()}),hr=ye({content:b(yt),structuredContent:D().optional(),isError:z().optional()}),Cn=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),tools:b(Bt),nextCursor:o.optional()}),In=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),prompts:b(Nt),nextCursor:o.optional()}),Tn=ye({description:u().optional(),messages:b(ar)}),En=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resources:b(ae),nextCursor:o.optional()}),kn=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:b(ke),nextCursor:o.optional()}),An=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),contents:b(U([Oe,$e]))}),Pn=ye({completion:g({values:b(u()).max(100),total:C().int().optional(),hasMore:z().optional()}).loose()}),Do=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"])}),xn=ye({ttlMs:C().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:b(u()),capabilities:cr,instructions:u().optional()}),_t=g({messages:b(Jt),modelPreferences:sn.optional(),systemPrompt:u().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:b(u()).optional(),metadata:t.optional(),tools:b(Bt).optional(),toolChoice:an.optional()}),On=g({method:_("sampling/createMessage"),params:_t}),Un=g({method:_("roots/list"),params:g({_meta:P(u(),D()).optional()}).optional()}),Mn=g({...Jt.shape,model:u(),stopReason:u().optional()}),qn=g({roots:b(wn)}),zn=g({action:B(["accept","decline","cancel"]),content:P(u(),U([u(),C(),z(),b(u())])).optional()}),Nn=g({mode:_("url"),message:u(),url:u().url()}),jn=U([$t,Nn]),Dn=g({method:_("elicitation/create"),params:jn}),$n=U([On,Un,Dn]),Ln=U([Mn,qn,zn]),Hn=P(u(),$n),Bn=P(u(),Ln),Ft=ye({inputRequests:Hn.optional(),requestState:u().optional()}),Gt={inputResponses:Bn.optional(),requestState:u().optional()},$o=g({_meta:dr,...Gt}),Lo=L({progressToken:r.optional()});function Ue(re,Kt){return g({method:_(re),params:g({_meta:dr,...Kt})})}n(Ue,"wireRequest");function Me(re,Kt){return g({method:_(re),params:g({_meta:Lo.optional(),...Kt}).optional()})}n(Me,"dispatchRequest");let Jn={name:u(),arguments:P(u(),D()).optional(),...Gt},Ke={cursor:o.optional()},Ho=Ue("tools/call",Jn),Bo=Ue("tools/list",Ke),Jo=Ue("prompts/list",Ke),Fo=Ue("prompts/get",{name:u(),arguments:P(u(),u()).optional(),...Gt}),Go=Ue("resources/list",Ke),Vo=Ue("resources/templates/list",Ke),Ko=Ue("resources/read",{uri:u(),...Gt}),Fn={ref:U([Ht,Lt]),argument:g({name:u(),value:u()}),context:g({arguments:P(u(),u()).optional()}).optional()},Wo=Ue("completion/complete",Fn),Zo=Ue("server/discover",{}),fr=g({toolsListChanged:z().optional(),promptsListChanged:z().optional(),resourcesListChanged:z().optional(),resourceSubscriptions:b(u()).optional()}),Gn={notifications:fr},Yo=Ue("subscriptions/listen",Gn),Xo=pr.extend({"io.modelcontextprotocol/subscriptionId":s}),Vn=L({_meta:Xo,resultType:lr.default("complete")}),wt={"tools/call":Me("tools/call",Jn),"tools/list":Me("tools/list",Ke),"prompts/get":Me("prompts/get",{name:u(),arguments:P(u(),u()).optional()}),"prompts/list":Me("prompts/list",Ke),"resources/list":Me("resources/list",Ke),"resources/templates/list":Me("resources/templates/list",Ke),"resources/read":Me("resources/read",{uri:u()}),"completion/complete":Me("completion/complete",Fn),"server/discover":Me("server/discover",{}),"subscriptions/listen":Me("subscriptions/listen",Gn)};function Ae(re){return L({_meta:mr,...re})}n(Ae,"liftedResult");let Qo={"tools/call":Ae({content:b(yt),structuredContent:D().optional(),isError:z().optional()}),"tools/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),tools:b(Bt),nextCursor:o.optional()}),"prompts/get":Ae({description:u().optional(),messages:b(ar)}),"prompts/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),prompts:b(Nt),nextCursor:o.optional()}),"resources/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resources:b(ae),nextCursor:o.optional()}),"resources/templates/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:b(ke),nextCursor:o.optional()}),"resources/read":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),contents:b(U([Oe,$e]))}),"completion/complete":Ae({completion:g({values:b(u()).max(100),total:C().int().optional(),hasMore:z().optional()}).loose()}),"server/discover":Ae({ttlMs:C().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:b(u()),capabilities:cr,instructions:u().optional()}),"subscriptions/listen":Ae({})},Vt=L({"io.modelcontextprotocol/subscriptionId":s.optional()}),gr=g({method:_("notifications/subscriptions/acknowledged"),params:g({_meta:Vt.optional(),notifications:fr})}),yr=g({_meta:Vt.optional(),requestId:s,reason:u().optional()}),Sr=g({method:_("notifications/cancelled"),params:yr}),mi={"notifications/cancelled":Sr,"notifications/progress":j,"notifications/message":Z,"notifications/resources/updated":or,"notifications/resources/list_changed":ee,"notifications/tools/list_changed":nn,"notifications/prompts/list_changed":ir,"notifications/subscriptions/acknowledged":gr},Re=n(re=>g({jsonrpc:_("2.0"),id:U([u(),C().int()]),result:re}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:l,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:f,NotificationSchema:R,IconSchema:S,IconsSchema:w,BaseMetadataSchema:x,ImplementationSchema:I,ClientTasksCapabilitySchema:we,ServerTasksCapabilitySchema:q,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:pe,ProgressSchema:A,ProgressNotificationParamsSchema:K,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:W,LoggingMessageNotificationSchema:Z,ResourceContentsSchema:De,TextResourceContentsSchema:Oe,BlobResourceContentsSchema:$e,AnnotationsSchema:G,ResourceSchema:ae,ResourceTemplateSchema:ke,ResourceListChangedNotificationSchema:ee,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:or,PromptArgumentSchema:sr,PromptSchema:Nt,PromptListChangedNotificationSchema:ir,TextContentSchema:Xe,ImageContentSchema:Ve,AudioContentSchema:jt,ToolUseContentSchema:en,EmbeddedResourceSchema:tn,ResourceLinkSchema:rn,ContentBlockSchema:yt,PromptMessageSchema:ar,ToolAnnotationsSchema:Dt,ToolListChangedNotificationSchema:nn,ModelHintSchema:on,ModelPreferencesSchema:sn,ToolChoiceSchema:an,BooleanSchemaSchema:cn,StringSchemaSchema:dn,NumberSchemaSchema:un,UntitledSingleSelectEnumSchemaSchema:ln,TitledSingleSelectEnumSchemaSchema:pn,LegacyTitledEnumSchemaSchema:mn,SingleSelectEnumSchemaSchema:hn,UntitledMultiSelectEnumSchemaSchema:fn,TitledMultiSelectEnumSchemaSchema:gn,MultiSelectEnumSchemaSchema:yn,EnumSchemaSchema:Sn,PrimitiveSchemaDefinitionSchema:_n,ElicitRequestFormParamsSchema:$t,ResourceTemplateReferenceSchema:Lt,PromptReferenceSchema:Ht,RootSchema:wn,ClientCapabilities2026Schema:Rn,ServerCapabilities2026Schema:cr,RequestMetaEnvelopeSchema:dr,ToolSchema:Bt,ToolResultContentSchema:bn,SamplingMessageContentBlockSchema:ur,SamplingMessageSchema:Jt,ResultTypeSchema:lr,ResultMetaSchema:pr,ResultSchema:vn,PaginatedResultSchema:jo,CallToolResultSchema:hr,ListToolsResultSchema:Cn,ListPromptsResultSchema:In,GetPromptResultSchema:Tn,ListResourcesResultSchema:En,ListResourceTemplatesResultSchema:kn,ReadResourceResultSchema:An,CompleteResultSchema:Pn,CacheableResultSchema:Do,DiscoverResultSchema:xn,CreateMessageRequestParamsSchema:_t,CreateMessageRequestSchema:On,ListRootsRequestSchema:Un,CreateMessageResultSchema:Mn,ListRootsResultSchema:qn,ElicitResultSchema:zn,ElicitRequestURLParamsSchema:Nn,ElicitRequestParamsSchema:jn,ElicitRequestSchema:Dn,InputRequestSchema:$n,InputResponseSchema:Ln,InputRequestsSchema:Hn,InputResponsesSchema:Bn,InputRequiredResultSchema:Ft,InputResponseRequestParamsSchema:$o,CallToolRequestSchema:Ho,ListToolsRequestSchema:Bo,ListPromptsRequestSchema:Jo,GetPromptRequestSchema:Fo,ListResourcesRequestSchema:Go,ListResourceTemplatesRequestSchema:Vo,ReadResourceRequestSchema:Ko,CompleteRequestSchema:Wo,DiscoverRequestSchema:Zo,SubscriptionFilterSchema:fr,SubscriptionsListenRequestSchema:Yo,SubscriptionsListenResultMetaSchema:Xo,SubscriptionsListenResultSchema:Vn,dispatchRequestSchemas:wt,dispatchResultSchemas:Qo,NotificationMetaSchema:Vt,SubscriptionsAcknowledgedNotificationSchema:gr,CancelledNotificationParamsSchema:yr,CancelledNotificationSchema:Sr,notificationSchemas2026:mi,JSONRPCResultResponseSchema:Re(vn),CallToolResultResponseSchema:Re(U([hr,Ft])),ListToolsResultResponseSchema:Re(Cn),ListPromptsResultResponseSchema:Re(In),GetPromptResultResponseSchema:Re(U([Tn,Ft])),ListResourcesResultResponseSchema:Re(En),ListResourceTemplatesResultResponseSchema:Re(kn),ReadResourceResultResponseSchema:Re(U([An,Ft])),CompleteResultResponseSchema:Re(Pn),DiscoverResultResponseSchema:Re(xn),SubscriptionsListenResultResponseSchema:Re(Vn)}}n(N_,"build");var j_;function ct(){return j_??=N_()}n(ct,"buildSchemas2026");var D_=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $_(e){return D_.includes(e)}n($_,"isCacheableResultMethod");var Xi=Symbol("modelcontextprotocol.resultCacheHintFallback");function L_(e){return e[Xi]}n(L_,"cacheHintFallbackOf");function hm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(hm,"isValidCacheTtlMs");function fm(e){return e==="public"||e==="private"}n(fm,"isValidCacheScope");var k=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),ge=class gm extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return ze(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",Xt(this,new.target)}static fromError(t,r,o){if(t===k.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new xs(s.elicitations,r)}if(t===k.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Sm({supported:s.supported,requested:s.requested},r)}if(t===k.InvalidParams||t===k.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===k.ResourceNotFound||Object.keys(s).length===1))return new ym(s.uri,r)}if(t===k.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new _m({requiredCapabilities:s.requiredCapabilities},r)}return new gm(t,r,o)}},ym=class extends ge{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(k.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},xs=class extends ge{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(k.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Sm=class extends ge{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(k.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},_m=class extends ge{static{n(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(k.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},H_=0,B_="private",J_=["tools/call","prompts/get","resources/read"];function F_(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||J_.includes(e))return t;throw new ge(k.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(F_,"stampResultType");function G_(e,t){let r=L_(t);if(t.resultType!=="complete"||!$_(e))return r===void 0?t:Y_(t);let o=t,s=hm(o.ttlMs)?o.ttlMs:W_(r),i=fm(o.cacheScope)?o.cacheScope:Z_(r),a={...o,ttlMs:s,cacheScope:i};return delete a[Xi],a}n(G_,"fillCacheFields");function V_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(V_,"isPlainObject$4");function K_(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Rr]:t}}:!V_(r)||r[Rr]!==void 0?e:{...e,_meta:{...r,[Rr]:t}}}n(K_,"stampServerInfoMeta");function W_(e){return e!==void 0&&hm(e.ttlMs)?e.ttlMs:H_}n(W_,"resolveTtlMs");function Z_(e){return e!==void 0&&fm(e.cacheScope)?e.cacheScope:B_}n(Z_,"resolveCacheScope");function Y_(e){let t={...e};return delete t[Xi],t}n(Y_,"stripCacheHintFallback");var X_=["elicitation/create","sampling/createMessage","roots/list"],Es;function Qi(){if(Es)return Es;let e=ct();return Es={request:{"elicitation/create":g({method:_("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:_("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:_("roots/list"),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Es}n(Qi,"inputSchemaMaps");function Q_(){Qi()}n(Q_,"warmInputSchemaMaps2026");function wm(e){return X_.includes(e)}n(wm,"isInputRequestMethod2026");function ji(e){return wm(e)?Qi().request[e]:void 0}n(ji,"getInputRequestSchema2026");function ew(e){return wm(e)?Qi().response[e]:void 0}n(ew,"getInputResponseSchema2026");var ea={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Rm={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function bm(e){return Object.prototype.hasOwnProperty.call(ea,e)}n(bm,"hasRequestMethod2026");function vm(e){return Object.prototype.hasOwnProperty.call(Rm,e)}n(vm,"hasNotificationMethod2026");function tw(e){return Object.prototype.hasOwnProperty.call(ea,e)}n(tw,"hasResultMethod2026");function rw(e){return bm(e)?ct().dispatchRequestSchemas[e]:void 0}n(rw,"getRequestSchema2026");function nw(e){return tw(e)?ct().dispatchResultSchemas[e]:void 0}n(nw,"getResultSchema2026");function ow(e){return vm(e)?ct().notificationSchemas2026[e]:void 0}n(ow,"getNotificationSchema2026");var DP=Object.keys(ea),$P=Object.keys(Rm);function uo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(uo,"isPlainObject$3");function ao(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(ao,"triState");var sw={ok:!1,reason:"not-in-era"},iw=[wr,br];function aw(e,t){let r=t,o=!1,s=n(()=>(o||(r={...r},o=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>uo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!uo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(uo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}n(aw,"enforceDeletedFields");var ta={era:"2026-07-28",hasRequestMethod:bm,hasNotificationMethod:vm,hasInputRequestMethod:n(e=>ji(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>ao(rw(e),t),"validateRequest"),validateResult:n((e,t)=>ao(nw(e),t),"validateResult"),validateNotification:n((e,t)=>ao(ow(e),t),"validateNotification"),validateInputRequest:n((e,t)=>ao(ji(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>ao(ew(e),t),"validateInputResponse"),samplingResultVariant:n(()=>sw,"samplingResultVariant"),outboundEnvelope(e){return{[wr]:e.protocolVersion,[Zn]:e.clientInfo,[br]:e.clientCapabilities,...e.logLevel!==void 0&&{[Yn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of iw)o in e||t.push({key:o,problem:"missing"});let r=ct().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let s=o.path.map(String),i=s.length>0?s.join("."):"_meta";s.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:o.message})}return t},projectCallToolResult:n(e=>am(e),"projectCallToolResult"),inputRequestSchema:ji,decodeResult(e,t){if(!uo(t))return{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=uo(a)?a:{},d=t.requestState,l=t._meta===void 0?void 0:ct().ResultMetaSchema.safeParse(t._meta),m=l?.success?l.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new de(fe.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Cm(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return K_(G_(e,F_(e,aw(e,t))),r)},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=ct().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},ks;function Cm(){if(ks)return ks;let e=ct();return ks={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},ks}n(Cm,"getWireResultSchemas");function cw(){Cm()}n(cw,"warmWireResultSchemas2026");var ra="2026-07-28";function po(e){return e!==void 0&&im(e)?ta:Yi}n(po,"codecForVersion");function Yp(e){return e.revision!==void 0?po(e.revision).era:e.era==="modern"?ta.era:Yi.era}n(Yp,"classifiedWireEra");function Di(e){return Im.some(t=>t.hasRequestMethod(e))}n(Di,"isSpecRequestMethod");function $i(e){return Im.some(t=>t.hasNotificationMethod(e))}n($i,"isSpecNotificationMethod");function Xp(e){return e==="tasks/get"||e==="tasks/cancel"}n(Xp,"isExtensionReusedRequestMethod");var Im=[Yi,ta],dw=Fp({AnnotationsSchema:n(()=>Zd,"AnnotationsSchema"),AudioContentSchema:n(()=>Au,"AudioContentSchema"),BaseMetadataSchema:n(()=>kd,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>hd,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>Kd,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>vi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>Ju,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Fu,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Hu,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>jl,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>Dl,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Cd,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Id,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Od,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>Ll,"ClientNotificationSchema"),ClientRequestSchema:n(()=>$l,"ClientRequestSchema"),ClientResultSchema:n(()=>Hl,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Pd,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>Bu,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>_l,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>wl,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Rl,"CompleteResultSchema"),ContentBlockSchema:n(()=>Uu,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>sl,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>il,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>al,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>cl,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Al,"CreateTaskResultSchema"),CursorSchema:n(()=>ud,"CursorSchema"),DiscoverRequestSchema:n(()=>jd,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Ri,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>as,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>pl,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>ml,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>cs,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>gl,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>hl,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>fl,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>xu,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>vd,"EmptyResultSchema"),EnumSchemaSchema:n(()=>ll,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Iu,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Tu,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>qu,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>Ml,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>ql,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Ol,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>Ul,"GetTaskResultSchema"),IconSchema:n(()=>Td,"IconSchema"),IconsSchema:n(()=>Ed,"IconsSchema"),ImageContentSchema:n(()=>ku,"ImageContentSchema"),ImplementationSchema:n(()=>Ad,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>Ud,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>Md,"InitializeRequestSchema"),InitializeResultSchema:n(()=>zd,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>Nd,"InitializedNotificationSchema"),JSONArraySchema:n(()=>cd,"JSONArraySchema"),JSONObjectSchema:n(()=>ad,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Xn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>wi,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>Si,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Wt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>bd,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>_i,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>id,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Ti,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>bi,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>vu,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Cu,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>tu,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>ru,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Qd,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>eu,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>vl,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Cl,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>zl,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>Nl,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>$u,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>Lu,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>Vu,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Zu,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>Yu,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Xu,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Qu,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>ul,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>Sd,"NotificationSchema"),NotificationsParamsSchema:n(()=>yd,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>is,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>Bd,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>Jd,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Fd,"PaginatedResultSchema"),PingRequestSchema:n(()=>Dd,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>Ai,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>Ld,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Hd,"ProgressNotificationSchema"),ProgressSchema:n(()=>$d,"ProgressSchema"),ProgressTokenSchema:n(()=>dd,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Ru,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>zu,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>Mu,"PromptMessageSchema"),PromptReferenceSchema:n(()=>Sl,"PromptReferenceSchema"),PromptSchema:n(()=>bu,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>ou,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>su,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>iu,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>pd,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Rd,"RequestIdSchema"),RequestMetaSchema:n(()=>md,"RequestMetaSchema"),RequestSchema:n(()=>gd,"RequestSchema"),ResourceContentsSchema:n(()=>Gd,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Ou,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>au,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>nu,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>Yd,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>yl,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Xd,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>_u,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>wu,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>_d,"ResultMetaObjectSchema"),ResultSchema:n(()=>wd,"ResultSchema"),RoleSchema:n(()=>Wd,"RoleSchema"),RootSchema:n(()=>bl,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Il,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>rl,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>nl,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>ol,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>qd,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>Jl,"ServerNotificationSchema"),ServerRequestSchema:n(()=>Bl,"ServerRequestSchema"),ServerResultSchema:n(()=>Fl,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>xd,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>Ku,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>Wu,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>dl,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>ss,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>cu,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>du,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>pu,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>fu,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>gu,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>mu,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>hu,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>yu,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>Su,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>fd,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Tl,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>ld,"TaskMetadataSchema"),TaskSchema:n(()=>kl,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Pl,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>xl,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>El,"TaskStatusSchema"),TextContentSchema:n(()=>Eu,"TextContentSchema"),TextResourceContentsSchema:n(()=>Vd,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>ki,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Ii,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>Nu,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>el,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>ju,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>Gu,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>tl,"ToolResultContentSchema"),ToolSchema:n(()=>Du,"ToolSchema"),ToolUseContentSchema:n(()=>Pu,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>uu,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>lu,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ei,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Ci,"UntitledSingleSelectEnumSchemaSchema")});var Tm=n(e=>Wt.safeParse(e).success,"isJSONRPCRequest"),Em=n(e=>Si.safeParse(e).success,"isJSONRPCNotification"),Fi=n(e=>_i.safeParse(e).success,"isJSONRPCResultResponse"),km=n(e=>Xn.safeParse(e).success,"isJSONRPCErrorResponse");var lo=-32020,LP=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[k.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[lo,k.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[k.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[k.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[k.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[lo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[k.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[lo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],HP={[k.ParseError]:400,[k.InvalidRequest]:400,[k.MethodNotFound]:404,[k.UnsupportedProtocolVersion]:400,[k.MissingRequiredClientCapability]:400,[lo]:400};function na(e,t){return Xc(e,t)}n(na,"parseSchema");function co(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(co,"shapeKeys");function Gi(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}n(Gi,"isStandardSchema");var Qp=!1,Vi="draft-2020-12";function uw(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:Vi});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Qp||(Qp=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=hi(e,{target:Vi,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:Am(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}n(uw,"standardSchemaToJsonSchema");function Am(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||Am(o)))}return!1}n(Am,"isProvablyObjectShapedRoot");function lw(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(lw,"formatIssue");async function Li(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>lw(o)).join(", ")}:{success:!0,data:r.value}}n(Li,"validateStandardSchema");function pw(e){let t=hi(e,{target:Vi,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(pw,"zodEmittedPattern");var mw=/\\\.\\d\{(\d+)\}/;function hw(e){let t=mw.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(s=>r.map(i=>Kn.datetime({local:o,offset:s,precision:i}))))}n(hw,"datetimeReferenceSchemas");function fw(e,t){let r;switch(e){case"email":r=[Qc()];break;case"uri":r=[ed()];break;case"date":r=[Kn.date()];break;case"date-time":r=hw(t);break}return new Set(r.map(o=>pw(o)).filter(o=>o!==void 0))}n(fw,"referencePatternsForFormat");function gw(e,t,r){return r!=="zod"?!0:fw(e,t).has(t)}n(gw,"isLibraryFormatPattern");function mo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(mo,"isJsonObject");function yw(e){try{return uw(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ge(k.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(yw,"convertStandardElicitationSchema");var Sw=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function oa(e){return Sw.has(e)||e.startsWith("x-")}n(oa,"isAnnotationOnlyJsonSchemaKeyword");var _w=new Set(["$schema",...Object.keys(as.shape.requestedSchema.shape)]),em={string:co([ss,Ci,Ii,Ti]),number:co([is]),integer:co([is]),boolean:co([vi]),array:co([Ei,ki])},ww=new Set(ss.shape.format.unwrap().options);function Rw(e,t,r,o){if(!mo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(em,e.type)?em[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||oa(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?ww.has(e.format)?(typeof c!="string"||!gw(e.format,c,r))&&o.push(`${t}.${a}`):i[a]=c:o.push(`${t}.${a}`);return i}n(Rw,"walkProperty");function bw(e,t){let r={},o=[];for(let[s,i]of Object.entries(e))s==="properties"&&mo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Rw(c,`properties.${a}`,t,o)])):_w.has(s)?r[s]=i:oa(s)||o.push(s);if(o.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(bw,"walkRequestedSchema");function vw(e,t){if(!mo(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!na(Ai,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(vw,"describeUnsupportedProperties");function Ki(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Ki(o,t[s],`${r}[${s}]`)):!mo(e)||!mo(t)?[]:Object.entries(e).flatMap(([o,s])=>{let i=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Ki(s,t[o],i):oa(o)?[]:[i]})}n(Ki,"findDroppedConstraintPaths");function Cw(e){if(!Gi(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=bw(yw(e.requestedSchema),t),o=na(as.shape.requestedSchema,r);if(!o.success)throw new ge(k.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${vw(r,o.error.message)}`);let s=Ki(r,o.data);if(s.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(o.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(o.data.properties,a));if(i.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Cw,"normalizeElicitInputParams");function Iw(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}n(Iw,"buildInputRequired");var BP=Object.assign(Iw,{elicit(e){try{return{method:"elicitation/create",params:Cw(e)}}catch(t){throw t instanceof ge?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var Tw=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Ew={IdJagTokenExchangeResponseSchema:Pi,OAuthClientInformationFullSchema:Zt,OAuthClientInformationSchema:Qn,OAuthClientMetadataSchema:Vl,OAuthClientRegistrationErrorSchema:Kl,OAuthErrorResponseSchema:ds,OAuthMetadataSchema:Ir,OAuthProtectedResourceMetadataSchema:Cr,OAuthTokenRevocationRequestSchema:Wl,OAuthTokensSchema:Rt,OpenIdProviderDiscoveryMetadataSchema:Tr,OpenIdProviderMetadataSchema:Gl},Pm={},xm={};function Om(e,t){let r=e.slice(0,-6);Pm[r]=t,xm[r]=o=>t.safeParse(o).success}n(Om,"register");for(let e of Tw)Om(e,dw[e]);for(let[e,t]of Object.entries(Ew))Om(e,t);var kw=Object.freeze(Pm),Aw=Object.freeze(xm);function Pw(e){switch(e){case"initialize":case"notifications/initialized":return po(void 0);case"server/discover":return po(ra);default:return}}n(Pw,"bootstrapOutboundCodec");var Um=6e4,xw=[wr,Zn,br,Yn],Ow=["inputResponses","requestState"];function tm(e,t){let r=e.params;if(!Hi(r))return{message:e,lifted:{}};let o=r._meta,s=Hi(o)?xw.filter(d=>d in o):[],i=t==="request"?Ow.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&Hi(o)){let d={},l={...o};for(let m of s)d[m]=o[m],delete l[m];a.envelope=d,Object.keys(l).length>0?c._meta=l:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}n(tm,"liftWireOnlyMaterial");function rm(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let s=e.validateResult(t,o);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}n(rm,"codecResultValidator");function Mm(e){return()=>e}n(Mm,"requestStateAccessor");var Uw=Mm(void 0),Mw,qw=class{static{n(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Mw=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??yi,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new de(fe.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new de(fe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Fi(s)||km(s)?this._onresponse(s):Tm(s)?this._onrequest(s,i):Em(s)?this._onnotification(s,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new de(fe.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=tm(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Yp(t.classification);if(a!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${o.era}`));return}}if($i(r.method)&&!o.hasNotificationMethod(r.method))return;let s=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;s===void 0&&i===void 0||Promise.resolve().then(()=>s===void 0?i(r):s(r,o)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:o}=tm(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=n((S,w,x)=>{let I={jsonrpc:"2.0",id:r.id,error:{code:S,message:w,...x!==void 0&&{data:x}}};i?.send(I).catch(O=>this._onerror(new Error(`Failed to send an error response: ${O}`)))},"sendErrorResponse");if(t?.classification!==void 0){let S=Yp(t.classification);if(S!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${S} but this instance serves ${s.era}`));let w=t.classification.revision??S;a(k.UnsupportedProtocolVersion,`Unsupported protocol version: ${w}`,{supported:this._supportedProtocolVersions,requested:w});return}}if(Di(r.method)&&!s.hasRequestMethod(r.method)&&!(Xp(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(k.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(k.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(o);if(d!==void 0){a(k.InvalidParams,d);return}let l=n((S,w)=>this._notificationViaCodec(this._resolveOutboundCodec(S.method),S,{...w,relatedRequestId:r.id}),"sendNotification"),m=n((S,w,x)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(S.method),S,w,{...x,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let y=o.inputResponses===void 0?void 0:zw(o.inputResponses),f={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:o.requestState===void 0?Uw:Mm(o.requestState),signal:h.signal,send:n(((S,w,x)=>{let I=this._resolveOutboundCodec(S.method);if(this._assertOutboundRequestInEra(I,S.method),Gi(w))return m(S,w,x);let O=rm(I,S.method);if(O===void 0)throw new TypeError(`'${S.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(S,O,w)}),"send"),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},R=this.buildContext(f,t);Promise.resolve().then(()=>c(r,R)).then(async S=>{if(h.signal.aborted)return;let w;try{w=s.encodeResult(r.method,S,this._outboundServerInfo())}catch(I){this._onerror(new Error(`Failed to encode result for ${r.method}: ${I}`)),a(k.InternalError,"Internal error");return}let x={result:w,jsonrpc:"2.0",id:r.id};await i?.send(x)},async S=>{if(h.signal.aborted)return;let w=Number.isSafeInteger(S.code)?S.code:k.InternalError,x={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(w),message:S.message??"Internal error",...S.data!==void 0&&{data:S.data}}};await i?.send(x)}).catch(S=>this._onerror(new Error(`Failed to send response: ${S}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Fi(e)?r(e):r(ge.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(Gi(t))return Xp(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let s=rm(o,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,s,t)}_negotiatedWireCodec(){return po(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Pw(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Di(t)&&!e.hasRequestMethod(t))throw new de(fe.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=o??{},d=Date.now(),l,m;return new Promise((h,y)=>{let f=n(q=>{y(q)},"earlyReject");if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(q){f(q);return}if(o?.signal?.aborted){let q=o.signal.reason;throw q instanceof de?q:new de(fe.RequestTimeout,String(q))}let R=e.era===ra&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,S=this._requestMessageId++;m=S;let w={...t,jsonrpc:"2.0",id:S};o?.onprogress&&(this._progressHandlers.set(S,o.onprogress),w.params={...t.params,_meta:{...t.params?._meta,progressToken:S}});let x=this._envelopeOutbound(w),I=!1,O=n(q=>{I||(this._progressHandlers.delete(S),R===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(q)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(ie=>this._onerror(new Error(`Failed to send cancellation: ${ie}`))):R.abort(),y(q instanceof de?q:new de(fe.RequestTimeout,String(q))))},"cancel");this._responseHandlers.set(S,q=>{if(o?.signal?.aborted)return;if(I=!0,q instanceof Error)return y(q);let ie;try{ie=e.decodeResult(t.method,q.result)}catch(A){return y(A instanceof Error?A:new Error(String(A)))}if(ie.kind==="invalid")return y(ie.error);if(ie.kind==="input_required"){if(o?.allowInputRequired===!0)return h(Nw(ie));let A={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:d,retry:n((K,j)=>this._requestWithSchemaViaCodec(e,K===void 0?{method:t.method}:{method:t.method,params:K},r,j),"retry")};return h(this._resolveNonCompleteResult(ie,A))}let pe=ie.result;Li(r,pe).then(A=>{A.success?h(A.data):y(new de(fe.InvalidResult,`Invalid result for ${t.method}: ${A.error}`))},y)}),l=n(()=>O(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",l,{once:!0});let N=o?.timeout??Um,we=n(()=>O(new de(fe.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(S,N,o?.maxTotalTimeout,we,o?.resetTimeoutOnProgress??!1),this._transport.send(x,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:R?.signal}).catch(q=>{this._progressHandlers.delete(S),y(q)})}).finally(()=>{l&&o?.signal?.removeEventListener("abort",l),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new de(fe.NotConnected,"Not connected");if($i(t.method)&&!e.hasNotificationMethod(t.method))throw new de(fe.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,r).catch(s=>this._onerror(s))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!Di(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((s,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,s);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,s)),!c.ok)throw c.reason==="not-in-era"?new ge(k.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)o=n(async(s,i)=>{let a=await Li(t.params,{...s.params});if(!a.success)throw new ge(k.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!$i(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,s)=>{let i=s.validateNotification(e,o);if(!i.ok)throw i.reason==="not-in-era"?new ge(k.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Li(t.params,{...o.params});if(!s.success)throw new ge(k.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Hi,"isPlainObject$1");function nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(nm,"isPlainObject");function zw(e){let t={},r=[];if(!nm(e))return{accepted:t,droppedKeys:r};for(let[o,s]of Object.entries(e)){if(!nm(s)||"method"in s||"result"in s){r.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:r}}n(zw,"partitionInputResponses");function Nw(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}n(Nw,"manualInputRequiredValue");var jw=Jp((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(c){if(!c)throw new TypeError("argument string is required");var d=typeof c=="object"?i(c):c;if(typeof d!="string")throw new TypeError("argument string is required to be a string");var l=d.indexOf(";"),m=l!==-1?d.slice(0,l).trim():d.trim();if(!o.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(l!==-1){var y,f,R;for(t.lastIndex=l;f=t.exec(d);){if(f.index!==l)throw new TypeError("invalid parameter format");l+=f[0].length,y=f[1].toLowerCase(),R=f[2],R.charCodeAt(0)===34&&(R=R.slice(1,-1),R.indexOf("\\")!==-1&&(R=R.replace(r,"$1"))),h.parameters[y]=R}if(l!==d.length)throw new TypeError("invalid parameter format")}return h}n(s,"parse");function i(c){var d;if(typeof c.getHeader=="function"?d=c.getHeader("content-type"):typeof c.headers=="object"&&(d=c.headers&&c.headers["content-type"]),typeof d!="string")throw new TypeError("content-type header is missing from object");return d}n(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}n(a,"ContentType")})),JP=Gp(jw(),1);var Dw=10*1024*1024;var $w=new Set([301,302,303,307,308]),Lw=5;function Hw(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}n(Hw,"isWithinOrigin");function Bw(e,t){let r=$w.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}n(Bw,"redirectTarget");var Jw=new WeakSet;function Os(e){return Jw.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Bw(s,a);if(!c||i===Lw)return a;let d=new URL(s),l=o==="GET"||a.status===307||a.status===308,m=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!l||!m||!Hw(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}n(Os,"fetchWithinOrigin");function sa(){Zi(),ct(),O_(),Q_(),cw()}n(sa,"preloadSchemas");var rx=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var Fw=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Gw=[0,31,28,31,30,31,30,31,31,30,31,30,31],Vw=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Kw=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Ww=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Zw=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Yw=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Xw=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Qw=/^(?:\/(?:[^~/]|~0|~1)*)*$/,eR=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,tR=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,rR=n(e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),nR=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,oR=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,sR=n(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function et(e){return e.test.bind(e)}n(et,"bind");var nx={date:qm,time:zm.bind(void 0,!1),"date-time":cR,duration:sR,uri:lR,"uri-reference":et(Ww),"uri-template":et(Zw),url:et(Yw),email:rR,hostname:et(Kw),ipv4:et(nR),ipv6:et(oR),regex:mR,uuid:et(Xw),"json-pointer":et(Qw),"json-pointer-uri-fragment":et(eR),"relative-json-pointer":et(tR)};function iR(e){return e%4===0&&(e%100!==0||e%400===0)}n(iR,"isLeapYear");function qm(e){let t=e.match(Fw);if(!t)return!1;let r=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o==2&&iR(r)?29:Gw[o])}n(qm,"date");function zm(e,t){let r=t.match(Vw);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(o<=23&&s<=59&&i<=59||o==23&&s==59&&i==60)&&(!e||a)}n(zm,"time");var aR=/t|\s/i;function cR(e){let t=e.split(aR);return t.length==2&&qm(t[0])&&zm(!0,t[1])}n(cR,"date_time");var dR=/\/|:/,uR=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function lR(e){return dR.test(e)&&uR.test(e)}n(lR,"uri");var pR=/[^\\]\\Z/;function mR(e){if(pR.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(mR,"regex");sa();var Nm=!1;var ia;ia=globalThis.crypto;async function fR(e){return(await ia).getRandomValues(new Uint8Array(e))}n(fR,"getRandomValues");async function gR(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let s=await fR(e-o.length);for(let i of s)i<r&&(o+=t[i%t.length])}return o}n(gR,"random");async function yR(e){return await gR(e)}n(yR,"generateVerifier");async function SR(e){let t=await(await ia).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(SR,"generateChallenge");async function aa(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await yR(e),r=await SR(t);return{code_verifier:t,code_challenge:r}}n(aa,"pkceChallenge");var fo=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return ze(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,e)}constructor(e){super(e),this.name=new.target.name,Xt(this,new.target)}},ho=class extends fo{static{n(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},pa=class extends fo{static{n(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},qs=class extends fo{static{n(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Ms=class extends fo{static{n(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Gx=class extends fo{static{n(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function la(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Lm(e.issuer,t)?e:void 0}n(la,"discardIfIssuerMismatch");function Lm(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(Lm,"issuersMatch");var Vx=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return ze(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Xt(this,new.target)}};function Hm(e){return e?.authorization_response_iss_parameter_supported===!0}n(Hm,"isIssParameterSupported");function Bm({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new ho("authorization_response",t,void 0);return}if(e!==t)throw new ho("authorization_response",t,e)}}n(Bm,"validateAuthorizationResponseIssuer");function _R(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(_R,"isClientAuthMethod");var ca="code",da="S256";function wR(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_R(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(wR,"selectClientAuthMethod");function RR(e,t,r,o){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":bR(s,i,r);return;case"client_secret_post":vR(s,i,o);return;case"none":CR(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(RR,"applyClientAuthentication");function bR(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(bR,"applyBasicAuth");function vR(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(vR,"applyPostAuth");function CR(e,t){t.set("client_id",e)}n(CR,"applyPublicAuth");function Jm(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Jm,"isLoopbackHost");function IR(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Jm(t.hostname))throw new qs(t.href);return t}n(IR,"assertSecureTokenEndpoint");function TR(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Jm(r.hostname))return"native"}return"web"}n(TR,"deriveApplicationType");function ER(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??TR(t.redirect_uris)}}n(ER,"resolveClientMetadata");async function jm(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=ds.parse(JSON.parse(r));return Ct.fromResponse(o)}catch(o){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Ct(le.ServerError,s)}}n(jm,"parseErrorResponse");function Dm(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${o}. Cause: ${JSON.stringify(t.message)}`)}n(Dm,"warnCredentialInvalidation");async function ma(e,t){try{return await ua(e,t)}catch(r){if(r instanceof Ct){if(r.code===le.InvalidClient||r.code===le.UnauthorizedClient)return Dm(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ua(e,t);if(r.code===le.InvalidGrant||r.code===le.InvalidDpopProof)return Dm(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await ua(e,t)}throw r}}n(ma,"auth");function kR(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}n(kR,"determineScope");async function ua(e,{serverUrl:t,authorizationCode:r,iss:o,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let l=ER(e),m=await e.discoveryState?.(),h,y,f,R,S=i;if(!S&&m?.resourceMetadataUrl&&(S=new URL(m.resourceMetadataUrl)),m?.authorizationServerUrl){if(y=m.authorizationServerUrl,h=m.resourceMetadata,f=m.authorizationServerMetadata??await Km(y,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await Gm(t,{resourceMetadataUrl:S},a)}catch(W){if(W instanceof TypeError)throw W}(f!==m.authorizationServerMetadata||h!==m.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:S?.toString(),resourceMetadata:h,authorizationServerMetadata:f})}else{let W=await qR(t,{resourceMetadataUrl:S,fetchFn:a,skipIssuerMetadataValidation:c});y=W.authorizationServerUrl,f=W.authorizationServerMetadata,h=W.resourceMetadata,R={authorizationServerUrl:String(y),resourceMetadataUrl:S?.toString(),resourceMetadata:h,authorizationServerMetadata:f}}let w=f?.issuer??String(y),x={issuer:w};if(await e.saveAuthorizationServerUrl?.(w),r!==void 0){let W=m?.authorizationServerMetadata?.issuer??m?.authorizationServerUrl;if(W===void 0){if(e.saveDiscoveryState!==void 0)throw new Ms("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",w);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Lm(W,w))throw new Ms(W,w)}R&&await e.saveDiscoveryState?.(R);let I=await AR(t,e,h),O=I&&h&&!e.validateResourceURL?h.resource:I;O&&await e.saveResourceUrl?.(fa(O));let N=kR({requestedScope:s,resourceMetadata:h,authServerMetadata:f,clientMetadata:e.clientMetadata}),we=await Promise.resolve(e.clientInformation(x)),q=la(we,w,{canPersistStamp:e.saveClientInformation!==void 0});if(q===void 0&&we?.issuer&&e.saveClientInformation===void 0)throw new Ms(we.issuer,w);if(q&&q.issuer===void 0&&(q={...q,issuer:w},await e.saveClientInformation?.(q,x)),!q){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let W=f?.client_id_metadata_document_supported===!0,Z=e.clientMetadataUrl;if(Z&&!ha(Z))throw new Ct(le.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Z}`);if(W&&Z)q={client_id:Z,issuer:w},await e.saveClientInformation?.(q,x);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");q={...await $R(y,{metadata:f,clientMetadata:l,scope:N,fetchFn:a}),issuer:w},await e.saveClientInformation(q,x)}}let ie=!e.redirectUrl;if(r!==void 0||ie){r!==void 0&&Bm({iss:o,expectedIssuer:f?.issuer,issParameterSupported:Hm(f)});let W=await DR(e,y,{metadata:f,resource:O,authorizationCode:r,iss:o,scope:N,fetchFn:a});return await e.saveTokens({...W,issuer:w},x),"AUTHORIZED"}let pe=la(await e.tokens(x),w);if(pe&&pe.issuer===void 0&&(pe={...pe,issuer:w},await e.saveTokens(pe,x)),pe?.refresh_token&&!d){let W;try{W=await jR(y,{metadata:f,clientInformation:q,refreshToken:pe.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(Z){if(Z instanceof qs)throw Z;if(!(Z instanceof Ct)||Z.code===le.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(Z instanceof Error?Z.message:String(Z))}`);else throw Z}if(W)return await e.saveTokens({...W,issuer:w},x),"AUTHORIZED"}let A=e.state?await e.state():void 0,{authorizationUrl:K,codeVerifier:j}=await zR(y,{metadata:f,clientInformation:q,state:A,redirectUrl:e.redirectUrl,scope:N,resource:O});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(K),"REDIRECT"}n(ua,"authInternal");function ha(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(ha,"isHttpsUrl");async function AR(e,t,r){let o=sm(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!As({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(AR,"selectResourceURL");var PR=new Set(["bearer","dpop"]);function Fm(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!PR.has(r.toLowerCase())||!o)return{};let s=Us(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=Us(e,"scope")||void 0,c=Us(e,"error")||void 0,d=Us(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}n(Fm,"extractWWWAuthenticateParams");function Us(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(o);if(s){let i=s[1]||s[2];if(i)return i}return null}n(Us,"extractFieldFromWwwAuth");async function Gm(e,t,r=fetch){let o=await UR(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Cr.parse(await o.json())}n(Gm,"discoverOAuthProtectedResourceMetadata");async function Vm(e,t,r=fetch){let o=Os(r);try{return await o(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Nm)throw s;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(Vm,"fetchWithCorsRetry");function xR(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(xR,"buildWellKnownPath");async function $m(e,t,r=fetch){return await Vm(e,{"MCP-Protocol-Version":t},r)}n($m,"tryMetadataDiscovery");function OR(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}n(OR,"shouldAttemptFallback");async function UR(e,t,r,o){let s=new URL(e),i=o?.protocolVersion??os,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let d=xR(t,s.pathname);a=new URL(d,o?.metadataServerUrl??s),a.search=s.search}let c=await $m(a,i,r);return!o?.metadataUrl&&OR(c,s.pathname)&&(c=await $m(new URL(`/.well-known/${t}`,s),i,r)),c}n(UR,"discoverMetadataWithFallback");function MR(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"},{url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(MR,"buildDiscoveryUrls");async function Km(e,{fetchFn:t=fetch,protocolVersion:r=os,skipIssuerValidation:o=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=MR(e);for(let{url:a,type:c}of i){let d=await Vm(a,s,t);if(!d)continue;if(!d.ok){if(await d.text?.().catch(()=>{}),d.status<500||d.status===502)continue;throw new Error(`HTTP ${d.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let l=c==="oauth"?Ir.parse(await d.json()):Tr.parse(await d.json());if(!o){let m=typeof e=="string"?e:e.href;if(!(l.issuer===m||m.endsWith("/")&&l.issuer===m.slice(0,-1)))throw new ho("metadata",m,l.issuer)}return l}}n(Km,"discoverAuthorizationServerMetadata");async function qR(e,t){let r,o;try{r=await Gm(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}o||(o=String(new URL("/",e)));let s=await Km(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:s,resourceMetadata:r}}n(qR,"discoverOAuthServerInfo");function fa(e){return typeof e=="string"?e:e.href}n(fa,"resourceIndicatorToString");async function zR(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ca))throw new Error(`Incompatible auth server: does not support response type ${ca}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(da))throw new Error(`Incompatible auth server: does not support code challenge method ${da}`)}else c=new URL("/authorize",e);let d=await aa(),l=d.code_verifier,m=d.code_challenge;return c.searchParams.set("response_type",ca),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",da),c.searchParams.set("redirect_uri",String(o)),i&&c.searchParams.set("state",i),s&&c.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",fa(a)),{authorizationUrl:c,codeVerifier:l}}n(zR,"startAuthorization");function NR(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(NR,"prepareAuthorizationCodeRequest");async function Wm(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=IR(t?.token_endpoint??new URL("/token",e)),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",fa(i)),!s&&o&&RR(wR(o,t?.token_endpoint_auth_methods_supported??[]),o,l,r);let m=n(async()=>{let f=new Headers(l);return s&&await s(f,r,d,t),a&&f.set("DPoP",await a.buildProof({htm:"POST",htu:d})),Os(c??fetch)(d,{method:"POST",headers:f,body:r})},"requestOnce"),h=await m();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===le.UseDpopNonce&&(a.observeNonce(h,d),h=await m()),a?.observeNonce(h,d),!h.ok)throw await jm(h);let y=await h.json();try{return Rt.parse(Wi(y))}catch(f){throw typeof y=="object"&&y!==null&&"error"in y?await jm(JSON.stringify(y)):f}}n(Wm,"executeTokenRequest");async function jR(e,{metadata:t,clientInformation:r,refreshToken:o,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:o,...await Wm(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}n(jR,"refreshAuthorization");async function DR(e,t,{metadata:r,resource:o,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&Bm({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Hm(r)});let d=r?.issuer??String(t),l=n(async()=>{let f=await e.clientInformation({issuer:d}),R=la(f,d,{canPersistStamp:!1});if(f&&R===void 0)throw new Ms(String(f.issuer),d);return R},"readClientInformation"),m=await l(),h=a??e.clientMetadata.scope,y;if(e.prepareTokenRequest&&(y=await e.prepareTokenRequest(h)),!y){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");y=NR(s,await e.codeVerifier(),e.redirectUrl)}return m??=await l(),Wm(t,{metadata:r,tokenRequestParams:y,clientInformation:m,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:c})}n(DR,"fetchToken");async function $R(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:s}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...o===void 0?{}:{scope:o}},c=await Os(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new pa({status:c.status,body:await c.text(),submittedMetadata:a});return Zt.parse(Wi(await c.json()))}n($R,"registerClient");var Kx=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return ze(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return ze(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Xt(this,new.target)}};function go(e){let t=Wt.safeParse(e);return t.success?t.data.id:void 0}n(go,"parseJsonRpcRequestId");function ga(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return go(t)}catch{return}}n(ga,"readJsonRpcRequestIdFromBody");function ya(e){return Xn.parse({jsonrpc:vr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(ya,"jsonRpcErrorResponse");function Zm(e){return new xs([cs.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Zm,"urlElicitationRequiredError");function It(e){return(e??"").split(";")[0].trim().toLowerCase()}n(It,"mediaTypeEssence");var LR=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function dt(e){for(let t of LR)e.delete(t);return e}n(dt,"deleteEncodedBodyHeaders");function Ym(){let e=es.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}n(Ym,"currentRuntime");var HR=new Set(["gzip","x-gzip","deflate","br","zstd"]);function Tt(e,t=Ym()){let r=e.get("content-encoding")?.trim();if(!r||r.toLowerCase()==="identity")return!1;switch(t){case"deno":return!0;case"workerd":return r!=="gzip"&&r!=="br";default:return!r.toLowerCase().split(",").every(o=>HR.has(o.trim()))}}n(Tt,"isBodyStillEncoded");function Xm(e){return Tt(e)?e:dt(e)}n(Xm,"deleteEncodedBodyHeadersIfDecoded");function Qm(e,t=Ym()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?Tt(e,t):e.has("content-length"))?e:dt(e)}n(Qm,"deleteEncodedBodyHeadersIfRuntimeDecoded");var th=10*1024*1024,BR=1024,JR=32,FR=64,Qt=class extends Error{constructor(r,o=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=o;this.name="SseEventTooLargeError"}maxEventChars;comment;static{n(this,"SseEventTooLargeError")}},GR=10;function VR(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}n(VR,"handleRejection");function rh(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}n(rh,"fieldName");var yo=class{static{n(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#d=!1;#g=/\r\n|\r|\n/g;#s="";#u=[];#o=[];#c=0;#l=!1;#p=!1;#y=!1;#i=!1;#m=!1;#S=0;#C=0;#a=[];#h=0;#f=[];#_;#w;#R;#b=[];constructor(t={}){let r=t.maxEventChars??th;if(!Number.isInteger(r)||r<=0)throw new RangeError(`maxEventChars must be a positive integer, got ${r}`);this.#e=r,this.#r=t.onOversize==="discard",this.#t=t.emitLoneComments===!0}get discardedEvents(){return this.#S}get discardedComments(){return this.#C}get discarding(){return this.#i||this.#m}get idle(){return this.#c===0&&!this.#l&&!this.#i&&this.#a.length===0}push(t){let r=[];return this.#T(this.#I(this.#n.decode(t,{stream:!0})),r),r}end(){let t=[];return this.#T(this.#I(this.#n.decode()),t),(this.#c>0||this.#l)&&this.#A(t,!1),this.#i||this.#P(t,!1),this.#i=!1,t}#I(t){return this.#d||t===""?t:(this.#d=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let o=0;this.#y&&(this.#y=!1,t.charCodeAt(0)===GR&&(o=1));let s=this.#g;s.lastIndex=o;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(o,i.index)),this.#A(r),o=i.index+i[0].length,i[0]==="\r"&&o===t.length&&(this.#y=!0),i=s.exec(t);this.#E(t.slice(o))}#E(t){if(t!==""){if(this.#i||this.#m){this.#l=!0;return}if(this.#c===0?this.#s=t:(this.#o.push(t),this.#o.length>=FR&&(this.#u.push(this.#o.join("")),this.#o=[])),this.#c+=t.length,this.#h+this.#c>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#m=!0,this.#S++,this.#C++):this.#k(r),this.#l=!0}}}#O(){return this.#t&&this.#a.length===0&&this.#s.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new Qt(this.#e,t);this.#x(),this.#p=!1,this.#v(),this.#i=!0,this.#S++}#v(){this.#s="",this.#u.length>0&&(this.#u=[]),this.#o.length>0&&(this.#o=[]),this.#c=0}#A(t,r=!0){let o=this.#u.length===0&&this.#o.length===0?this.#s:this.#s+this.#u.join("")+this.#o.join(""),s=o===""&&!this.#l;if(this.#v(),this.#l=!1,this.#m){this.#m=!1,this.#p=!0;return}if(s){this.#i?this.#i=!1:this.#p&&this.#a.length===0?(this.#p=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#p=!1,this.#P(t,!0));return}if(this.#i)return;if(this.#t&&r&&this.#a.length===0&&o.charCodeAt(0)===58){t.push({lines:[o],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[o.slice(1)],terminated:!0,lone:!0}),this.#p=!0;return}if(this.#h+=o.length,this.#a.push(o),this.#a.length>BR&&(this.#h+=Math.max(0,JR-o.length),this.#h>this.#e)){this.#k();return}if(o.charCodeAt(0)===58){this.#b.push(o.slice(1));return}let i=o.indexOf(":"),a=i===-1?o:o.slice(0,i),c=i===-1?"":o.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#f.push(c);break;case"event":this.#_=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#R=Number(c));break;default:break}}#P(t,r){this.#a.length>0&&t.push({lines:this.#a,data:this.#f.length>0?this.#f.join(`
26
+ `):void 0,event:this.#_,id:this.#w,retry:this.#R,comments:this.#b,terminated:r}),this.#x()}#x(){this.#a=[],this.#h=0,this.#f=[],this.#_=void 0,this.#w=void 0,this.#R=void 0,this.#b=[]}};function Sa(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}n(Sa,"assertSingleLine");function _a(e){if("lines"in e){for(let o of e.lines){if(/[\r\n]/.test(o))throw new TypeError("SSE event line must not contain a line break");if(o==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(o=>`${o}
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??[])Sa("comment",r),t+=`:${r}
30
+ `;if(e.event!==void 0&&(Sa("event",e.event),t+=`event: ${e.event}
31
+ `),e.id!==void 0){if(Sa("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
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
+ `}n(_a,"serializeSseEvent");var KR=new Set(["data","event","id","retry"]);function nh(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!KR.has(rh(t)))}n(nh,"hasUnknownSseFields");function Ra(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(o=>rh(o)!=="data"),...r.map(o=>`data: ${o}`)],data:r.join(`
36
+ `)}}n(Ra,"replaceSseData");var oh=Symbol("sse.terminate");function ba(...e){return{[oh]:!0,events:e}}n(ba,"terminateSse");function WR(e){return typeof e=="object"&&e!==null&&oh in e}n(WR,"isTerminate");var ZR=64,eh=new Uint8Array(0),wa=class{static{n(this,"SseRawEventBytes")}#e=eh;#r=0;#t=[];#n=0;get length(){return this.#r+this.#n}get views(){return this.#t.length}push(t){t.length!==0&&(this.#t.push(t),this.#n+=t.length,this.#t.length>=ZR&&this.#d())}take(){let t;return this.#r===0?t=eb(this.#t):(this.#d(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=eh,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#d(){let t=this.#r+this.#n;if(t>this.#e.length){let r=new Uint8Array(Math.max(t,this.#e.length*2));r.set(this.#e.subarray(0,this.#r)),this.#e=r}for(let r of this.#t)this.#e.set(r,this.#r),this.#r+=r.length;this.#t=[],this.#n=0}},So=10,zs=13,YR=[239,187,191];function XR(e){let t=[],r=0;for(let o=0;o<e.length;o++){let s=e[o];(s===So||s===zs&&e[o+1]!==So)&&(t.push(e.subarray(r,o+1)),r=o+1)}return r<e.length&&t.push(e.subarray(r)),t}n(XR,"splitLines");function QR(e){let t=e[e.length-1];return t===So||t===zs}n(QR,"endsLine");function va(e,t,r={}){let o=r.failureMode??"closed",s=o==="open"&&r.onOversize!=="discard",i=r.maxEventChars??th,a=new yo(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,l={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},m=e.getReader(),h=!1,y=!1,f=0,R=new wa,S=0,w=!1,x,I,O=n(A=>{h=!0,d.abort(A),m.cancel(A).catch(()=>{})},"stop"),N=n((A,K)=>{try{VR(r.onFailure?.(A,K),()=>{})}catch{}},"report"),we=n(A=>{N(A,{mode:o,kind:"oversize",...A.comment?{comment:!0}:{}})},"reportOversize"),q=n(A=>{if(!("lines"in A))return _a(A);if(A.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return A.lone===!0&&A.lines.length>0&&A.lines.every(K=>K.charCodeAt(0)===58)?_a({...A,terminated:!1}):_a(A)},"write"),ie=n((A,K)=>WR(A)?{text:A.events.map(q).join(""),terminate:!0}:A===void 0?{text:K===void 0?"":q(K),terminate:!1}:A===null?{text:"",terminate:!1}:{text:(Array.isArray(A)?A:[A]).map(q).join(""),terminate:!1},"render"),pe=n(A=>{if(!s)try{return a.push(A).map(j=>({event:j}))}catch(j){throw j instanceof Qt&&we(j),j}let K=[];for(let j of XR(A)){if(w&&(w=!1,j[0]===So)){a.push(j),f+=j.length,K.push({raw:j,atStart:!1});continue}let W=a.discardedEvents,Z=a.discardedComments,De=a.discarding;!De&&R.length===0&&(S=f),f+=j.length;for(let Oe of a.push(j))K.push({event:Oe});De?(K.push({raw:j,atStart:!1}),w=!a.discarding&&j[j.length-1]===zs):a.discardedEvents>W?(we(new Qt(i,a.discardedComments>Z)),R.push(j),K.push({raw:R.take(),atStart:S===0}),w=!a.discarding&&j[j.length-1]===zs):QR(j)&&a.idle?R.clear():R.push(j)}return K},"parse");return new ReadableStream({async pull(A){if(I!==void 0){A.error(I.error);return}try{for(;;){let K=await m.read();if(h)return;let j,W=!1,Z=!1;if(K.done){j=[],Z=s&&a.discarding;let G=a.discardedEvents,ae=a.discardedComments,ke;try{ke=a.end()}catch(ee){throw ee instanceof Qt&&we(ee),ee}for(let ee of ke)ee.terminated?j.push({event:ee}):W=!0;a.discardedEvents>G&&R.length>0&&(we(new Qt(i,a.discardedComments>ae)),j.push({raw:R.take(),atStart:S===0}),Z=!0),R.clear(),W||=Z}else j=pe(K.value);let De=!1,Oe=n(G=>{G.length>0&&(A.enqueue(G),De=!0,y=!0)},"enqueue"),$e=n(G=>{G!==""&&Oe(c.encode(G))},"emit");for(let G of j){if("raw"in G){!y&&!G.atStart&&YR.every((ee,Ge)=>G.raw[Ge]===ee)&&$e(`
37
+ `),Oe(G.raw.slice()),x=G.raw[G.raw.length-1];continue}let{event:ae}=G,ke;try{let ee=await t(ae,l);if(h)return;ke=ie(ee,ae)}catch(ee){if(h)return;if(N(ee,{mode:o,kind:"transform",event:ae}),o==="closed")throw ee;ke={text:q(ae),terminate:!1}}if($e(ke.text),ke.terminate){O("SSE stream terminated by its rewriter"),A.close();return}}if(K.done){if(r.end!==void 0){let G;try{let ae=await r.end({...l,unterminated:W});if(h)return;G=ie(ae,void 0)}catch(ae){if(h)return;if(N(ae,{mode:o,kind:"end"}),o==="closed")throw ae;G={text:"",terminate:!1}}if(Z&&G.text!==""&&$e(x===So?`
38
+ `:`
39
+
40
+ `),$e(G.text),G.terminate){O("SSE stream terminated by its rewriter"),A.close();return}}h=!0,A.close();return}if(De)return}}catch(K){h||(O(K),(A.desiredSize??0)<0?I={error:K}:A.error(K))}},cancel(A){if(!h)return h=!0,d.abort(A),m.cancel(A)}},{highWaterMark:0})}n(va,"rewriteSseStream");function eb(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((o,s)=>o+s.length,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}n(eb,"concatBytes");function sh(e,t,r){if(e.body===null)return e;let o=dt(new Headers(e.headers));return o.set("content-type","text/event-stream"),new Response(va(e.body,t,r),{status:e.status,statusText:e.statusText,headers:o})}n(sh,"rewriteSseResponse");var ch=new Set(["jsonrpc","method","id","params"]),dh=new Set(["name","uri","ref"]),uh=new Set(["type","name","uri"]),tb=/[^\u0000-\u007f]/,rb=34,nb=92,ih=123,ob=125,sb=91,ib=93,ab=58,ah=44;function Ca(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Ca,"isRecord");function _o(e){return e.toUpperCase().toLowerCase()}n(_o,"foldCase");function Ia(e,t){return Object.keys(e).some(r=>{let o=_o(r);return o!==r&&t.has(o)})}n(Ia,"hasCaseVariant");function cb(e){let t={batch:void 0,member:ch,params:dh,ref:uh},r=[],o=0,s=n(i=>{let a=r.at(-1);if(a===void 0)return i?"member":"batch";if(i){if(a.role==="batch")return"member";if(a.role==="member"&&a.key==="params")return"params";if(a.role==="params"&&a.key==="ref")return"ref"}},"childRole");for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a===rb){let c=i;for(;;){if(c=e.indexOf('"',c+1),c===-1)return!0;let l=0;for(;e.charCodeAt(c-1-l)===nb;)l++;if(l%2===0)break}let d=o>0?void 0:r.at(-1);if(d?.isObject&&d.expectKey){let l=e.slice(i,c+1),m=l.includes("\\")?JSON.parse(l):l.slice(1,-1);if(tb.test(m))return!0;d.key=m;let h=_o(m);if(t[d.role]?.has(h)){if(d.seen.has(h))return!0;d.seen.add(h)}}i=c}else if(a===ih||a===sb){let c=a===ih,d=o>0?void 0:s(c);d===void 0?o++:r.push({role:d,isObject:c,seen:new Set,expectKey:c})}else if(a===ob||a===ib)o>0?o--:r.pop();else if(o===0&&(a===ab||a===ah)){let c=r.at(-1);c?.isObject&&(c.expectKey=a===ah)}}return!1}n(cb,"hasUnsafeKeyInText");function lh(e){for(let t of e.envelope.messages){let r=t.raw;if(Ca(r)){if(Ia(r,ch))return!0;if(!(typeof r.method!="string"||!e.isCapabilityMethod(r.method)||!Ca(r.params))&&(Ia(r.params,dh)||Ca(r.params.ref)&&Ia(r.params.ref,uh)))return!0}}return cb(e.text)}n(lh,"hasAmbiguousIdentifyingKeys");var db=n(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),ub=47,ph=44,lb=38,Ta=n(e=>e!==ub&&e!==ph,"VALUE"),pb=n(e=>!db(e),"ANY"),mb=n(e=>e!==lb,"QUERY_VALUE"),hb=["+","#",".","/","?","&"],Ea=class{static{n(this,"Builder")}edges=[[]];current=0;#e(){return this.edges.push([]),this.edges.length-1}literal(t){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:n(i=>i===o,"test"),to:s}),this.current=s}}plus(t){let r=this.#e();this.edges[this.current].push({test:t,to:r}),this.edges[r].push({test:t,to:r}),this.current=r}value(t){if(this.plus(Ta),!t)return;let r=this.current,o=this.#e();this.edges[r].push({test:n(s=>s===ph,"test"),to:o}),this.edges[o].push({test:Ta,to:r})}};function mh(e){let t=new Ea,r="",o=0;for(;o<e.length;){if(e[o]!=="{"){r+=e[o],o++;continue}let s=e.indexOf("}",o);if(s===-1)return;t.literal(r),r="";let i=e.slice(o+1,s),a=hb.find(l=>i.startsWith(l))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(l=>l.replace("*","").trim()).filter(l=>l.length>0);switch(a){case"?":case"&":d.forEach((l,m)=>{t.literal(`${m===0?a:"&"}${l}=`),t.plus(mb)});break;case"+":case"#":t.plus(pb);break;case".":t.literal("."),t.plus(Ta);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}o=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}n(mh,"compileUriTemplate");function hh(e,t){if(t.length>1e6)return!1;let{edges:r,accept:o}=e,s=new Array(r.length).fill(-1),i=[0];for(let a=0;a<t.length;a++){let c=t.charCodeAt(a),d=[];for(let l of i)for(let m of r[l])s[m.to]!==a&&m.test(c)&&(s[m.to]=a,d.push(m.to));if(d.length===0)return!1;i=d}return i.includes(o)}n(hh,"matchesUriTemplate");var $s=p.record(p.string(),p.unknown()),fb=p.record(p.string(),p.unknown()),Et=p.array(p.string().min(1)).min(1).optional(),gb=p.object({name:p.string().min(1),description:p.string().min(1).optional(),annotations:fb.optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),yb=p.object({name:p.string().min(1),description:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),Sb=p.object({uri:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),_b=p.object({uriTemplate:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),wb=p.array(p.union([p.string(),gb])),Rb=p.array(p.union([p.string(),yb])),bb=p.array(p.union([p.string(),Sb])),vb=p.array(p.union([p.string(),_b])),Cb=p.object({module:p.unknown(),export:p.string().min(1)}).strict(),Ib=p.object({mode:p.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:p.string().min(1).optional(),groupClaim:p.string().min(1).optional(),identifier:Cb.optional()}).strict(),Tb=p.object({tools:wb.optional(),prompts:Rb.optional(),resources:bb.optional(),resourceTemplates:vb.optional(),accessControl:Ib.optional()}).strict(),lt=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read","resources/subscribe","resources/unsubscribe"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function Eb(e,t){return tp(Tb,e,`MCP capability filter policy "${t}"`)}n(Eb,"parseMcpCapabilityFilterOptions");function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Q,"isRecord");function ut(e){return typeof e.method=="string"?e.method:void 0}n(ut,"messageMethod");function bo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(bo,"correlationKey");function Rh(e){let t=new Set,r=new Map;for(let o of e){let s=bo(o);if(s===void 0)continue;t.add(s);let i=String(o),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return o=>{let s=bo(o);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(o));return i?.size===1?[...i][0]:void 0}}n(Rh,"createReplyIdMatcher");function fh(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(fh,"asStringArray");function gh(e,t){if(!Q(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,s)=>Q(o)?o[s]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n(gh,"readClaimValues");function Oa(e,t){if(typeof e=="string")return{key:e,public:!1};if(!Q(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:fh(e.roles),groups:fh(e.groups),public:e.public===!0}}n(Oa,"normalizeEntry");function kb(e,t,r){if(e.public)return!0;let o=e.roles??[],s=e.groups??[];return o.length===0&&s.length===0?!1:o.some(i=>t.has(i))||s.some(i=>r.has(i))}n(kb,"isCallerAllowed");function Ns(e,t,r,o){if(e===void 0)return;let s=[];for(let i of e){let a=Oa(i,t);a!==void 0&&kb(a,r,o)&&s.push(a.key)}return s}n(Ns,"allowedKeys");var bh=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(gh(e.user?.data,o)),a=new Set(gh(e.user?.data,s));return{tools:Ns(r.tools,"name",i,a),prompts:Ns(r.prompts,"name",i,a),resources:Ns(r.resources,"uri",i,a),resourceTemplates:Ns(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function Ab(e,t){let r=[];for(let o of lt){let s=e[o.option];if(s!==void 0)for(let i of s){let a=Oa(i,o.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new Y(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}n(Ab,"assertNoConflictingMarkup");function Pb(e,t){let r=[];for(let o of lt){let s=e[o.option];if(s!==void 0)for(let i of s){let a=Oa(i,o.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new Y(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}n(Pb,"assertNoMarkup");function xb(e,t){let r=e.identifier;if(r===void 0)throw new Y(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=o;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new T(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof d!="object"||Array.isArray(d))throw new T(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}n(xb,"buildCustomResolver");function Ob(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new Y(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return xb(r,t)}if(o==="rolesAndGroups")return Ab(e,t),bh;Pb(e,t)}n(Ob,"buildCapabilityResolver");function Ub(e){let t={};for(let r of lt){let o=e[r.option];if(o===void 0)continue;let s=new Map;for(let i of o){let a=Vb(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}n(Ub,"buildProjectionMaps");function vh(e){return e===void 0?void 0:lt.find(t=>t.listMethod===e)}n(vh,"findListRule");function Ua(e){return e===void 0?void 0:lt.find(t=>t.directMethods.includes(e))}n(Ua,"findDirectRule");var Ls="completion/complete",Ch=["prompts","resources","resourceTemplates"];function Ih(e){return e===Ls||Ua(e)!==void 0}n(Ih,"isCapabilityMethod");var Mb=[...lt.flatMap(e=>[e.listMethod,...e.directMethods]),Ls];function qb(e){let t=_o(e.trim()),r=Mb.find(o=>_o(o)===t);return r!==void 0&&r!==e?r:void 0}n(qb,"methodVariantOf");function zb(e,[t,r]){return{code:k.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}n(zb,"invalidParams");function js(e){return t=>({code:k.InvalidParams,message:`${e} "${us(t)}" not found`})}n(js,"namedNotFound");function Nb(e,t){return{code:Zl(t),message:"Resource not found",data:{uri:Xl(e,Yl)}}}n(Nb,"resourceNotFound");function jb(e){let t=ut(e);if(t===void 0||!Ih(t))return[];let r=Q(e.raw)?e.raw.params:void 0,o=n((d,l)=>Q(d)&&typeof d[l]=="string"?d[l]:void 0,"stringAt"),s=n(d=>Q(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==Ls){let d=Ua(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:o(r,"uri"),issue:s("params.uri"),notFound:Nb}]:[{options:[d.option],target:o(r,"name"),issue:s("params.name"),notFound:js(d.option==="tools"?"Tool":"Prompt")}]}let i=Q(r)?r.ref:void 0,a=Q(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:o(i,"name"),issue:["params.ref.name","a string"],notFound:js("Prompt")}];if(a==="ref/resource"){let d=o(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&Db(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:js("Resource template")}]}let c=Q(r)?Q(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Ch,target:void 0,issue:c,notFound:js("Prompt")}]}n(jb,"capabilityAccesses");function Db(e){let t=!1,r=0;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else $b(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}n(Db,"hasTemplateExpression");function $b(e){return e>32&&e<127?!1:Lb.test(String.fromCharCode(e))}n($b,"isWhitespaceCode");var Lb=/\s/;function Hb(e){return e.type==="invalid"&&(!Q(e.raw)||e.raw.jsonrpc!=="2.0")}n(Hb,"isNonJsonRpcMember");function Bb(e){return Q(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}n(Bb,"hasNonStringMethod");function Th(e){return e.type==="request"||e.type==="invalid"&&ut(e)!==void 0}n(Th,"awaitsReply");var Jb={code:k.MethodNotFound,message:"Method not found"},yh={code:k.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},Fb={code:k.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},Gb="2025-06-18";function Eh(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}n(Eh,"isValidRequestId");function kh(e){return Q(e.raw)&&!Object.hasOwn(e.raw,"id")}n(kh,"isSentAsNotification");function wo(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}n(wo,"jsonRpcError");function Ro(e,t,r){return Response.json(wo(t,r),{status:e})}n(Ro,"jsonRpcErrorResponse");function Ds(e){return Ro(400,{code:k.InvalidRequest,message:`Invalid Request: ${e}`})}n(Ds,"invalidRequestResponse");function ka(e,t){if(kh(e))return{status:400,body:wo({code:k.InvalidRequest,message:`Invalid Request: a notification cannot use ${us(ut(e)??"this method")}; send it as a request with an id`})};let r=Q(e.raw)?e.raw.id:void 0;return Eh(r)?{status:200,body:wo(t,r)}:{status:400,body:wo({code:k.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}n(ka,"refusalOf");function Sh(e,t){let[r]=[...t];if(e.shape!=="batch"){let{status:i,body:a}=ka(r[0],r[1]);return Response.json(a,{status:i})}let o=e.protocolVersion;if(o!==void 0&&o>=Gb)return Ds(`protocol version ${us(o)} does not support JSON-RPC batches`);let s=e.messages.flatMap(i=>i.type==="result"||i.type==="error"||kh(i)?[]:[ka(i,t.get(i)??Fb).body]);if(s.length===0){let{status:i,body:a}=ka(r[0],r[1]);return Response.json(a,{status:i})}return Response.json(s)}n(Sh,"refusalResponse");function Vb(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!Q(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(Vb,"buildProjection");function _h(e){let t=e.base[e.property],r=e.overlay[e.property];return Q(r)?Q(t)?{...t,...r}:r:t}n(_h,"mergeRecordProperty");function Kb(e,t){let r={...e,...t.overlay},o=_h({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let s=_h({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}n(Kb,"applyProjection");var Ie=Symbol("unreadable");function Wb(e,t,r,o){let s=e.result;if(!Q(s))return Ie;let i=s[t.resultProperty];return!Array.isArray(i)||Object.hasOwn(s,"nextCursor")&&s.nextCursor!==null&&typeof s.nextCursor!="string"?Ie:{...e,result:{...s,[t.resultProperty]:i.flatMap(a=>{if(!Q(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let d=r.get(c);return d===void 0?[]:[Kb(a,d)]})}}}n(Wb,"filterAndProjectItems");function Ah(e,t){let r=vh(ut(e)),o=r===void 0?void 0:t[r.option];return r===void 0||o===void 0?null:{rule:r,projections:o}}n(Ah,"listTargetOf");function Zb(e,t,r){return Q(e)&&lt.some(o=>o!==t?.rule&&r[o.option]!==void 0&&Object.hasOwn(e,o.resultProperty))}n(Zb,"carriesUnfilteredList");function Yb(e){let{envelope:t,projectionMaps:r,allowedSets:o}=e,s=n(h=>Ah(h,r),"listTarget"),i=t.messages.filter(Th),a=new Map;for(let h of i){let y=bo(h.id);y!==void 0&&!a.get(y)&&a.set(y,s(h))}let c=Rh(i.map(h=>h.id)),d=t.messages[0],l=n(h=>{if(t.shape!=="batch")return d===void 0?void 0:s(d);let y=c(h);return y===void 0?void 0:a.get(y)},"targetForReply"),m=n(h=>{if(!Q(h))return Ie;if(!("result"in h))return"error"in h||"method"in h?h:Ie;let y=l(h.id);return y===void 0||Zb(h.result,y,r)?Ie:y===null?h:Wb(h,y.rule,y.projections,o?.[y.rule.option])},"filterMessage");return h=>{if(!Array.isArray(h))return m(h);if(t.shape!=="batch")return Ie;let y=h.map(m);return y.includes(Ie)?Ie:y}}n(Yb,"createReplyFilter");function Xb(e){return It(e.headers.get("content-type")).includes("json")}n(Xb,"isJsonResponse");function Qb(e){return It(e.headers.get("content-type"))==="text/event-stream"}n(Qb,"isEventStreamResponse");var ev=10*1024*1024,tv=/^[\w.~:/+=-]{0,256}$/;function rv(e){if(nh(e))return null;let t=!1;for(let o of e.lines){let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&tv.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=n(o=>o.trim()===""?o:"","blank");return{...e,lines:e.lines.map(o=>o.startsWith(":")?`:${r(o.slice(1))}`:o),comments:e.comments.map(r)}}n(rv,"inspectSseLines");var Ph="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",nv="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function Pa(e,t){let r=e.messages.filter(Th),o=new Map,s=new Set;for(let l of r){let m=l.id,h=bo(m);m==null||h===void 0||(o.set(h,m),Ah(l,t)!==null&&s.add(h))}let i=Rh(r.map(l=>l.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:bo(a.id),d=new Set;return{keyOf(l){if(!(!Q(l)||!("result"in l||"error"in l)))return e.shape==="batch"?i(l.id):c},isPending:n(l=>l!==void 0&&o.has(l),"isPending"),hasFailed:n(l=>d.has(l),"hasFailed"),answer(l){l!==void 0&&o.delete(l)},fail(l){return[...l].flatMap(m=>{let h=o.get(m);return h===void 0?[]:(o.delete(m),d.add(m),[{jsonrpc:"2.0",id:h,error:{code:k.InternalError,message:s.has(m)?Ph:nv}}])})},pendingKeys:n(()=>[...o.keys()],"pendingKeys")}}n(Pa,"createReplyTracker");function xh(e,t,r){let o=[],s=0;for(let i of e){let a=r.keyOf(i);if(a!==void 0&&r.hasFailed(a))continue;let c=Array.isArray(i)?Ie:t(i);c!==Ie?(o.push(c),r.answer(a)):r.isPending(a)?o.push(...r.fail([a])):s++}return{replies:o,dropped:s}}n(xh,"filterBatchMembers");function ov(e){let{response:t,envelope:r,projectionMaps:o,filterReply:s,warn:i}=e,a=Pa(r,o),c=!1,d=n(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),l=n(h=>h.map(y=>({data:JSON.stringify(y)})),"toEvents"),m=n(()=>a.pendingKeys().length===0,"isDone");return sh(t,h=>{let y=rv(h);if(y===null)return d("it has a line the filter does not forward");if(y.data===void 0||y.data==="")return y;let f;try{f=JSON.parse(y.data)}catch{return d("its data is not JSON")}let R=a.keyOf(f);if(R!==void 0&&a.hasFailed(R))return null;let S=s(f);if(S===Ie&&r.shape==="batch"&&Array.isArray(f)){let{replies:w,dropped:x}=xh(f,s,a);if(x>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),w.length===0)return null;let I=Ra(y,JSON.stringify(w));return m()?ba(I):I}if(S===Ie){if(!a.isPending(R))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let w=l(a.fail([R]));return m()?ba(...w):w}for(let w of Array.isArray(S)?S:[S])a.answer(a.keyOf(w));return S===f?y:Ra(y,JSON.stringify(S))},{maxEventChars:ev,onOversize:"discard",end:n(({unterminated:h,discardedEvents:y})=>((h||y>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||y>0?l(a.fail(a.pendingKeys())):null),"end"),onFailure:n((h,y)=>{i(`could not rewrite the upstream SSE stream (${y.kind})`)},"onFailure")})}n(ov,"filterEventStream");var Aa=Symbol("access unresolved"),wh=10*1024*1024,Oh="the request body could not be read";async function sv(e,t,r){let o=e.clone().body;if(o===null)return{blank:!0,overLimit:!1};let s=o.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:l}=await s.read(),m=d?i.decode():i.decode(l,{stream:!0});if(a+=m.length,c&&=!/\S/.test(m),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}n(sv,"scanBody");function Ma(e){return Array.isArray(e)?`batch member 0: ${Ma(e[0])}`:Q(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}n(Ma,"invalidMessageReason");async function iv(e,t){if(e.body===null)return;let r=n(()=>He.contentTooLarge(e,t,{detail:"The request body is larger than the MCP capability filter can inspect."}),"tooLarge");if(Number(e.headers.get("content-length")??Number.NaN)>wh)return r();let s=It(e.headers.get("content-type")).includes("json"),i=n(()=>He.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=n(()=>Ro(400,{code:k.ParseError,message:`Parse error: ${Oh}`}),"unreadable"),c;try{c=await sv(e,wh,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(m){return m instanceof SyntaxError?Ro(400,{code:k.ParseError,message:"Parse error: Invalid JSON"}):a()}let l=Q(d)?d.id:void 0;return Ro(400,{code:k.InvalidRequest,message:`Invalid Request: ${Ma(d)}`},Eh(l)?l:void 0)}n(iv,"refuseUninspectable");var xa=class extends ns{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let o=Eb(t,r);super(o,r),this.#r=r,this.#e=Ub(o),this.#t=Ob(o,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,mh(i)]))}async handler(t,r){let o=await Bp(t);if(o===null)return await iv(t,r)??t;let s=o.messages.findIndex(Hb);if(s!==-1)return Ds(`batch member ${s}: ${Ma(o.messages[s].raw)}`);let i=o.messages.findIndex(Bb);if(i!==-1)return Ds(o.shape==="batch"?`batch member ${i}: method must be a string`:"method must be a string");let a=Hp(o);if(a===void 0)try{a=await t.clone().text()}catch{return Ro(400,{code:k.ParseError,message:`Parse error: ${Oh}`})}if(lh({envelope:o,text:a,isCapabilityMethod:Ih}))return Ds("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let c=new Map;for(let f of o.messages){let R=ut(f),S=R===void 0?void 0:qb(R);S!==void 0&&this.#s(S)&&c.set(f,Jb)}let d=c.size===0&&this.#t!==void 0&&this.#u(o)?await this.#c(t,r):void 0;if(c.size===0)for(let f of o.messages){let R=d===Aa?this.#s(ut(f)??"")?yh:void 0:this.#d(f,d,o.protocolVersion);R!==void 0&&c.set(f,R)}if(c.size>0)return Sh(o,c);if(d===Aa)return Sh(o,new Map(o.messages.map(f=>[f,yh])));if(!this.#o(o))return t;let l=Yb({envelope:o,projectionMaps:this.#e,allowedSets:d}),m=n(f=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${f}`),"warn"),h=n((f,R)=>{m(`did not forward an upstream reply (${f}); answered -32603`);let S=Pa(o,this.#e),w=S.fail(S.pendingKeys()),x=dt(new Headers(R.headers));return x.set("content-type","application/json"),w.length===0?new Response(JSON.stringify(wo({code:k.InternalError,message:Ph})),{status:502,headers:x}):new Response(JSON.stringify(o.shape==="batch"?w:w[0]),{status:200,headers:x})},"unreadable");r.addResponseSendingHook(async f=>{let R=!f.ok;if(f.body!==null&&Tt(f.headers))return R?f:h("its body is still content-encoded",f);if(Qb(f))return ov({response:f,envelope:o,projectionMaps:this.#e,filterReply:l,warn:m});if(!Xb(f))return f.ok&&f.status!==202&&f.status!==204&&f.body!==null?h("no or an unknown media type",f):f;let S;try{S=await f.clone().json()}catch{return R?f:h("its body is not JSON",f)}if(R&&!Array.isArray(S)&&!(Q(S)&&"result"in S))return f;let w=l(S);if(w===Ie&&o.shape==="batch"&&Array.isArray(S)){let I=Pa(o,this.#e),{replies:O,dropped:N}=xh(S,l,I);N>0&&O.push(...I.fail(I.pendingKeys())),O.length>0&&(m("did not forward a batch reply member it could not read; sent the rest"),w=O)}if(w===Ie)return h("the filter could not read the reply",f);if(w===S)return f;let x=dt(new Headers(f.headers));return new Response(JSON.stringify(w),{status:f.status,statusText:f.statusText,headers:x})});let y=new _r(t);return y.headers.set("accept-encoding","gzip, br"),y}#d(t,r,o){let s=n(a=>this.#e[a]!==void 0,"isConfigured"),i=n((a,c)=>{let d=r?.[a];return this.#e[a]?.has(c)===!0&&(d===void 0||d.has(c))},"isAllowed");for(let a of jb(t)){if(!(a.refusedBy??a.options).some(s))continue;let{target:c}=a;if(c===void 0)return zb(ut(t)??"",a.issue);if(!(a.resource?this.#g(c,i):a.options.filter(s).some(l=>i(l,c))))return a.notFound(c,o??null)}}#g(t,r){let o=this.#e.resources!==void 0;if(o&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!hh(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!o&&!s}#s(t){let r=n(o=>this.#e[o]!==void 0,"isConfigured");return t===Ls?Ch.some(r):Ua(t)?.option==="resources"&&r("resourceTemplates")?!0:lt.some(o=>r(o.option)&&(o.listMethod===t||o.directMethods.includes(t)))}#u(t){return t.messages.some(r=>{let o=ut(r);return o!==void 0&&this.#s(o)})}#o(t){return t.messages.some(r=>{let o=vh(ut(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#c(t,r){let o=this.#t;if(o===void 0)return{};let s;try{s=await o(t,r,this.options)}catch(a){return r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; refused the requests that needed it`,a),Aa}let i={};for(let a of lt){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let l=new Set;if(Array.isArray(d))for(let m of d)typeof m=="string"&&c.has(m)&&l.add(m);i[a.option]=l}return i}};var qa="zuplo.com",av=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),cv=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Uh(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Uh,"s2FaviconHref");function dv(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(dv,"strictFaviconHref");var Mh=Uh(qa);function za(e){let t=e.toLowerCase();return t===qa||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Uh(qa):dv(e)}n(za,"resolveIconHref");function uv(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(uv,"hostnameFromHost");function lv(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(lv,"isLocalOrAddressHost");function pv(e){let t=uv(e).toLowerCase().replace(/\.$/,"");if(lv(t)||cv.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),s=av.has(o)?3:2;return r.slice(-s).join(".")}n(pv,"inferFaviconDomain");function Na(e){return{src:za(pv(e)),mimeType:"image/png",sizes:["128x128"]}}n(Na,"resolveMcpFaviconIcon");function Hs(e){try{return Na(new URL(e).host)}catch{return}}n(Hs,"resolveMcpFaviconIconFromUrl");function kt(e){let t=_e().connectionsById.get(e);if(!t)throw new Y(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(kt,"getUpstreamServerConfig");function Bs(e){let t=_e().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new Y(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}n(Bs,"getUpstreamAuthConfig");function Nr(e,t){let r=Bs({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new Y(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n(Nr,"requireUpstreamOAuthConfig");function qh(e,t){let r=Bs({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new Y(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(qh,"requireUpstreamIdJagConfig");import{base64url as Js}from"jose";var mv="__Host-",hv=16,fv=32,Nh=".",gv=!1;function At(){return gv}n(At,"isBrowserBindingEnforced");var vo=p.object({id:p.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:p.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function Fs(e,t){return new URL(ne(e,t)).protocol==="https:"}n(Fs,"isSecureGatewayOrigin");function ja(e,t){return t?`${mv}${e}`:e}n(ja,"gatewayCookieName");function Co(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}n(Co,"serializeGatewayCookie");function Da(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}n(Da,"parseCookieHeader");function zh(e){return Js.encode(crypto.getRandomValues(new Uint8Array(e)))}n(zh,"randomBase64url");async function jh(e){let t=await crypto.subtle.digest("SHA-256",he(new TextEncoder().encode(e)));return Js.encode(new Uint8Array(t))}n(jh,"hashNonce");function yv(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o+=1)r|=e.charCodeAt(o)^t.charCodeAt(o);return r===0}n(yv,"constantTimeEqual");function Dh(e,t,r){return ja(`zuplo_mcp_${e}_${t}`,r)}n(Dh,"bindingCookieName");async function Io(e){let t=zh(hv),r=zh(fv),o=Fs(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${Nh}${Js.encode(e.payload)}`;return{claim:{id:t,hash:await jh(r)},setCookie:Co({name:Dh(e.purpose,t,o),value:s,maxAgeSeconds:e.ttlSeconds,secure:o})}}n(Io,"startBrowserBinding");async function Gs(e){let t=Fs(e.request.url,e.request.headers),r=Dh(e.purpose,e.claim.id,t),o=Co({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Da(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:o};let i=s.indexOf(Nh),a=i<0?s:s.slice(0,i);if(!yv(await jh(a),e.claim.hash))return{matched:!1,clearCookie:o};if(i<0)return{matched:!0,clearCookie:o};try{return{matched:!0,payload:new TextDecoder().decode(Js.decode(s.slice(i+1))),clearCookie:o}}catch{return{matched:!1,clearCookie:o}}}n(Gs,"verifyBrowserBinding");function $h(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n($h,"mergeAbortSignals");async function Sv(e){try{await e.cancel()}catch{}}n(Sv,"cancelReader");async function Vs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await Sv(r),t.createLimitError();o.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of o)a.set(d,c),c+=d.byteLength;return a}n(Vs,"readBoundedByteStream");var _v=2,wv=1024*1024,Rv=1e4,bv=new Set([301,302,303,307,308]),vv=["authorization","proxy-authorization","cookie","cookie2"];function $a(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n($a,"readRequestUrl");function jr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(jr,"readRequestMethod");function Cv(e,t,r){let o=e.headers.get("content-length");if(!o)return;let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>t)throw new T({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[E]:r}})}n(Cv,"assertContentLengthWithinLimit");async function Iv(e,t,r){return Cv(e,t,r),Vs(e.body,{maxBytes:t,createLimitError:n(()=>new T({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[E]:r}}),"createLimitError")})}n(Iv,"readBoundedResponseBody");function Tv(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(Tv,"responseFromBufferedBody");function Ev(e,t){if(!bv.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ev,"resolveRedirectUrl");function Lh(e,t){try{return t.validateUrl(e)}catch(r){throw new T({message:"Outbound URL was not allowed.",extensionMembers:{[E]:t.problemCode}},{cause:r})}}n(Lh,"validateOutboundUrl");function kv(e,t){throw e instanceof T&&ps(e.extensionMembers?.[E])?e:new T({message:"Outbound fetch failed.",extensionMembers:{[E]:t}},{cause:e})}n(kv,"normalizeFetchError");function To(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,s]of Object.entries(t.extra))s!==void 0&&(r[o]=s);t.error!==void 0&&Ce(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(To,"logOutboundFailure");async function Av(e,t,r,o,s,i,a){let c=jr(r,o);try{return await t(r,o)}catch(d){let l=d instanceof DOMException&&d.name==="AbortError";To(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ce(i),error:d,extra:{abortReason:a()}}),kv(d,s)}}n(Av,"fetchWithNormalizedError");function Pv(e){if(e.redirects>=e.maxRedirects)throw new T({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[E]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new T({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[E]:e.problemCode}})}n(Pv,"assertRedirectAllowed");function xv(e,t){let r=new Headers(e);for(let o of vv)r.delete(o);for(let o of t)r.delete(o);return r}n(xv,"stripCrossOriginHeaders");function Ov(e,t,r,o,s){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=xv(e.headers,s)),i}n(Ov,"buildRedirectInit");function Uv(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Uv,"buildInitialRequestInit");function Mv(e){let t=jr(e.currentInput,e.currentInit);Pv({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Lh(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),s=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Ov(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Mv,"followRedirect");async function La(e,t,r){let o=r.problemCode??"invalid_request",s=r.maxRedirects??_v,i=r.maxResponseBytes??wv,a=r.timeoutMs??Rv,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],l=r.context,m=new AbortController,h=$h(m,t.signal),y=!1,f=setTimeout(()=>{y=!0,m.abort()},a),R=e,S=Uv(e,t,m.signal),w;try{w=Lh($a(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(I){throw To(l,{event:"outbound_url_blocked",problemCode:o,method:jr(e,t),host:ce($a(e)),error:I}),clearTimeout(f),h?.(),I}let x=0;try{for(;;){let I=await Av(l,c,R,S,o,w,()=>y?`timeout_after_${a}ms`:void 0),O=Ev(I,w);if(O!==void 0)try{let N=Mv({currentInput:R,currentInit:S,currentUrl:w,redirectUrl:O,redirects:x,maxRedirects:s,problemCode:o,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:d});R=N.currentInput,S=N.currentInit,w=N.currentUrl,x=N.redirects;continue}catch(N){throw To(l,{event:"outbound_redirect_blocked",problemCode:o,method:jr(R,S),host:ce(w),error:N,extra:{redirects:x,maxRedirects:s,redirectTargetHost:ce(O)}}),N}try{return Tv(I,await Iv(I,i,o))}catch(N){throw To(l,{event:"outbound_response_size_exceeded",problemCode:o,method:jr(R,S),host:ce(w),error:N,extra:{maxResponseBytes:i,status:I.status}}),N}}}finally{clearTimeout(f),h?.()}}n(La,"runSafeOutboundExchange");async function Eo(e,t,r){let o=await La(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(s){throw To(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:jr(e,t),host:ce($a(e)),error:s,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new T({message:"Outbound JSON response could not be parsed.",extensionMembers:{[E]:r.problemCode??"invalid_request"}},{cause:s})}}n(Eo,"runSafeOutboundJsonExchange");function Hh(e,t={},r={}){return La(e,t,{...r,validateUrl:so})}n(Hh,"fetchConfiguredOutbound");function Bh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:so})}n(Bh,"fetchConfiguredOutboundJson");function Ks(e,t={},r={}){return Eo(e,t,{...r,validateUrl:Ap})}n(Ks,"fetchIdentityProviderJson");function Jh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:Rs})}n(Jh,"fetchCimdClientMetadataJson");function Fh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:io})}n(Fh,"fetchCimdClientJwksJson");import{errors as Yh,jwtVerify as Xh,SignJWT as Qh}from"jose";var Te="zuplo-mcp-gateway",Pe=Te,xe="HS256";import{base64url as qv}from"jose";var zv=new TextEncoder,Nv="MCP gateway could not initialize secure key material.",jv=32,Gh=new Map,Vh=new Map,Dv;function $v(){return Dv??es.instance.authPrivateKey}n($v,"readAuthPrivateKey");function Kh(e){return new be(Nv,e===void 0?void 0:{cause:e})}n(Kh,"createGeneratedKeyMaterialError");function Wh(e,t){let r=qv.decode(t);if(r.byteLength!==jv)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Wh,"decodeJwkKeyField");function Lv(e){let t=$v();if(!t)throw Kh();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=Wh("d",r.d);Wh("x",r.x);let s=zv.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+o.byteLength);return i.set(s),i.set(o,s.byteLength),i}catch(r){throw Kh(r)}}n(Lv,"decodeGeneratedKeyMaterial");function Hv(e){let t=Gh.get(e);return t||(t=Lv(e),Gh.set(e,t)),t}n(Hv,"getMasterKeyMaterial");async function tt(e){let t=Vh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Hv(e.keyMaterialPurpose));return Vh.set(e.purpose,r),r}n(tt,"readCachedDerivedKey");var Bv="SHA-256",Jv=32,Fv="zuplo-mcp-gateway:",Gv=new TextEncoder,Zh=new WeakMap;async function Pt(e,t){let r=Zh.get(e);r||(r=new Map,Zh.set(e,r));let o=r.get(t);if(o)return o;let s=await Vv(e,t);return r.set(t,s),s}n(Pt,"deriveGatewaySigningKey");async function Vv(e,t){let r=he(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=Gv.encode(`${Fv}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:Bv,salt:new Uint8Array,info:he(s)},o,Jv*8);return new Uint8Array(i)}n(Vv,"hkdfExpand");var ef=900,Kv=900,Wv=lp.extend({id:Mp,browserBinding:vo.optional()}),Zv=Wv.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),tf=xi.extend({id:qp,purpose:p.literal("browser_connect")}),Yv=xi.extend({purpose:p.literal("browser_connect")}),Xv=tf.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),Ws=ef*1e3;async function rf(){return tt({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"oauth-state"),"derive")})}n(rf,"getOAuthStateKey");async function nf(){return tt({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-connect"),"derive")})}n(nf,"getBrowserConnectKey");async function of(e){let t=Math.floor(Date.now()/1e3)+ef;return new Qh(e).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(t).sign(await rf())}n(of,"signOAuthState");async function Zs(e){try{let{payload:t}=await Xh(e,await rf(),{algorithms:[xe],issuer:Te,audience:Pe});return Zv.parse(t)}catch(t){throw t instanceof Yh.JWTExpired?new T({message:"OAuth state has expired",extensionMembers:{[E]:"oauth_state_expired"}},{cause:t}):new T({message:"OAuth state could not be verified",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:t})}}n(Zs,"verifyOAuthState");async function sf(e){let t=Math.floor(Date.now()/1e3)+Kv,r=Yv.parse(e),o=tf.parse({...r,id:Dp()});return new Qh(o).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(t).sign(await nf())}n(sf,"signBrowserConnectTicket");async function af(e){try{let{payload:t}=await Xh(e,await nf(),{algorithms:[xe],issuer:Te,audience:Pe});return Xv.parse(t)}catch(t){throw t instanceof Yh.JWTExpired?new T({message:"Browser connect ticket has expired",extensionMembers:{[E]:"oauth_state_expired"}},{cause:t}):new T({message:"Browser connect ticket could not be verified",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:t})}}n(af,"verifyBrowserConnectTicket");async function cf(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new T({message:"Browser connect ticket has already been used",extensionMembers:{[E]:"oauth_state_reused"}})}n(cf,"consumeBrowserConnectTicket");function Qv(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(Qv,"buildConnectRequiredMessage");async function eC(e){let t=ne(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await sf({...no(e),purpose:"browser_connect"})),r.toString()}n(eC,"buildGatewayBrowserTicketUrl");function tC(e){return me().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(tC,"buildGatewayConnectPath");async function Ha(e){return eC({...e,path:tC(e.upstreamServerId),redirect:!0})}n(Ha,"buildGatewayConnectUrl");async function Ys(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Ha(t),message:Qv(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ys,"buildRedirectConnectRequiredResponse");function df(e){return uf({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(df,"buildAdminConnectRequiredResponse");function uf(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(uf,"buildAdminSetupRequiredResponse");function lf(e){return _e().byOperationId.get(e)?.downstreamOAuth!==void 0}n(lf,"routeSupportsBrowserConnect");function pf(e){return uf({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}n(pf,"buildBrowserConnectUnavailableResponse");var mf=12;async function hf(e){let t=await crypto.subtle.digest("SHA-256",he(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(hf,"sha256Hex");async function er(e){if(e)return(await hf(e)).slice(0,mf)}n(er,"fingerprintSecret");async function Dr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await hf(t)).slice(0,mf)}n(Dr,"fingerprintConnectionIdentity");var rC=6e4;function $r(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,o)=>t.scopes[o]!==r)}n($r,"credentialGenerationChanged");function Ee(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+rC)return"near_expiry"}return"usable"}n(Ee,"describeAccessTokenState");var ff=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function nC(e,t){return e&&e.length>0?e.join(t):void 0}n(nC,"joinOAuthScopes");function oC(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ff)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(oC,"sanitizeAuthorizationServerMetadata");function gf(e){let t=oC(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(gf,"sanitizeOAuthDiscoveryState");function yf(e){let t=new URL(e);for(let r of ff){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(yf,"dedupeSingletonAuthorizationRequestParams");function Xs(e){let t=new URL(e);return qe(t)&&ep(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Xs,"normalizeLoopbackOAuthRedirectUri");function Sf(e){return nC(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Sf,"readProtectedResourceMetadataScope");function sC(e){return`Zuplo MCP Gateway - ${e}`}n(sC,"buildGatewayOAuthClientName");function iC(e,t){return e&&e.length>0?e.join(t):void 0}n(iC,"joinOAuthScopeList");function aC(e){if(e.clientRegistration.mode!=="auto")return iC(e.scopes,e.scopeDelimiter)}n(aC,"readPublicClientMetadataScope");function Ba(e){return new URL(me().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Ba,"buildOAuthClientMetadataDocumentUrl");function Ja(e){let t=kt(e.upstreamServerId);return{client_name:sC(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Ja,"buildGatewayOAuthClientMetadata");function _f(e,t,r){let o=Nr(t,r),s=aC(o);return{client_id:Ba({origin:e,upstreamServerId:t}),...Ja({origin:e,upstreamServerId:t,redirectUri:Xs(new URL(o.redirectPath,e)).toString(),scope:s})}}n(_f,"buildOAuthClientMetadataDocument");import{base64url as xt}from"jose";var cC="SHA-256",Lr="AES-GCM",dC=12,Ga="zuplo-secret",Va=1,wf="generated:auth_private_key:token-encryption",uC=p.object({version:p.literal(Va),keyId:p.literal(wf),algorithm:p.literal(Lr),iv:p.string().min(1),ciphertext:p.string().min(1)}).strict();async function Fa(){return tt({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(cC,he(e));return crypto.subtle.importKey("raw",t,{name:Lr},!1,["encrypt","decrypt"])},"derive")})}n(Fa,"getEncryptionKey");function Rf(e){return he(new TextEncoder().encode(`${Ga}:v${e.version}:${e.keyId}`))}n(Rf,"getAssociatedData");function lC(e){return`${Ga}:v${e.version}:${xt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(lC,"encodeEnvelope");function pC(e){let t=`${Ga}:v${Va}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(xt.decode(r));return uC.parse(JSON.parse(o))}n(pC,"decodeEnvelope");async function pt(e){let t=await Fa(),r=crypto.getRandomValues(new Uint8Array(dC)),o={version:Va,keyId:wf},s=await crypto.subtle.encrypt({name:Lr,iv:r,additionalData:Rf(o)},t,new TextEncoder().encode(e));return lC({...o,algorithm:Lr,iv:xt.encode(r),ciphertext:xt.encode(new Uint8Array(s))})}n(pt,"encryptSecret");async function mt(e){let t=pC(e);if(t){let a=await Fa(),c=await crypto.subtle.decrypt({name:Lr,iv:he(xt.decode(t.iv)),additionalData:Rf(t)},a,he(xt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new be("Encrypted payload is malformed");let s=await Fa(),i=await crypto.subtle.decrypt({name:Lr,iv:he(xt.decode(r))},s,he(xt.decode(o)));return new TextDecoder().decode(i)}n(mt,"decryptSecret");var bf={issuer:p.string().min(1).optional()},mC=p.union([Zt.extend(bf),Qn.extend(bf)]),vf=p.object({authorizationServerUrl:p.url(),resourceMetadataUrl:p.url().optional(),resourceMetadata:Cr.optional(),authorizationServerMetadata:p.union([Ir,Tr]).optional()}).passthrough(),hC="Bearer",fC="__zuplo_refresh_only_upstream_access_token__";function Ka(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ka,"splitScopes");function Wa(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Wa,"scopesCover");function gC(e){return kr.parse(e)}n(gC,"parsePkceCodeVerifier");function yC(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}n(yC,"readTokenExpiry");async function Cf(e){if(e!==void 0)return pt(JSON.stringify(e))}n(Cf,"encryptJson");async function If(e,t){if(!e)return;let r=await mt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new T({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:o})}}n(If,"decryptJson");function SC(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(SC,"clientInformationAllowsRedirectUri");function _C(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(_C,"clientInformationMatchesCurrentClientMetadataUrl");function wC(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(wC,"isUrlBasedClientInformation");function RC(e,t){return t===void 0?e:{...e,scope:t}}n(RC,"applyOAuthClientMetadataScope");function bC(e,t){return Sf({state:e,delimiter:t})}n(bC,"readResourceMetadataScope");function vC(e,t){return e&&e.length>0?e.join(t):void 0}n(vC,"joinOAuthScopeList");function CC(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new Y(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Zt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(CC,"buildManualOAuthClientInformation");function IC(e,t){let r=Ba({origin:new URL(t).origin,upstreamServerId:e});return ha(r)?r:void 0}n(IC,"buildClientMetadataUrl");function TC(e){for(let t of e)if(t!==void 0)return t}n(TC,"firstDefined");function EC(e){let t=Nr(e.target.upstreamServerId,e.target.authProfileId),r=vC(t.scopes,t.scopeDelimiter),o=Ja({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:CC({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=IC(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}n(EC,"buildInitialOAuthClientSetup");function kC(e,t){if(t===void 0)return TC([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(kC,"readEncryptedClientInformation");function AC(e){return e.pendingState?.encryptedDiscoveryState}n(AC,"readEncryptedDiscoveryState");function Za(e,t){return t===void 0?e:{...e,issuer:t}}n(Za,"applyIssuerStamp");var Ot=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;skipIssuerMetadataValidationValue;skipResourceIndicatorValidationValue;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=EC({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.browserBinding=t.browserBinding,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.skipIssuerMetadataValidationValue=r.skipIssuerMetadataValidation,this.skipResourceIndicatorValidationValue=r.skipResourceIndicatorValidation,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=kC(t,this.configuredClientInformation),this.encryptedDiscoveryState=AC(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get skipIssuerMetadataValidation(){return this.skipIssuerMetadataValidationValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let o=Ka(this.configuredScope??r??this.readEffectiveScope());return Wa(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Ee(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let o=te();o&&o.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Dr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await er(await mt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(o){let s=te();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:o}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});s.error(i,"Upstream OAuth conditional storage write failed")}throw o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return RC(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return of({id:t.id,...no({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId}),...this.browserBinding===void 0?{}:{browserBinding:this.browserBinding}})}async clientInformation(t){return this.configuredClientInformation?Za(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,te()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!wC({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cf(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!As({requestedResource:t,configuredResource:r}))throw new Error(`Protected resource ${r} does not match expected ${t} (or origin)`);return new URL(r)}}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=gf(vf.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Cf(r),await this.syncPendingState(!1),te()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ce(r.authorizationServerUrl),resourceMetadataHost:ce(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=bC(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let s=Ka(this.configuredScope).filter(i=>!o.includes(i));s.length>0&&te()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:o},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return Za(r,t?.issuer)}async saveTokens(t){let r=Rt.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,a=r.refresh_token?await pt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:Rt.parse({...r,refresh_token:await mt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??bs(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await pt(r.access_token),encryptedRefreshToken:a,scopes:Ka(r.scope??this.readEffectiveScope()),expiresAt:yC(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},l=await this.conditionalUpsertCredential(c,d),m=!1;if(l.kind==="precondition_failed"&&l.connection!==void 0&&(Ee(l.connection)!=="usable"||!Wa(l.connection.scopes,c.scopes)||!$r(s,l.connection))){m=!0;let y=l.connection,f={id:y.id,ownerMode:y.ownerMode,subjectId:y.subjectId,upstreamServerId:y.upstreamServerId,authProfileId:y.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?y.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:y.metadata};te()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:y.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:y.scopes.length,resultingScopeCount:f.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),l=await this.conditionalUpsertCredential(f,{expectedUpdatedAt:y.updatedAt})}if(l.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=l.kind,l.kind==="persisted"?(this.credentialState.currentConnection=l.connection,this.credentialState.peerAdoption=void 0):l.kind==="precondition_failed"&&l.connection!==void 0?(this.credentialState.currentConnection=l.connection,$r(s,l.connection)&&Ee(l.connection)==="usable"&&Wa(l.connection.scopes,c.scopes)?this.adoptPeerConnection(l.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),m){let y=l.kind==="persisted"?"succeeded":l.kind==="precondition_failed"?"lost":"exhausted";te()?.info({event:`upstream_oauth_bounded_rebase_${y}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${y}`)}let h=l.kind==="persisted"?l.connection:void 0;te()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await er(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:l.kind,rebaseAttempted:m,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=yf(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:gC(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new T({message:"OAuth code verifier is missing",extensionMembers:{[E]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),s&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:jp(),...no({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:J(new Date(Date.now()+Ws)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await If(this.encryptedClientInformation,mC)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!SC(r,this.redirectUriValue)||!_C({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Za(Qn.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await If(this.encryptedDiscoveryState,vf)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){te()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await mt(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await mt(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let s=te();this.usedRefreshTokenFingerprintValue=s?await er(o):void 0,s?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Rt.parse({access_token:r??fC,token_type:hC,refresh_token:o,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=i,i}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let o=r.status,s=r.updatedAt,i={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let a=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,$r(r,a.connection)&&Ee(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=te();if(c){let d=a.kind==="missing"?void 0:a.connection,l={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:o,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...l,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(l,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(l,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var PC=3e4,xC=256*1024,OC=2,UC="does not support dynamic client registration",MC=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],qC=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],zC=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],NC="Protected resource ",jC=" does not match expected ",DC=["HTTP 403 Forbidden","Access Denied","permission to access"],$C=new Set([le.AccessDenied,le.InvalidClient,le.InvalidGrant,le.InvalidRequest,le.InvalidScope,le.InvalidTarget,le.UnauthorizedClient,le.UnsupportedGrantType]);function LC(e){return e instanceof Error&&e.message.includes(UC)}n(LC,"isDynamicClientRegistrationUnsupported");function HC(e){return e instanceof Error&&MC.some(t=>e.message.includes(t))}n(HC,"isProtectedResourceMetadataUnavailable");function BC(e){return e instanceof Error&&qC.some(t=>e.message.includes(t))}n(BC,"isAuthorizationServerMetadataUnavailable");function JC(e){return e instanceof Error&&zC.some(t=>e.message.includes(t))}n(JC,"isAuthorizationServerIncompatible");function FC(e){return e instanceof Error&&e.message.includes(NC)&&e.message.includes(jC)}n(FC,"isProtectedResourceMismatch");function GC(e){return e instanceof Error&&DC.some(t=>e.message.includes(t))}n(GC,"isUpstreamProviderAccessDenied");function VC(e){return e instanceof Ct&&$C.has(e.code)}n(VC,"isStoredConnectionReconsentError");function ht(e){let t=e.diagnostics??{};return new T({message:e.message,extensionMembers:{[E]:e.code,[ls]:e.upstreamServerId,[xr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[nt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[rt]:t.httpStatus},...t.providerError===void 0?{}:{[Or]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Ur]:t.providerErrorDescription}}},{cause:e.cause})}n(ht,"buildUpstreamSetupProblem");function KC(e,t){return`The authorization server for ${e} failed RFC 8414 \xA73.3 issuer validation: the gateway discovered it at "${t.expected}", but its metadata document declares issuer "${t.received}". Providers that publish a path-scoped authorization server whose metadata reports the root origin hit this; if that is the case here, set skipIssuerMetadataValidation on this upstream's OAuth config to accept it \u2014 that weakens the authorization-server mix-up defense, so scope it to this upstream. Otherwise correct the authorization server URL this upstream points at, or ask the provider to fix the published issuer.`}n(KC,"describeIssuerMetadataMismatch");var WC=128,ZC=256;function Tf(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Tf,"truncateProviderDetail");function YC(e){let{error:t,errorDescription:r}=kf(e.body),o=Tf(t,WC),s=Tf(r,ZC);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...s===void 0?{}:{providerErrorDescription:s}}}n(YC,"readRegistrationRejectionDiagnostics");function XC(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}n(XC,"describeRegistrationRejection");function QC(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(QC,"readDiscoveryEndpointUrl");function eI(e){if(e.error instanceof T&&e.error.extensionMembers?.[E]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(LC(e.error))return ht({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`});if(e.error instanceof pa){let r=YC(e.error);return ht({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${XC(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof ho&&e.error.kind==="metadata")return ht({...t,code:"upstream_oauth_issuer_mismatch",message:KC(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof qs)return ht({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} publishes the non-HTTPS token endpoint "${e.error.tokenEndpoint}". The gateway will not send credentials to it. Ask the provider to serve the token endpoint over TLS before retrying.`,diagnostics:{upstreamUrl:e.error.tokenEndpoint}});if(JC(e.error))return ht({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} cannot run the OAuth flow the gateway requires: ${e.error.message}. Ask the provider to support the authorization code flow with PKCE (S256), or configure this upstream to use an authorization server that does.`});if(BC(e.error)){let r=QC(e.error.message);return ht({...t,code:"upstream_oauth_discovery_unavailable",message:`The gateway could not load OAuth authorization server metadata for the upstream MCP server "${e.upstreamServerId}": ${e.error.message}. Confirm the authorization server advertised by "${e.resourceMetadataUrl}" publishes RFC 8414 or OpenID Connect discovery metadata and is reachable from the gateway, then retry.`,diagnostics:r===void 0?{}:{upstreamUrl:r}})}if(FC(e.error))return ht({...t,code:"upstream_oauth_discovery_unavailable",message:`The protected resource metadata at "${e.resourceMetadataUrl}" names a resource that does not match the configured MCP URL for ${e.upstreamServerId}: ${e.error.message}. Point this upstream's MCP URL at the resource the provider publishes, or ask the provider to correct the advertised resource.`});if(HC(e.error))return ht({...t,code:"upstream_oauth_discovery_unavailable",message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`});if(GC(e.error))return ht({...t,code:"upstream_provider_access_denied",message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`})}n(eI,"mapUpstreamOAuthSetupError");function tI(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(tI,"readOAuthFetchRequest");function rI(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(rI,"readOAuthFetchMethod");function nI(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(nI,"responseLooksJson");function oI(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(oI,"responseLooksHtml");var sI=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function iI(e){return sI.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(iI,"isMetadataDiscoveryRequest");function aI(e,t,r){return e!=="GET"||!iI(t)?!1:r>=400&&r<500||r===502}n(aI,"sdkRetriesDiscoveryCandidate");function cI(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new T({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[E]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[rt]:e.response.status,[Ar]:r,[nt]:e.request.url.toString(),[Pr]:e.body}})}n(cI,"throwUpstreamHtmlError");function kf(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(kf,"readUpstreamOAuthErrorBody");function dI(e){let{error:t,errorDescription:r}=kf(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ce(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(dI,"logUpstreamOAuthHttpError");function Af(e){return async(t,r)=>{let o=tI(t),s=rI(t,r),i=te(),a=Date.now(),c=await Hh(t,r,{maxRedirects:OC,maxResponseBytes:xC,problemCode:"upstream_token_exchange_failed",timeoutMs:PC}),d=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:ce(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:d.length},"Upstream OAuth HTTP request completed"),c.ok||dI({log:i,upstreamServerId:e,method:s,request:o,response:c,body:d}),aI(s,o.url,c.status)||(!c.ok&&oI(c,d)&&cI({upstreamServerId:e,request:o,response:c,body:d}),!nI(c,d)))return c;try{JSON.parse(d)}catch(l){throw new T({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[E]:"upstream_token_exchange_failed"}},{cause:l})}return c}}n(Af,"createUpstreamOAuthFetch");function Pf(e){te()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ce(e.serverUrl),resourceMetadataHost:ce(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Pf,"logUpstreamOAuthFlowStarted");function xf(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ce(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof T?e.error.extensionMembers?.[E]:void 0;typeof o=="string"&&(t.code=o),Ce(t,"error",e.error),te()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(xf,"logUpstreamOAuthFlowFailed");function Of(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Of,"readAuthorizationRequestScope");async function Uf(e,t){e.applyChallengeScope(t.requestedScope),Pf({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Af(t.upstreamServerId)},o=Of(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await ma(e,r)}catch(r){xf({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=eI({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Uf,"runUpstreamOAuth");async function uI(e,t){e.applyChallengeScope(t.requestedScope),Pf({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Af(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Of(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await ma(e,r)}catch(s){throw xf({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}n(uI,"exchangeUpstreamAuthorizationCode");async function Ef(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await H().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Ee(r)!=="usable"||!$r(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(Ef,"adoptPeerCredentialAtResolutionBoundary");async function Mf(e,t){let r=await Uf(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new T({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}}):new T({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}})}n(Mf,"requireUpstreamAuthorizationRedirect");async function qf(e){let t=Ee(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=te(),i=s?await Dr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(s?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:i,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a;try{a=await Uf(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!VC(c))throw c;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await Ef({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Ya({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Ya({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new T({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new T({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});return await Ef({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Ya({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(qf,"authorizeUpstreamOAuthSession");async function lI(e){let t=await Zs(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),o=pI(r);return mI({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),hI(o),o}n(lI,"consumeStoredCallbackState");function pI(e){switch(e.kind){case"consumed":throw new T({message:"OAuth state has already been used",extensionMembers:{[E]:"oauth_state_reused"}});case"missing":throw new T({message:"OAuth state is missing or expired",extensionMembers:{[E]:"oauth_state_expired"}});case"available":return e.record}}n(pI,"readConsumedCallbackState");function mI(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new T({message:"OAuth callback did not match the initiating request",extensionMembers:{[E]:"oauth_callback_mismatch"}})}n(mI,"assertStoredCallbackStateMatches");function hI(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new T({message:"OAuth state has expired",extensionMembers:{[E]:"oauth_state_expired"}})}n(hI,"assertStoredCallbackStateFresh");async function Ya(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),df(r)}if(At()&&!lf(e.operationId))return te()?.warn({event:"upstream_connect_link_unavailable",upstreamServerId:e.upstreamServerId,operationId:e.operationId},"User-owned upstream needs a connection, but this MCP route has no gateway MCP OAuth sign-in to bind a connect link to; returning an administrator answer instead of a link"),pf({upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,...e.connection===void 0?{}:{connectionId:e.connection.id},requiresReconsent:!!e.connection});let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Ys(t)}n(Ya,"buildOAuthConnectRequiredResponse");async function zf(e){let t=await lI({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=fs(t),[o]=await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(s.connection=o);let i=new Ot(s),a=await uI(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(a==="AUTHORIZED"){let c=i.readUsablePeerAdoption();if(c!==void 0&&await i.adoptConnectionForDirectResolution(c,"cas_loss"),!i.tokenWriteWasPersisted&&c===void 0)throw new T({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new T({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}}):new T({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}})}n(zf,"finishUpstreamOAuthCallback");import{importPKCS8 as fI,SignJWT as gI}from"jose";var jf=1e4,Df=64*1024,$f=2,yI=300,Ze=p.string().min(1),SI=p.object({access_token:Ze,issued_token_type:p.literal(Ui),token_type:p.string().optional(),expires_in:p.number().int().positive().optional(),scope:Ze.optional()}).passthrough(),_I=p.object({id_token:Ze,token_type:Ze.optional(),expires_in:p.number().int().positive().optional(),refresh_token:Ze.optional(),scope:Ze.optional()}).passthrough(),wI=p.object({access_token:Ze,token_type:Ze,expires_in:p.number().int().positive().optional(),scope:Ze.optional(),resource:Ze.optional(),refresh_token:Ze.optional()}).passthrough();function Nf(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Nf,"formEncodeClientCredential");function RI(e){return e.replaceAll("\\n",`
41
+ `)}n(RI,"normalizePem");async function bI(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??yI,o=await fI(RI(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new gI({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(bI,"createPrivateKeyJwtClientAssertion");async function vI(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=Nf(e.clientAuth.clientId),r=Nf(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",ys),e.form.set("client_assertion",await bI({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(vI,"appendClientAuthentication");async function Xa(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await vI({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(Xa,"buildFormRequest");function Lf(e){return(t,r)=>Ks(t,r,{context:e,maxRedirects:$f,maxResponseBytes:Df,problemCode:"upstream_token_exchange_failed",timeoutMs:jf})}n(Lf,"defaultIdpFetchJson");function CI(e){return(t,r)=>Bh(t,r,{context:e,maxRedirects:$f,maxResponseBytes:Df,problemCode:"upstream_token_exchange_failed",timeoutMs:jf})}n(CI,"defaultResourceAsFetchJson");function Qs(e){let t={[E]:e.code,[nt]:e.tokenUrl};return e.response!==void 0&&(t[rt]=e.response.status),new T({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(Qs,"runtimeError");function Qa(e){if(!e.response.ok)throw Qs({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}n(Qa,"assertTokenEndpointSucceeded");function II(e){let t=_I.safeParse(e.json);if(!t.success)throw Qs({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(II,"parseIdpRefreshTokenResponse");function TI(e){let t=SI.safeParse(e.json);if(!t.success)throw Qs({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(TI,"parseIdJagTokenExchangeResponse");function EI(e){let t=wI.safeParse(e.json);if(!t.success)throw Qs({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}n(EI,"parseAccessTokenResponse");async function Hf(e){let t=new URLSearchParams({grant_type:gs,requested_token_type:Ui,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??Lf(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qa({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),TI({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Hf,"requestIdJag");async function Bf(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Lf(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qa({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),II({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Bf,"refreshIdpSubjectToken");async function Jf(e){let t=new URLSearchParams({grant_type:vt,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??CI(e.context),{response:o,json:s}=await r(e.resourceAs.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Qa({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),EI({json:s,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Jf,"exchangeIdJagForAccessToken");function kI(e){return Ee(e)==="usable"}n(kI,"hasUsableAccessToken");function AI(e){if(e.tokenType.toLowerCase()!=="bearer")throw new T({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[E]:"upstream_token_response_invalid"}})}n(AI,"assertBearerToken");function Ff(e,t){if(t===zr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Ff,"hasExpiredSubjectToken");async function PI(e){let t=await mt(e.encryptedSubjectToken);if(e.subjectTokenType!==zr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Bf({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:oo};let o=await H().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await pt(r.refreshToken),idpSubjectTokenType:zr,idpSubjectTokenExpiresAt:void 0}});return te()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:o.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await er(t),newSubjectRefreshTokenFingerprint:await er(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:oo}}n(PI,"resolveIdJagSubjectToken");async function Gf(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Ee(t),o=!!e.forceRefresh,s=!o&&r==="usable",i=te(),a=i?await Dr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(i?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:a,connectionId:t?.id,accessTokenState:r,forceRefresh:o,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&kI(t))return{kind:"authorized",credential:{type:"bearer_token",token:await mt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||Ff(t,d))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:d,subjectTokenExpired:d!==void 0&&Ff(t,d)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let l=kt(e.upstreamServerId),m=qh(e.upstreamServerId,e.authProfileId),h=m.resourceAs.resource??l.transport.baseUrl,y=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),f=await PI({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),R=await Hf({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:f.subjectToken,subjectTokenType:f.subjectTokenType,audience:m.resourceAs.audience,resource:h,scope:y,clientAuth:m.idp.clientAuth,context:e.context}),S=R.scope??y,w=await Jf({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:R.assertion,resource:h,scope:S,clientAuth:m.resourceAs.clientAuth,context:e.context});if(AI(w),t!==void 0){let I=(w.scope??S)?.split(/[,\s]+/).filter(Boolean)??[],O=w.expiresIn===void 0?void 0:J(new Date(Date.now()+w.expiresIn*1e3)),N=await H().upsertUpstreamConnection({id:f.connection.id,ownerMode:f.connection.ownerMode,subjectId:f.connection.subjectId,upstreamServerId:f.connection.upstreamServerId,authProfileId:f.connection.authProfileId,status:"active",encryptedAccessToken:await pt(w.accessToken),encryptedRefreshToken:f.connection.encryptedRefreshToken,scopes:I,expiresAt:O,metadata:f.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:f.connection.status,priorUpdatedAt:f.connection.updatedAt,scopeCount:I.length,expiresAt:O},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:w.accessToken}}}n(Gf,"authorizeUpstreamIdJagRequest");var ei=new Map;function xI(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(xI,"normalizeRefreshFlightScope");function OI(e){return Xs(new URL(e.callbackPath,ne(e.requestUrl,e.requestHeaders))).toString()}n(OI,"buildGatewayOAuthRedirectUri");async function ec(e){let t=kt(e.upstreamServerId),r=Nr(e.upstreamServerId,e.authProfileId),o=OI({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:ne(e.request.url,e.request.headers)}}}n(ec,"prepareUpstreamOAuthRequest");async function Vf(e){let t=await ec(e),r=new Ot({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Mf(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Vf,"startUpstreamConnect");async function Kf(e){let t=await ec(e),r=new Ot({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>qf({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&Ee(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o();let s=zp({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,xI(r.configuredAuthorizationScope??e.requestedScope)]),a=ei.get(i);if(a!==void 0){te()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let l=await a;if(l.kind==="usable"&&r.connectionSatisfiesRequestedScope(l.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(l.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:m,...h}=e;if(t=await ec(h),r=new Ot({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Ee(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o()}let c=o(),d;return d=c.then(()=>{let l=r.currentConnection;return l!==void 0&&Ee(l)==="usable"?{kind:"usable",connection:l}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{ei.get(i)===d&&ei.delete(i)}),ei.set(i,d),c}n(Kf,"authorizeUpstreamRequest");async function Hr(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Kf({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Gf({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new be(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Hr,"resolveUpstreamCredentialForRoute");async function Wf(e){if(e.connectRequest.authMode==="id-jag")throw new be(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Vf({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding}});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Wf,"startUpstreamConnectForRequest");async function UI(e,t){if(t===void 0)throw new T({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[E]:"oauth_callback_mismatch"}});let r=await Gs({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new T({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[E]:"oauth_callback_mismatch"}})}n(UI,"requireCallbackBrowser");async function Zf(e){let t=await Zs(e.callbackRequest.state);At()&&await UI(e,t.browserBinding);let r=t.authProfileId;if(Bs({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new be(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return zf({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:kt(e.callbackRequest.upstreamServerId)})}n(Zf,"finishUpstreamCallbackForRequest");function MI(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(MI,"buildRouteAuthBaseFromConnection");function Yf(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:pp(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Yf,"buildRouteAuthBaseFromPolicyOptions");function ti(e,t){let o=_e().byOperationId.get(t);if(!o)throw new Y(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new Y(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new Y(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return MI({connection:o.connection,operationId:t})}n(ti,"resolveRouteAuthBase");function tc(e,t){switch(e){case"user":return Mr(t);case"shared":return up()}}n(tc,"buildOwnerForSubject");function Br(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:tc("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:tc("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:tc("user",t),initiatedBySubjectId:t}}}n(Br,"resolveRouteAuthForSubject");var rc=new WeakMap;function Xf(e,t){rc.set(e,t)}n(Xf,"setUpstreamAuthRetry");function Qf(e){let t=rc.get(e);return rc.delete(e),t}n(Qf,"takeUpstreamAuthRetry");var qI=k.InvalidRequest,zI="The upstream connection returned no OAuth tokens.";function eg(e){let t=ga(e);return Response.json(ya({id:t,error:{code:k.InternalError,message:zI}}),{status:t===void 0?500:200})}n(eg,"noUpstreamTokensJsonRpcResponse");function NI(e,t){return{credentialType:e.type,forceRefresh:t}}n(NI,"buildCredentialResolvedAttributes");function jI(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(jI,"connectRequiredReasonCode");function tg(e){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:NI(e.credential,e.forceRefresh===!0)})}n(tg,"emitCredentialResolvedAnalyticsEvent");function rg(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:jI(e.payload.state),reasonClass:"auth",attributes:t})}n(rg,"emitCredentialMissingAnalyticsEvents");function DI(e){let t=e.route.raw();return hs.parse(t?.operationId)}n(DI,"readOperationId");async function $I(e,t,r,o,s){let i=await Hr({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return rg({context:o,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(tg({context:o,credential:a,routeBinding:t,mcpProtocolVersion:s}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}n($I,"buildCredentialHeaders");var LI=new Set(["authorization","cookie","cookie2"]);function HI(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}n(HI,"parseJsonRequestBody");function BI(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}n(BI,"readJsonRequestMethod");function JI(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(JI,"isJsonResponse");function nc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(nc,"isRecord");function FI(e){return Array.isArray(e)&&e.length>0}n(FI,"hasIconList");function GI(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Hs(cp(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(GI,"readFallbackServerIcons");function VI(e){if(!nc(e.body))return e.body;let t=e.body.result;if(!nc(t))return e.body;let r=t.serverInfo;return!nc(r)||FI(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(VI,"addMissingServerIcons");function KI(e,t){let r=ng(e.headers);for(let o of LI)r.delete(o);for(let[o,s]of t)r.set(o,s);return new _r(e,{headers:r})}n(KI,"applyUpstreamHeaders");function ng(e){let t=new Headers(e);return sd(t),t}n(ng,"buildProxyHeaders");async function WI(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(WI,"readRetryBody");function og(e,t){let r=t.authUrl===void 0?void 0:Zm({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(ya({id:ga(e),error:{code:r?.code??qI,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(og,"connectRequiredJsonRpcResponse");async function ZI(e){let{scope:t}=Fm(e.upstreamResponse),r=await Hr({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return rg({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),s=r.credential;if(tg({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return o.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:o};let i=await s.provider.tokens();return i?(o.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"no_tokens"})}n(ZI,"applyRefreshedCredentialHeaders");function YI(e){Xf(e.context,{refresh:n(async(t,r)=>{let o=await ZI({request:e.request,context:e.context,headers:ng(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return o.kind==="connect_required"?{kind:"response",response:og(e.requestBody,o.payload)}:o.kind==="no_tokens"?{kind:"response",response:eg(e.requestBody)}:o},"refresh")})}n(YI,"registerUpstreamAuthRetry");function XI(e){if(BI(e.requestJson)!=="initialize")return;let t=GI({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!JI(r))return r;let o;try{o=await r.clone().json()}catch{return r}let s=VI({body:o,icons:t});if(s===o)return r;let i=Xm(new Headers(r.headers));return i.delete("content-length"),new Response(JSON.stringify(s),{status:r.status,statusText:r.statusText,headers:i})})}n(XI,"installInitializeIconHook");async function oc(e,t,r){let o=DI(t),s=await WI(e),i=HI(s),a=eo(e.headers,i),c=Yf({connection:r,operationId:o}),d=Yt(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),Sp(t,d);let l=Br(c,d.subjectId),m=await $I(e,l,r,t,a);if(m.kind==="connect_required")return og(s,m.payload);if(m.kind==="no_tokens")return eg(s);let h=KI(e,m.headers);return YI({request:h,context:t,requestBody:s,routeAuth:l,mcpProtocolVersion:a}),XI({context:t,requestJson:i,connection:r}),h}n(oc,"mcpTokenExchangePolicy");var sc=class extends ns{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=mp(t,r);super(o,r),this.#e=o}async handler(t,r){return oc(t,r,this.#e)}};var sg=Symbol("Html");function QI(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(QI,"escapeHtml");function eT(e){return e===null||typeof e!="object"?!1:e[sg]===!0}n(eT,"isHtml");function ri(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ri).join(""):eT(e)?e.value:QI(String(e))}n(ri,"renderValue");function Be(e){return{[sg]:!0,value:e}}n(Be,"trustedHtml");var Je=Be("");function V(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ri(t[o]),r+=e[o+1]??"";return Be(r)}n(V,"html");function Jr(e,t=Je){let r=ri(t),o="",s=!0;for(let i of e)s||(o+=r),o+=ri(i),s=!1;return Be(o)}n(Jr,"joinHtml");function Fr(e){return e.value}n(Fr,"renderHtml");function ig(e){return V`<section class="page-section" aria-labelledby="error-next-steps"><h2 class="section-label" id="error-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol>${e.action}</section><section class="page-section" aria-labelledby="error-reference"><h2 class="section-label" id="error-reference">Reference</h2><dl class="kv kv--boxed">${e.reference}</dl></section><section class="page-section tech" aria-labelledby="error-technical"><h2 class="section-label" id="error-technical">Technical details <span class="section-label__count">for administrators</span></h2><dl class="kv">${e.diagnostics}</dl>${e.upstreamResponse}</section>`}n(ig,"renderBrowserErrorPage");var ag=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><path d="m8.25 12.25 2.5 2.5 5-5.25"/></svg>'),cg=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><line x1="12" y1="7.5" x2="12" y2="12.75"/><circle cx="12" cy="16.25" r=".9" fill="currentColor" stroke="none"/></svg>'),Gr=Be('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}.card__status{border:1px solid;border-radius:50%;justify-content:center;align-items:center;width:48px;height:48px;margin:0 auto 16px;display:flex}.card__status svg{width:24px;height:24px}.card__status--error{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger)}.card__status--success{background:var(--success-bg);border-color:var(--success-border);color:var(--success)}.card__status--neutral{background:var(--surface-2);border-color:var(--border);color:var(--text-3)}.page-section{flex-direction:column;gap:10px;display:flex}.steps{counter-reset:step;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.steps li{counter-increment:step;color:var(--text-2);align-items:flex-start;gap:10px;font-size:13.5px;line-height:1.5;display:flex}.steps li:before{content:counter(step);border:1px solid var(--border-strong);background:var(--surface);width:20px;height:20px;color:var(--text-2);border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;margin-top:1px;font-size:11.5px;font-weight:600;line-height:1;display:inline-flex}.kv{flex-direction:column;margin:0;display:flex}.kv__row{border-top:1px solid var(--border);grid-template-columns:124px minmax(0,1fr);gap:2px 12px;padding:7px 0;display:grid}.kv__row:first-child{border-top:0;padding-top:0}.kv__row:last-child{padding-bottom:0}.kv__row--block{grid-template-columns:minmax(0,1fr)}.kv__label{color:var(--text-3);margin:0;padding-top:1px;font-size:12px;font-weight:500}.kv__value{min-width:0;color:var(--text);overflow-wrap:anywhere;margin:0;font-size:13px;line-height:1.5}.kv__value code{font-family:var(--font-mono);color:var(--text);font-size:12px}.kv__row--fix .kv__value{color:var(--text);font-weight:500}.kv--boxed{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px}.kv--boxed .kv__row{grid-template-columns:92px minmax(0,1fr);padding:6px 0}.kv--boxed .kv__row:first-child{padding-top:0}.kv--boxed .kv__row:last-child{padding-bottom:0}.tech{border-top:1px solid var(--border);padding-top:18px}.provider-response{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2)}.provider-response__summary{cursor:pointer;user-select:none;color:var(--text-2);align-items:center;gap:8px;padding:9px 12px;font-size:12.5px;font-weight:500;list-style:none;display:flex}.provider-response__summary::-webkit-details-marker{display:none}.provider-response__summary:before{content:"";border-bottom:1.5px solid;border-right:1.5px solid;flex-shrink:0;width:6px;height:6px;margin-left:2px;transition:transform .15s;transform:rotate(-45deg)}.provider-response[open]>.provider-response__summary:before{transform:rotate(45deg)}.provider-response__summary:hover{color:var(--text)}.provider-response__summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--radius)}.provider-response__frame{border:0;border-top:1px solid var(--border);border-radius:0 0 var(--radius)var(--radius);background:#fff;width:100%;min-height:240px;display:block}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.kv__row{grid-template-columns:minmax(0,1fr)}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function Vr(e){return V`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
27
42
  ${e.styles}
28
- </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(Nr,"renderShell");function Is(e){return $`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?sh:ih}</div>`}n(Is,"renderStatusIcon");var kb="text/html; charset=utf-8";function jr(e){try{return new URL(e).host}catch{return""}}n(jr,"safeHostFromUrl");function Fe(e){let t=e.kind??"authorization_failed",r=Pb(t),o=Eb(e),s=e.title??r.title;return new Response(zr(Nr({title:s,iconHref:"",styles:qr,headerIcon:Is(t==="access_denied"?"neutral":"error"),heading:s,subhead:$`<p class="card__subtitle">${e.detail}</p>`,body:oh({steps:Mr(r.steps.map(i=>$`<li>${i}</li>`)),action:Ub(e.action),reference:Ob(o),diagnostics:Mb({diagnostic:o,detail:e.detail}),upstreamResponse:zb(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":kb,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Fe,"browserErrorPageResponse");function Eb(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Ab(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??xb(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(Eb,"buildBrowserErrorDiagnostic");function Pb(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(Pb,"readBrowserErrorPagePresentation");function Ab(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(Ab,"readBrowserErrorStage");function xb(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(xb,"readBrowserErrorSuggestedFix");function Ub(e){return e===void 0?xe:$`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Ub,"renderAction");function Cs(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 $`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}n(Cs,"renderRow");function ke(e){return Cs({label:e.label,value:e.value===void 0?void 0:$`<code>${e.value}</code>`})}n(ke,"renderCodeRow");function Ob(e){return Mr([Cs({label:"Error code",value:$`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),ke({label:"Request ID",value:e.requestId}),ke({label:"Time",value:e.timestamp})])}n(Ob,"renderReference");function Mb(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return Mr([Cs({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Cs({label:"Reason",value:r,block:!0}),ke({label:"Stage",value:t.stage}),ke({label:"Gateway route",value:t.routePath}),ke({label:"Operation ID",value:t.operationId}),ke({label:"Upstream",value:t.upstreamServerId}),ke({label:"Auth profile",value:t.authProfileId}),ke({label:"Upstream URL",value:t.upstreamUrl}),ke({label:"Metadata URL",value:t.metadataUrl}),ke({label:"HTTP status",value:t.httpStatus}),ke({label:"Content type",value:t.contentType}),ke({label:"Provider error",value:t.providerError}),ke({label:"Provider error description",value:t.providerErrorDescription})])}n(Mb,"renderDiagnostics");function zb(e){return e===void 0?xe:$`<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(zb,"renderUpstreamHtml");var ah="application/json",qb="application/x-www-form-urlencoded";function Ts(e,t){return new v({message:e,extensionMembers:{[C]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(Ts,"invalidRequestError");function Nb(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Nb,"normalizeContentType");function jb(e,t){return e===t?!0:t===ah&&e.endsWith("+json")}n(jb,"contentTypeMatches");function Db(e,t){if(!t||t.length===0)return;let r=Nb(e.headers.get("content-type"));if(!t.some(o=>jb(r,o)))throw Ts(`Request body must be ${t.join(" or ")}.`)}n(Db,"assertExpectedContentType");function $b(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 Ts(`${r} exceeded the maximum allowed size.`)}n($b,"assertContentLengthWithinLimit");async function ch(e,t){let r=t.label??"Request body";Db(e,t.expectedContentTypes),$b(e,t.maxBytes,r);let o=await fs(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>Ts(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ch,"readBoundedTextBody");async function dh(e,t){let r=await ch(e,{...t,expectedContentTypes:[ah]});try{return JSON.parse(r)}catch(o){throw Ts("Request body must be valid JSON.",o)}}n(dh,"readBoundedJsonBody");async function uh(e,t){let r=await ch(e,{...t,expectedContentTypes:[qb]});return new URLSearchParams(r)}n(uh,"readBoundedFormUrlEncodedBody");import{errors as ph,jwtVerify as mh,SignJWT as hh}from"jose";import{base64url as Lb}from"jose";var Hb="mcp-browser-login-pkce:",Bb=new TextEncoder;async function Fb(e){return crypto.subtle.importKey("raw",me(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}n(Fb,"importHmacKey");async function da(e){let t=await Fb(e.signingKey),r=Bb.encode(`${Hb}${e.stateId}`),o=await crypto.subtle.sign("HMAC",t,me(r));return Sr.parse(Lb.encode(new Uint8Array(o)))}n(da,"deriveBrowserLoginPkceVerifier");async function lh(e){let t=await da(e),r=await Qo(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:yr}}n(lh,"deriveBrowserLoginPkceParams");var Gb={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},R=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=Gb[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var Jb=300,Vb=l.object({purpose:l.literal("gateway_browser_login"),transactionId:ri,stateId:ni,exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Kb=l.object({purpose:l.literal("gateway_authorization_setup"),transactionId:ri,stateId:ni,exp:l.number().int().positive(),iat:l.number().int().positive().optional()});async function so(){return Be({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>_t(e,"browser-login"),"derive")})}n(so,"getBrowserLoginKey");async function fh(){return Be({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>_t(e,"authorization-csrf"),"derive")})}n(fh,"getCsrfKey");function gh(e){return{now:e.now??new Date,ttlSeconds:yh()}}n(gh,"readPendingTransactionDependencies");function yh(){return le().browserLogin.stateTtlSeconds}n(yh,"readBrowserLoginStateTtlSeconds");function Wb(e){let t=de();return ve(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(Wb,"isLoopbackDevLoginUrl");async function Zb(e){let t=le().browserLogin,r=de(),o=new URL(pt("url")),s=new URL(r.actionPath("/oauth/callback"),Cr(e.requestUrl,e.requestHeaders));if(Wb(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",pt("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===yr){let i=await lh({stateId:e.stateId,signingKey:await so()});o.searchParams.set("code_challenge",i.codeChallenge),o.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return o}n(Zb,"buildBrowserLoginUrl");function Yb(e,t){return e.subjectId===t.subjectId}n(Yb,"principalsMatch");function Sh(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(Sh,"toPendingPrincipal");function _h(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:D(e.now),expiresAt:D(Ye(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 x("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:Sh(e.principal)}}n(_h,"createTransactionRecord");async function wh(e){let{id:t,...r}=e.record,o=await N().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw x("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new R("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new R("invalid_request","redirect_uri is not registered for the client.")}}n(wh,"startPendingTransaction");async function Xb(e){return new hh({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await so())}n(Xb,"signBrowserLoginState");async function Rh(e){return new hh({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:si()}).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fh())}n(Rh,"signCsrfToken");async function ua(e){try{let{payload:t}=await mh(e,await so(),{algorithms:[Te],issuer:we,audience:Ce}),r=Vb.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof ph.JWTExpired?x("oauth_state_expired","Browser login state has expired.",t):x("oauth_state_invalid","Browser login state could not be verified.",t)}}n(ua,"verifyBrowserLoginStateToken");async function ks(e){try{let{payload:t}=await mh(e,await fh(),{algorithms:[Te],issuer:we,audience:Ce});return{transactionId:Kb.parse(t).transactionId}}catch(t){throw t instanceof ph.JWTExpired?x("oauth_state_expired","Authorization setup state has expired.",t):x("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(ks,"verifyCsrfToken");function la(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(la,"pendingStateErrorCode");function Qb(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(Qb,"toPendingAuthorizationGetResult");function ev(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(ev,"toPendingAuthorizationAdvanceResult");function pa(e){return e==="principal_mismatch"?"oauth_callback_mismatch":la(e==="consumed_already"?"consumed_already":e)}n(pa,"setupDecisionErrorCode");async function bh(e){let t=e.now??new Date,r=await ks(e.csrfToken),o=await N().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await X(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:D(t)});if(o.kind!=="marked")throw x(pa(o.kind),"Authorization setup state is invalid, expired, or already used.");return vh({kind:"available",record:o.transaction})}n(bh,"markSetupApproved");function vh(e){if(e.kind!=="available")throw x(la(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw x("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(vh,"requireAwaitingSetup");function tv(e){if(!Yb(e.currentBrowserPrincipal,e.transaction.principal))throw x("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(tv,"requireCurrentPrincipalMatches");async function Ih(e){let t=e.now??new Date,r=yh(),o=oi(),s=si(),i=await Xb({transactionId:o,stateId:s,ttlSeconds:r}),c=_h({id:o,transaction:e.transaction,currentStateHash:await X(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw x("oauth_state_invalid","Authorization transaction did not start in login phase.");let a=await wh({record:c,client:e.transaction.client});if(a.phase!=="awaiting_login")throw x("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await Zb({state:i,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:a,browserLoginStateToken:i,browserLoginUrl:u}}n(Ih,"startAwaitingLogin");async function Ch(e){let{now:t,ttlSeconds:r}=gh(e),o=oi(),s=await Rh({transactionId:o,ttlSeconds:r}),i=_h({id:o,transaction:e.transaction,currentStateHash:await X(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw x("oauth_state_invalid","Authorization transaction did not start in setup phase.");let c=await wh({record:i,client:e.transaction.client});if(c.phase!=="awaiting_setup")throw x("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:c,csrfToken:s}}n(Ch,"startAwaitingSetup");async function Th(e){let{now:t,ttlSeconds:r}=gh(e),o=await ua(e.browserLoginStateToken),s=await Rh({transactionId:o.transactionId,ttlSeconds:r}),i=ev(await N().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await X(e.browserLoginStateToken),nextStateHash:await X(s),nextPhase:"awaiting_setup",principal:Sh(e.principal),now:D(t)}));if(i.kind!=="advanced")throw x(la(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw x("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}n(Th,"completeLogin");async function kh(e){let t=await ma(e);return tv({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(kh,"getSetup");async function ma(e){let t=e.now??new Date,r=await ks(e.csrfToken);return vh(Qb(await N().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await X(e.csrfToken),now:D(t)})))}n(ma,"getSetupTransaction");async function rv(e){let t=await ks(e.csrfToken),r=Qe(),o=D(Ye(e.now,Jb)),s=await N().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await X(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await X(r),authorizationCodeExpiresAt:o,grantId:dl(),now:D(e.now)});if(s.kind!=="approved")throw x(s.kind==="cancelled"?"oauth_state_invalid":pa(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),i}n(rv,"createAuthorizationCodeRedirectWithDecision");async function nv(e){let t=await ks(e.csrfToken),r=await N().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await X(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:D(e.now)});if(r.kind!=="cancelled")throw x(r.kind==="approved"?"oauth_state_invalid":pa(r.kind),"Authorization setup state is invalid, expired, or already used.");return ov({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(nv,"createCancelRedirectWithDecision");function ov(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(ov,"buildClientCancelRedirect");async function Eh(e){let t=e.now??new Date;return rv({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Eh,"approve");async function Ph(e){let t=e.now??new Date;return nv({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ph,"cancel");import{createRemoteJWKSet as sv,errors as Dr,jwtVerify as Ah,SignJWT as iv}from"jose";var ga="zuplo_mcp_session",av=l.object({purpose:l.literal("gateway_browser_session"),sub:Bn,browserLoginOrigin:l.string().min(1),roles:l.array(l.string().min(1)).optional(),exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),cv=l.object({id_token:l.string().min(1),token_type:l.string().min(1).optional(),expires_in:l.number().optional(),access_token:l.string().min(1).optional(),refresh_token:l.string().min(1).optional(),scope:l.string().min(1).optional()}),dv=l.object({error:l.string().min(1).optional(),error_description:l.string().min(1).optional(),error_uri:l.string().min(1).optional()}),uv=l.object({sub:Bn,nonce:l.string().min(1)}).catchall(l.unknown()),ha;function lv(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(lv,"parseCookieHeader");async function xh(){return Be({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>_t(e,"browser-session"),"derive")})}n(xh,"getBrowserSessionKey");function fa(e,t){let r=new URL(Y(e,t)),o=[`${ga}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return r.protocol==="https:"&&o.push("Secure"),o.join("; ")}n(fa,"buildBrowserSessionEvictionCookie");function pv(e){let t=new URL(Y(e.requestUrl,e.requestHeaders)),r=[`${ga}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(pv,"serializeSessionCookie");function Uh(){return new URL(pt("url")).origin}n(Uh,"readBrowserLoginOrigin");function mv(e){let t=dv.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(mv,"readIdpErrorFields");function hv(e){return e instanceof Dr.JWTExpired?"expired":e instanceof Dr.JWTClaimValidationFailed?"claim":e instanceof Dr.JWSSignatureVerificationFailed?"signature":e instanceof Dr.JWKSNoMatchingKey?"jwks_no_match":e instanceof Dr.JWTInvalid?"invalid":e instanceof l.ZodError?"schema":"other"}n(hv,"readJwtFailureKind");function fv(e){return e instanceof Error&&"cause"in e?e.cause:e}n(fv,"readErrorCause");function gv(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(gv,"readRuntimeGatewayCode");function yv(){if(!ha){let e=le();ha=sv(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return ha}n(yv,"readFederatedJwks");function Oh(e){if(!e.user)throw x("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Lt(e.user,e.url)}n(Oh,"resolveCurrentRequestPrincipal");async function Es(e,t={}){let r=lv(e.headers.get("cookie")).get(ga);if(!r)return{};try{let{payload:o}=await Ah(r,await xh(),{algorithms:[Te],issuer:we,audience:Ce}),s=av.parse(o);if(s.browserLoginOrigin!==Uh())return{evictCookie:fa(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 Dr.JWTExpired?{evictCookie:fa(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:fa(e.url,e.headers)})}}n(Es,"readBrowserSession");async function Ps(e){let t=le().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:Uh()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new iv(r).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await xh());return pv({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(Ps,"createBrowserSessionCookie");async function Sv(e){let t=le(),r=pt("tokenUrl"),o=pt("clientId"),s=pt("clientSecret"),i=new URL(de().actionPath("/oauth/callback"),Cr(e.requestUrl,e.requestHeaders)).toString(),c=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:o,client_secret:s});if(t.browserLogin.pkce===yr){let a=await da({stateId:e.stateId,signingKey:await so()});c.set("code_verifier",a)}try{let{response:a,json:u}=await gs(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:c},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!a.ok){let S=mv(u);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:te(r),idpStatus:a.status,...S},"Federated browser login token exchange returned non-2xx from the identity provider"),x({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${a.status}${S.idpError?` idp_error=${S.idpError}`:""}${S.idpErrorDescription?` idp_error_description=${S.idpErrorDescription}`:""})`)})}let p=cv.parse(u),h;try{({payload:h}=await Ah(p.id_token,yv(),{issuer:t.oidc.issuer,audience:o}))}catch(S){let k={};throw pe(k,"error",S),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:hv(S),idpHost:te(r),expectedIssuer:t.oidc.issuer,...k},"Federated id_token failed jose verification"),S}if(h.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:te(r),nonceMissingFromIdToken:h.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),x("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let f=uv.parse(h);return{principal:Lt({sub:f.sub,data:f},e.requestUrl),subjectToken:{token:p.id_token,tokenType:Gn,expiresAt:typeof h.exp=="number"?D(new Date(h.exp*1e3)):void 0}}}catch(a){let u=Ze(a)??gv(a);throw u!==void 0&&u!=="browser_login_verification_failed"?a:x("browser_login_verification_failed","Federated browser login callback could not be verified.",fv(a))}}n(Sv,"exchangeFederatedAuthorizationCode");async function Mh(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return Sv({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await Es(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw x("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(Mh,"resolveBrowserLoginCallbackIdentity");var _v=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function wv(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(wv,"readScheme");function Rv(e){return e.protocol==="https:"}n(Rv,"isSpecCompliantRedirectUri");function bv(e){let t=wv(e);return t.length>0&&t!=="http"&&t!=="https"&&!_v.has(t)}n(bv,"isNativeAppCustomSchemeRedirectUri");var qh=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>Rv(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>ve(e),"accepts"),matches:n((e,t)=>ve(e)&&ve(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>bv(e),"accepts")}];function Nh(e){let t=qh.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(Nh,"evaluateBuiltInRedirectUriCompatibility");function zh(e){try{return new URL(e)}catch{return}}n(zh,"parseUrl");function jh(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=zh(e.registeredRedirectUri),r=zh(e.requestedRedirectUri);return t===void 0||r===void 0?!1:qh.some(o=>o.matches?.(t,r))}n(jh,"redirectUriMatchesBuiltInCompatibility");var vv=1e4,Iv=5*1024,Cv=0,Tv=2160*60*60,Dh=["authorization_code","refresh_token",Ko,mt],kv=["authorization_code","refresh_token"],$h=[il],Ev=["code"],Pv=l.object({client_name:l.string().min(1).optional(),redirect_uris:l.array(l.string().min(1)).min(1),grant_types:l.array(l.enum(Dh)).min(1).max(Dh.length).optional(),authorization_grant_profiles_supported:l.array(l.enum($h)).min(1).max($h.length).optional(),response_types:l.array(l.enum(Ev)).min(1).max(1).optional(),scope:l.literal(ne).optional(),token_endpoint_auth_method:cl.optional(),jwks_uri:l.string().min(1).optional()});function Av(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&ve(t))&&t.pathname!=="/"}catch{return!1}}n(Av,"isCimdClientIdCandidate");function Lh(e,t){throw new R("invalid_client",yl({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Lh,"invalidCimdClientError");function $r(e,t="invalid_request"){if(xv(e))throw new R(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new R(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new R(t,"redirect_uris must not include credentials or fragments.");if(Nh({url:r}).kind==="rejected")throw new R(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n($r,"assertValidRedirectUri");function xv(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(xv,"hasForbiddenRawRedirectUriCharacter");async function Uv(e){let{response:t,json:r}=await Kp(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Cv,maxResponseBytes:Iv,timeoutMs:vv});if(!t.ok)throw x("invalid_request","CIMD metadata could not be fetched.");let o=Zo(r);for(let s of o.redirect_uris)$r(s,"invalid_request");if(o.jwks_uri!==void 0&&Vn(o.jwks_uri),o.client_id!==e.clientId)throw x("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(Uv,"fetchCimdMetadata");async function Ov(e){let t=Yo(e),r=await Uv({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(Ov,"resolveCimdClient");async function As(e,t){let r=Xe.parse(e);if(Av(r)){le().gateway.downstreamCimdEnabled||Lh(r);try{return await Ov(r)}catch(s){Lh(r,s)}}let o=await N().readClient({clientId:r});if(o.kind==="found"){let s=o.client,i=_l(s.clientId),c=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",a=s.jwksUri??i;if(c==="private_key_jwt"&&a===void 0)throw new R("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let u=Zo({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:c,...a===void 0?{}:{jwks_uri:a}}),p={kind:"dcr",clientId:r,metadata:u};return s.hashedClientSecret&&(p.hashedClientSecret=s.hashedClientSecret),p}throw new R("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(As,"resolveClient");function Hh(e,t){if(!e.metadata.redirect_uris.some(r=>jh({registeredRedirectUri:r,requestedRedirectUri:t})))throw x("invalid_request","redirect_uri is not registered for the client.")}n(Hh,"assertRedirectRegistered");function Mv(e){return e===void 0?[...kv]:Array.from(new Set(e))}n(Mv,"normalizeGrantTypes");function zv(e){try{Vn(e)}catch(t){throw new R("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(zv,"assertValidDcrJwksUri");function qv(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?Xe.parse(Sl({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):Xe.parse(`dcr:${crypto.randomUUID()}`)}n(qv,"createDcrClientId");function Lr(e){if(e===void 0||e===ne)return ne;throw new R("invalid_request",`Only the ${ne} scope is supported.`)}n(Lr,"assertSupportedOAuthScope");function Ft(e,t,r){let o;try{o=new URL(t)}catch{throw new R("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new R("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!ve(o))throw new R("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=Y(e,r),i=ol(),c=i?[...i.byOperationId.values()].find(a=>new URL(a.routePath,s).toString()===t):void 0;if(!c)throw new R("invalid_target","resource must match a published MCP route.");return c}n(Ft,"resolveResource");async function Bh(e){let t;try{t=Pv.parse(e)}catch(S){if(S instanceof l.ZodError){let k=S.issues.some(w=>w.path[0]==="redirect_uris");throw new R(k?"invalid_redirect_uri":"invalid_client_metadata",S.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:S})}throw S}for(let S of t.redirect_uris)$r(S,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new R("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&zv(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",s=o==="private_key_jwt"?"none":o,i=qv({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),c=Zo({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}}),a=Ye(r,Tv),u=Math.floor(r.getTime()/1e3),p=Math.floor(a.getTime()/1e3),h={client_id:c.client_id,client_name:c.client_name,redirect_uris:c.redirect_uris,grant_types:Mv(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:ne,token_endpoint_auth_method:c.token_endpoint_auth_method,client_id_issued_at:u,jwks_uri:c.jwks_uri},f={clientId:c.client_id,clientName:c.client_name,redirectUris:c.redirect_uris,tokenEndpointAuthMethod:s,createdAt:D(r),clientExpiresAt:D(a)};if(o==="client_secret_basic"||o==="client_secret_post"){let S=Qe();f.hashedClientSecret=await X(S),f.clientSecretExpiresAt=D(a),h.client_secret=S,h.client_secret_expires_at=p,h.client_secret_issued_at=u}if((await N().registerClient(f)).kind==="already_exists")throw x("invalid_request","OAuth client is already registered.");return h}n(Bh,"registerDownstreamClient");function Nv(e){return e?.metadata?.idpSubjectTokenType!==Tr&&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(Nv,"hasStoredIdJagSubjectTokenBinding");async function Fh(e){let t=Ir(e.principal.subjectId);return(await N().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Fh,"readIdJagSubjectConnection");async function ya(e){let t=Se().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Fh({connection:t.connection,principal:e.principal});return!Nv(r)}n(ya,"requiresIdJagSubjectTokenBinding");async function Gh(e){if(e.subjectToken===void 0)return;let t=Se().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 Fh({connection:t.connection,principal:e.principal});return N().upsertUpstreamConnection({id:r?.id??Xo(),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 et(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Gh,"bindIdJagSubjectTokenForAuthorizationTransaction");function Jh(e){return $`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(Jh,"renderShellIcon");function Vh(e){return $`<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(Vh,"renderActions");var Kh=Ae('<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 Wh(e){return $`<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(Wh,"renderBannerWarning");var iO=Ae('<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>'),aO=Ae('<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 cO=Ae('<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 jv="data:,",Zh=$`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);"`,Yh=$`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 Dv(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(Dv,"safeGatewayConnectHref");function $v(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n($v,"deriveMode");function Lv(e){return Vh({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Zh,authorizeAttrs:xe})}n(Lv,"renderActions");function Sa(e,t,r,o){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=Dv(s.connectUrl,t,o);if(i)return i}}n(Sa,"firstUserConnectHref");function Hv(e){let t=e.connectHref===void 0?xe:$`<a class="button button--primary" href="${e.connectHref}" ${Yh}>Connect</a>`;return $`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Zh}><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(Hv,"renderSetupActions");function Bv(e){return e?$`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Yh}>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}n(Bv,"renderReconnectAction");function Fv(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(Fv,"isRenderableIconHref");function Xh(e){return e?.find(t=>Fv(t.src))?.src}n(Xh,"readIconHref");function Gv(e){return Xh(e.serverIcons)??(e.transportHost===void 0?void 0:Bi(e.transportHost).src)}n(Gv,"readUpstreamIconHref");function Jv(e){let t=Xh(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=Gv(r);if(o!==void 0)return o}}n(Jv,"readHeaderIconHref");function Vv(e){let t=e.setupMessage===void 0?xe:Wh({icon:Kh,message:e.setupMessage});return $`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(Vv,"renderBody");function _a(e){let t=$v(e.upstreams),r=Sa(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=Sa(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=Sa(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o:void 0,c=t==="setup"?e.upstreams.find(p=>p.ownerMode==="user"&&p.status!=="active"&&p.connectUrl===void 0&&p.setupMessage!==void 0)?.setupMessage:void 0,a=Jv({routeIcons:e.routeIcons,upstreams:e.upstreams}),u=t==="setup"?$`<footer class="card__footer">${Hv({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:$`<footer class="card__footer">${Bv(s)}${Lv({state:e.state,gateway:e.gateway})}</footer>`;return zr(Nr({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:a??jv,styles:qr,headerIcon:a===void 0?xe:Jh({iconHref:a,fallbackIconHref:Hp}),heading:"Authorize access",subhead:xe,body:Vv({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:c}),footer:u}))}n(_a,"renderConsentPage");var Kv=1e4,Qh="mcp-session-id",Wv;function of(){return{tools:[],prompts:[],resources:[]}}n(of,"emptyCapabilities");function ef(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":ii})}n(ef,"buildReadinessHeaders");async function tf(e){if(e.type==="bearer_token"){let o=ef();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=ef();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(tf,"buildAsyncCredentialHeaders");function rf(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Dt.parse({jsonrpc:mr,id:1,method:"initialize",params:{protocolVersion:ii,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(rf,"buildInitializePreflight");async function wa(e){Jn(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Kv);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await Oo.fetch(o)}finally{clearTimeout(r)}}n(wa,"runPreflight");function Ra(e){e.body?.cancel().catch(()=>{})}n(Ra,"releasePreflightBody");async function Zv(e){let t=e.response.headers.get(Qh);if(!t)return;let r=new Headers(e.headers);r.set(Qh,t),r.delete("content-type");try{let o=await wa(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Ra(o)}catch{}}n(Zv,"terminatePreflightSession");async function sf(e){let{response:t}=e;return Ra(t),t.status>=200&&t.status<300?(await Zv(e),{kind:"ready",upstreamStatus:t.status,capabilities:of()}):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(sf,"classifyResponse");function nf(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(nf,"connectRequiredResult");async function Yv(e){try{return sf({response:await wa(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Yv,"classifyPreflight");async function Xv(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:of()};let r=bs(t.upstreamServerId,e.route.operationId),o=Or(r,e.subjectId),s=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),c=await Ur({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(c.kind==="connect_required")return nf(c.payload);let a=await tf(c.credential);if(a===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let u=rf({upstreamUrl:t.mcpUrl,headers:a}),p;try{p=await wa(u)}catch(y){return{kind:"upstream_unavailable",message:y instanceof Error?y.message:"Upstream MCP server readiness preflight failed."}}if(p.status!==401)return sf({response:p,upstreamUrl:t.mcpUrl,headers:a});Ra(p);let h=await Ur({request:i,routeAuth:s,forceRefresh:!0});if(h.kind==="connect_required")return nf(h.payload);let f=await tf(h.credential);return f===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Yv({request:rf({upstreamUrl:t.mcpUrl,headers:f}),upstreamUrl:t.mcpUrl,headers:f})}n(Xv,"checkUpstreamRouteReadinessImpl");function af(e){return(Wv??Xv)(e)}n(af,"checkUpstreamRouteReadiness");function Qv(e){try{return new URL(e).host}catch{return}}n(Qv,"safeUrlHost");function cf(e){return e!==void 0&&e.length>0}n(cf,"hasItems");function eI(e){let t=e.serverInfo?.icons;if(cf(t))return t;let r=ms(e.mcpUrl);return r===void 0?void 0:[r]}n(eI,"readServerIcons");async function tI(e){let{authConfig:t,authMode:r,description:o,displayName:s,mcpUrl:i,ownerMode:c,upstreamServerId:a,authProfileId:u}=e.registeredConnection,p=c==="user",h=p&&r!=="id-jag",f=e.readiness??(p?Il(e.connection):{connected:!0,status:"active"}),y=h?e.readiness?.connectUrl??(e.returnTo!==void 0?await Ji({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:a,authProfileId:u,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,S=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:a,authProfileId:u,authMode:r,ownerMode:c,upstreamDisplayName:s,description:o,transportHost:Qv(i),scopesRequested:cf(S)?S:void 0,serverIcons:eI(e.registeredConnection),status:f.status,connected:f.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:y,setupMessage:e.setupMessage,updatedAt:p&&"updatedAt"in f&&f.updatedAt!==void 0?f.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}n(tI,"buildSetupRequirement");function df(e){let t=Se().byOperationId.get(e);if(!t)throw x("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(df,"requireRoute");async function ba(e){let t=df(e.transaction.operationId),r=Ir(e.transaction.principal.subjectId),o=t.connection;if(o===void 0)return[];let i=o.ownerMode==="user"?(await N().batchGetUpstreamConnections([{owner:r,upstreamServerId:o.upstreamServerId,authProfileId:o.authProfileId}]))[0]:void 0,c=await af({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),a="connectionStatus"in c?c.connectionStatus:void 0,u=(c.kind==="connect_required"||c.kind==="admin_setup_required")&&c.payload.authUrl!==void 0?c.payload.authUrl:void 0,p=c.kind==="admin_setup_required"?c.payload.message:void 0;return[await tI({connection:i,registeredConnection:o,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:p,readiness:a===void 0?void 0:{...a,connectUrl:u}})]}n(ba,"requirementsForSetup");async function va(e){let t=df(e.transaction.operationId),r=await N().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,s={gatewayOrigin:Y(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(va,"consentContext");function Ia(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Ia,"hasUnresolvedUserUpstream");var rI=["mcp_user"],nI="dev-browser-user",oI=["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(" "),sI=l.object({response_type:l.literal("code"),client_id:l.string().min(1),redirect_uri:l.string().min(1),resource:l.url(),code_challenge:l.string().min(43),code_challenge_method:Fu,state:l.string().min(1).optional(),scope:l.literal(ne).default(ne)}),iI=l.enum(["continue","approve","cancel"]).default("continue"),aI=l.object({state:l.string().min(1),decision:iI}),bt=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function uf(e){return typeof e=="string"&&e.length>0?e:void 0}n(uf,"readQueryString");function cI(e,t){let r=uf(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new R("invalid_target",oI)}let o=ml(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new R("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(cI,"requireAuthorizeResource");async function dI(e,t){let r={};t!==void 0&&(r.context=t);let o=await Es(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let s=Oh(e);return{principal:s,setCookie:await Ps({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(dI,"resolveBrowserPrincipal");async function uI(e,t){let r={};t!==void 0&&(r.context=t);let o=await Es(e,r);if(!o.principal)throw x("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(uI,"requireSetupPrincipal");function lf(e){return`${de().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(lf,"buildSetupReturnTo");async function pf(e){let t=await ba({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:lf(e.csrfToken)}),r=await va({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:_a({state:e.csrfToken,operationId:e.transaction.operationId,gateway:de(),upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(pf,"renderSetup");function lI(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(lI,"toAuthorizationTransactionClient");async function Ca(e,t={}){let r=sI.parse({...e.query,resource:cI(e,t.operationId),state:uf(e.query.state)}),o=Lr(r.scope);$r(r.redirect_uri,"invalid_request");let s=new Date,i=Xe.parse(r.client_id),c=await As(r.client_id,s);Hh(c,r.redirect_uri);try{let a=Ft(e.url,r.resource,e.headers),u=lI(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,operationId:a.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&J(t.context,{eventType:B.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:a.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type}});let p={clientId:c?.clientId??i,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:a.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:h,setCookie:f}=await dI(e,t.context),y=h===void 0?!1:await ya({operationId:a.operationId,principal:h});if(!h||y){let k=await Ih({transaction:p,requestUrl:e.url,requestHeaders:e.headers,now:s});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,operationId:a.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login");let w={kind:"redirect",location:k.browserLoginUrl};return f!==void 0&&(w.setCookie=f),w}let S=await Ch({transaction:p,principal:h,now:s});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,operationId:a.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&J(t.context,{eventType:B.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:a.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),pf({transaction:S.transaction,csrfToken:S.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookie:f})}catch(a){throw pI({redirectUri:r.redirect_uri,clientState:r.state,cause:a})}}n(Ca,"authorizeDownstreamClient");function pI(e){if(e.cause instanceof bt)return e.cause;let t=mI(e.cause);return t?new bt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(pI,"toDownstreamAuthorizeRedirectError");function mI(e){if(e instanceof R)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof l.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(mI,"mapToOAuthRedirectError");async function mf(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,h=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,...p===void 0?{}:{idpErrorDescription:p},...h===void 0?{}:{idpErrorUri:h}},"Identity provider redirected browser-login callback with an error"),x("provider_access_denied",p??"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"),x("oauth_state_invalid","Browser login callback is missing state.");let s=await ua(o),i={request:e,stateId:s.stateId};t.context!==void 0&&(i.context=t.context);let c=await Mh(i),a=await Th({browserLoginStateToken:o,principal:c.principal});if(await Gh({transaction:a.transaction,principal:c.principal,subjectToken:c.subjectToken}),await ya({operationId:a.transaction.operationId,principal:c.principal}))throw x("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");let u=await pf({transaction:a.transaction,csrfToken:a.csrfToken,requestUrl:e.url,requestHeaders:e.headers});return u.setCookie=await Ps({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),u}n(mf,"completeBrowserLoginCallback");async function hf(e){let t=le(),r=new URL(e.url);if(!ve(r))throw x("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 x("oauth_state_invalid","Local browser login is missing state.");let s=de().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,Y(e.url)),c=new URL(Y(e.url)).origin;if(i.origin!==c||i.pathname!==s)throw x("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",o);let a={subjectId:Bn.parse(nI),roles:rI};return{kind:"redirect",location:i,setCookie:await Ps({principal:a,requestUrl:e.url,requestHeaders:e.headers})}}n(hf,"completeLocalDevBrowserLogin");function hI(e){let t=e.method==="POST"?e.body:e.query;return aI.parse(t)}n(hI,"readSetupContinueRequest");async function ff(e){let{state:t,decision:r}=hI({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,s=await ma({csrfToken:t,now:o}),i=await uI(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ph({csrfToken:t,currentBrowserPrincipal:i,now:o})};let c=await kh({csrfToken:t,currentBrowserPrincipal:i,now:o}),a=await ba({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:lf(t)});if(r==="approve"&&Ia(a)&&await bh({csrfToken:t,currentBrowserPrincipal:i,now:o}),Ia(a)){let u=await va({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:_a({state:t,operationId:c.operationId,gateway:de(),upstreams:a,...u})}}return{kind:"redirect",location:await Eh({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(ff,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as kI,decodeJwt as EI,errors as ao,jwtVerify as PI}from"jose";import{createRemoteJWKSet as fI,decodeJwt as gI,decodeProtectedHeader as yI,errors as io,jwtVerify as SI}from"jose";var wf=30,Q=l.string().min(1),_I=l.union([Q,l.array(Q).min(1)]),wI=l.union([Q,l.array(Q).min(1)]),RI=l.object({type:Q,locations:l.array(Q).optional(),actions:l.array(Q).optional(),datatypes:l.array(Q).optional(),identifier:Q.optional(),privileges:l.array(Q).optional()}).passthrough(),bI=l.object({iss:l.url(),sub:Q,aud:_I,client_id:Q,resource:wI.optional(),scope:Q.optional(),authorization_details:l.array(RI).optional(),jti:Q,iat:l.number().int(),nbf:l.number().int().optional(),exp:l.number().int(),tenant:Q.optional(),aud_tenant:Q.optional(),aud_sub:Q.optional(),sub_id:Q.optional(),act:l.unknown().optional(),email:Q.optional(),auth_time:l.number().int().optional(),acr:Q.optional(),amr:l.array(Q).optional(),cnf:l.unknown().optional()}).passthrough();function Ee(e){throw new R("invalid_grant",e)}n(Ee,"throwInvalidGrant");function vI(e){return e instanceof io.JWTExpired?"expired":e instanceof io.JWTClaimValidationFailed?"claim":e instanceof io.JWSSignatureVerificationFailed?"signature":e instanceof io.JWKSNoMatchingKey?"jwks_no_match":e instanceof io.JWTInvalid?"invalid":e instanceof l.ZodError?"schema":"other"}n(vI,"readJwtFailureKind");function II(e){return Array.isArray(e.aud)?(e.aud.length!==1&&Ee("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(II,"readSingleAudience");function gf(e){try{let t=bI.parse(e);return II(t),t}catch(t){if(t instanceof R)throw t;Ee("ID-JAG claims are invalid.")}}n(gf,"parseIdJagClaims");function CI(e,t){e.idJag.enabled||Ee("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&Ee("ID-JAG issuer is not trusted."),r}n(CI,"readTrustedIssuer");function TI(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(TI,"readGrantedAuthorizationDetails");function yf(e){if(e.clientAuth.method==="none")throw new R("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&Ee("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&Ee("ID-JAG client_id is not allowed for this issuer.")}n(yf,"assertClientBinding");function Sf(e){e.cnf!==void 0&&Ee("ID-JAG cnf-bound assertions require DPoP support.")}n(Sf,"assertProofOfPossessionNotDeferred");function _f(e){let t=Math.floor(e.now.getTime()/1e3)+wf;e.claims.iat>t&&Ee("ID-JAG iat must not be in the future.")}n(_f,"assertIssuedAtNotInFuture");async function Rf(e){let t;try{t=yI(e.assertion)}catch{Ee("ID-JAG assertion is malformed.")}t.typ!==ei&&Ee('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=gf(gI(e.assertion))}catch(a){if(a instanceof R)throw a;Ee("ID-JAG assertion is malformed.")}let o=Cr(e.requestUrl,e.requestHeaders),s=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&s.push(e.requestedResource);let i=CI(e.config,r.iss);s.includes(r.iss)&&Ee("ID-JAG issuer must be different from the gateway."),yf({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),Sf(r),_f({claims:r,now:e.now});let c;try{let a=fI(new URL(i.jwksUrl)),{payload:u}=await SI(e.assertion,a,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:wf,typ:ei});c=gf(u)}catch(a){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:vI(a)},"OAuth ID-JAG assertion verification failed"),Ee("ID-JAG assertion verification failed.")}return yf({claims:c,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),Sf(c),_f({claims:c,now:e.now}),{claims:c,trustedIssuer:i,subjectId:hl({issuer:c.iss,subject:c.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:c.tenant}),grantedAuthorizationDetails:TI({authorizationDetails:c.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(Rf,"verifyIdJagAssertion");var AI=new Set(["authorization_code","refresh_token",mt]),xI=1e4,UI=32*1024,OI=2,MI=3600,Ta=l.object({client_id:l.string().min(1).optional(),client_secret:l.string().min(1).optional(),client_assertion_type:l.string().min(1).optional(),client_assertion:l.string().min(1).optional()}),zI=l.discriminatedUnion("grant_type",[Ta.extend({grant_type:l.literal("authorization_code"),code:l.string().min(1),redirect_uri:l.string().min(1),code_verifier:Sr,resource:l.url().optional(),scope:l.literal(ne).optional()}),Ta.extend({grant_type:l.literal("refresh_token"),refresh_token:l.string().min(1),resource:l.url().optional(),scope:l.literal(ne).optional()}),Ta.extend({grant_type:l.literal(mt),assertion:l.string().min(1),resource:l.url().optional(),scope:l.literal(ne).optional(),authorization_details:l.string().min(1).optional()})]);function qI(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!AI.has(t)))throw new R("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(qI,"assertSupportedGrantType");var NI=l.object({token:l.string().min(1),client_id:l.string().min(1).optional(),token_type_hint:l.string().optional(),client_secret:l.string().min(1).optional(),client_assertion_type:l.string().min(1).optional(),client_assertion:l.string().min(1).optional()}),jI=l.object({keys:l.array(l.record(l.string(),l.unknown())).min(1)}).passthrough();function vf(){return le().gateway.accessTokenTtlSeconds}n(vf,"readAccessTokenTtlSeconds");function DI(){return le().gateway.refreshTokenTtlSeconds}n(DI,"readRefreshTokenTtlSeconds");function bf(e,t){let r=vf(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,o);return{expiresAt:D(Ye(e,s)),expiresIn:s}}n(bf,"calculateAccessTokenExpiresAt");function $I(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 R("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new R("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new R("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}n($I,"readIdJagResource");function LI(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 R("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}n(LI,"readIdJagGrantedAuthorizationDetails");function HI(e){if(e.claimScope?.split(/\s+/).includes(ne)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return ne;if(e.claimScope===void 0)throw new R("invalid_grant",`ID-JAG must include ${ne} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(ne))throw new R("invalid_grant",`ID-JAG scope must include ${ne}.`);return ne}n(HI,"readIdJagGrantedScope");function BI(e){if(e!==void 0&&e.get("dpop")!==null)throw new R("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}n(BI,"assertNoDpopProofForIdJag");function If(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new R("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new R("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new R("invalid_client","Malformed HTTP Basic client authentication.")}}n(If,"readBasicClientSecret");function Cf(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new R("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=EI(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new R("invalid_client","Malformed private_key_jwt client assertion.")}throw new R("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new R("invalid_client","Client authentication or client_id is required.")}n(Cf,"resolveAuthenticatedClientId");function FI(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new R("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(FI,"resolveClientSecretInput");function GI(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(GI,"hasClientAssertion");function JI(e){if(e.requestUrl===void 0)throw new R("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(de().actionPath(e.pathname),Y(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(JI,"buildEndpointAudience");function VI(e){return e instanceof ao.JWTExpired?"expired":e instanceof ao.JWTClaimValidationFailed?"claim":e instanceof ao.JWSSignatureVerificationFailed?"signature":e instanceof ao.JWKSNoMatchingKey?"jwks_no_match":e instanceof ao.JWTInvalid?"invalid":e instanceof l.ZodError?"schema":"other"}n(VI,"readJwtFailureKind");async function KI(e){let{response:t,json:r}=await Wp(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:OI,maxResponseBytes:UI,timeoutMs:xI});if(!t.ok)throw new R("invalid_client","Client JWKS could not be fetched.");return jI.parse(r)}n(KI,"fetchClientJwks");async function WI(e){if(e.clientAssertionType!==Wo||e.clientAssertion===void 0)throw new R("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=Xe.parse(e.clientId),r=await As(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new R("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new R("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=JI({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await KI({jwksUri:o,context:e.context}),{payload:c}=await PI(e.clientAssertion,kI(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),a=Math.floor(e.now.getTime()/1e3)+MI;if(typeof c.exp!="number"||c.exp>a)throw new R("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:VI(i)},"OAuth private_key_jwt client authentication failed"),new R("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(WI,"verifyPrivateKeyJwtClientAssertion");async function ZI(e){let t=Xe.parse(e.clientId);if(wl(t))throw new R("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 X(e.clientSecret)}}n(ZI,"buildRuntimeHttpClientAuth");async function Tf(e){if(GI({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new R("invalid_request","Use only one client authentication method per request.");return WI(e)}let t=FI({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return ZI({clientId:e.clientId,...t})}n(Tf,"resolveRuntimeHttpClientAuth");async function kf(e){qI(e.body);let t=zI.parse(e.body),r=If(e.authorizationHeader),o=Cf({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await Tf({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 YI({parsed:t,clientId:o,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(kf,"exchangeDownstreamToken");async function YI(e){if(e.parsed.grant_type==="authorization_code"){$r(e.parsed.redirect_uri,"invalid_request"),Lr(e.parsed.scope),e.parsed.resource!==void 0&&Ft(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let a=Qe(),u=Qe(),p=D(Ye(e.now,DI())),h=bf(e.now,p),f=await N().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await X(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Qo(e.parsed.code_verifier),currentRefreshTokenHash:await X(a),accessTokenHash:await X(u),grantExpiresAt:p,accessTokenExpiresAt:h.expiresAt,now:D(e.now)});if(f.kind==="invalid_client")throw new R("invalid_client","Client authentication failed.");if(f.kind==="resource_mismatch")throw new R("invalid_target","Token request resource must match the authorization code resource.");if(f.kind!=="exchanged")throw new R("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&J(e.context,{eventType:B.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:u,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:a,scope:f.grant.scope,resource:f.grant.resource}}if(e.parsed.grant_type===mt){Lr(e.parsed.scope),BI(e.requestHeaders);let a=await Rf({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:le()}),u=$I({claimedResource:a.claims.resource,requestedResource:e.parsed.resource}),p=Ft(e.requestUrl??u,u,e.requestHeaders),h=LI({claimAuthorizationDetails:a.claims.authorization_details,grantedAuthorizationDetails:a.grantedAuthorizationDetails,resource:u}),f=HI({claimScope:a.claims.scope,grantedAuthorizationDetails:h}),y=Qe(),S=D(new Date(a.claims.exp*1e3)),k=bf(e.now,S),w=await N().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await X(y),subjectId:a.subjectId,resource:u,operationId:p.operationId,scope:f,authorizationDetails:h,accessTokenExpiresAt:k.expiresAt,now:D(e.now),idJag:{issuer:a.claims.iss,jti:a.claims.jti,tenant:a.claims.tenant,expiresAt:S}});if(w.kind==="invalid_client")throw new R("invalid_client","Client authentication failed.");if(w.kind==="resource_mismatch")throw new R("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&J(e.context,{eventType:B.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:y,token_type:"Bearer",expires_in:k.expiresIn,scope:w.grant.scope,resource:w.grant.resource,...h===void 0?{}:{authorization_details:h}}}Lr(e.parsed.scope),e.parsed.resource!==void 0&&Ft(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await X(e.parsed.refresh_token),r=e.parsed.refresh_token,o=Qe(),s=D(Ye(e.now,vf())),i=await N().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await X(o),resource:e.parsed.resource,accessTokenExpiresAt:s,now:D(e.now)});if(i.kind==="invalid_client")throw new R("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new R("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new R("invalid_grant","Refresh token is invalid, expired, or revoked.");Ft(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let c=i.accessToken.expiresAt;return e.context&&J(e.context,{eventType:B.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(c).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}n(YI,"exchangeDownstreamTokenWithRuntimeHttp");async function Ef(e){let t=NI.parse(e.body),r=If(e.authorizationHeader),o=Cf({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await N().revokeOAuthToken({clientAuth:await Tf({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 X(t.token),now:D(s)})).kind==="invalid_client")throw new R("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&&J(e.context,{eventType:B.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Ef,"revokeDownstreamToken");var XI=64*1024,QI=16*1024,eC="text/html; charset=utf-8";function tC(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(tC,"formDataToObject");async function rC(e){return dh(e,{maxBytes:XI,label:"Request body"})}n(rC,"readJsonBody");async function Ea(e){return tC(await uh(e,{maxBytes:QI,label:"Request body"}))}n(Ea,"readFormBody");async function Pf(e,t,r){let o=Ze(r),s=r instanceof l.ZodError?vt(r):void 0,i={code:o??(r instanceof l.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),Go(e,t,i)}n(Pf,"handleProblem");function Af(e){return e?.requestId}n(Af,"readBrowserRequestId");function xf(e){if(!(e instanceof v))return;let t=e.extensionMembers?.[wr];return typeof t=="string"?t:void 0}n(xf,"readUpstreamHtmlError");function Hr(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Hr,"readRuntimeErrorExtensionString");function nC(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(nC,"readRuntimeErrorExtensionNumber");function oC(e){try{return new URL(e.url).pathname}catch{return}}n(oC,"readBrowserRequestPath");function Gt(e){let t={code:e.code,requestId:e.requestId,routePath:oC(e.request),underlyingError:e.underlyingError};return e.error instanceof v&&(t.httpStatus=nC(e.error,Ke),t.contentType=Hr(e.error,_r),t.upstreamUrl=Hr(e.error,We),t.upstreamServerId=Hr(e.error,Bo),t.metadataUrl=Hr(e.error,Rr),t.providerError=Hr(e.error,br),t.providerErrorDescription=Hr(e.error,vr)),t}n(Gt,"buildBrowserErrorDiagnostic");function co(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(co,"oauthErrorResponse");function sC(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(sC,"readOAuthProtocolHeaders");function iC(e,t){let r=ze("internal_server_error");return co({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:sC(e,t)})}n(iC,"oauthProtocolErrorResponse");function ka(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(ka,"readZodOAuthErrorCode");function aC(e){let t={error:ka(e)},r=vt(e);return r!==void 0&&(t.errorDescription=r),co(t)}n(aC,"oauthZodErrorResponse");function cC(e){let t=Ze(e);if(t===void 0)return;let r=ze(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:uC(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,co(o)}n(cC,"oauthGatewayProblemResponse");function dC(){let t={error:"server_error",status:500,errorDescription:ze("internal_server_error").publicDetail};return co(t)}n(dC,"oauthFallbackErrorResponse");function uC(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(uC,"readOAuthStatus");function Pa(e,t={}){return e instanceof bt?Mf(e):e instanceof R?iC(e,t):e instanceof l.ZodError?aC(e):cC(e)??dC()}n(Pa,"oauthProblemResponse");function Aa(e,t,r){let o=jr(e.url),s=Af(t);if(r instanceof bt)return Mf(r);if(r instanceof R){let a=ze("internal_server_error");return Fe({host:o,kind:lC(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?a.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?a.publicDetail:r.message,code:r.errorCode,diagnostic:Gt({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?a.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof l.ZodError)return Fe({host:o,kind:"invalid_request",detail:vt(r)??"The authorization request was invalid.",developerDetail:vt(r)??"The authorization request was invalid.",code:ka(r),diagnostic:Gt({request:e,requestId:s,code:ka(r),underlyingError:vt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=Ze(r);if(i!==void 0){let a=ze(i);return Fe({host:o,kind:Of(i),detail:a.publicDetail,developerDetail:a.status>=500||!(r instanceof Error)?a.publicDetail:r.message,code:i,diagnostic:Gt({request:e,requestId:s,code:i,underlyingError:a.status>=500||!(r instanceof Error)?a.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:xf(r),status:a.status})}let c=ze("internal_server_error");return Fe({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"server_error",diagnostic:Gt({request:e,requestId:s,code:"server_error",underlyingError:c.publicDetail,error:r}),requestId:s,status:c.status})}n(Aa,"browserOAuthProblemResponse");function Uf(e,t,r){let o=jr(e.url),s=Af(t),i=Ze(r);if(i!==void 0){let a=ze(i);return Fe({host:o,kind:Of(i),detail:a.publicDetail,developerDetail:a.status>=500||!(r instanceof Error)?a.publicDetail:r.message,code:i,diagnostic:Gt({request:e,requestId:s,code:i,underlyingError:a.status>=500||!(r instanceof Error)?a.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:xf(r),status:a.status})}if(r instanceof l.ZodError)return Fe({host:o,kind:"invalid_request",detail:vt(r)??"The authorization request was invalid.",developerDetail:vt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:Gt({request:e,requestId:s,code:"invalid_request",underlyingError:vt(r)??"The authorization request was invalid.",error:r}),requestId:s});let c=ze("internal_server_error");return Fe({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"internal_server_error",diagnostic:Gt({request:e,requestId:s,code:"internal_server_error",underlyingError:c.publicDetail,error:r}),requestId:s,status:c.status})}n(Uf,"browserGatewayProblemResponse");function lC(e){return e==="server_error"?"internal_error":"invalid_request"}n(lC,"readOAuthBrowserErrorKind");function Of(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":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(Of,"readGatewayBrowserErrorKind");function nt(e,t,r){let o={event:t},s=!1;if(r instanceof R)o.oauthError=r.errorCode,o.status=r.status,pe(o,"error",r);else if(r instanceof bt)o.oauthError=r.errorCode,pe(o,"error",r);else if(r instanceof l.ZodError){o.code="invalid_request",pe(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=Ze(r);if(i!==void 0){let c=ze(i);o.code=i,o.status=c.status,c.oauthError!==void 0&&(o.oauthError=c.oauthError),s=c.status>=500||c.oauthError==="server_error",pe(o,"error",r)}else s=!0,pe(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(nt,"logUnexpectedOAuthHandlerError");function Mf(e){let t;try{t=new URL(e.redirectUri)}catch{return co({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(Mf,"downstreamAuthorizeRedirectErrorResponse");function vt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(vt,"formatZodErrorDetail");function pC(e,t){let r={event:"browser_login_callback_failed",code:Ze(t)??"invalid_request"};pe(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(pC,"logBrowserLoginCallbackFailure");function zf(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(zf,"redirectResultResponse");function xs(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":eC,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return zf(e)}n(xs,"authorizeResultResponse");async function qf(e,t){try{return Response.json(ul(e.url,e.headers))}catch(r){return nt(t,"oauth_authorization_server_metadata_failed",r),Pf(e,t,r)}}n(qf,"authorizationServerMetadataHandler");async function Nf(e,t){try{let r=ai(e.params.routePath);return Response.json(ll({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return nt(t,"oauth_authorization_server_metadata_failed",r),Pf(e,t,r)}}n(Nf,"scopedAuthorizationServerMetadataHandler");async function jf(e,t){try{let r=await Bh(await rC(e)),o=r.client_id,s=r.client_name,i=r.redirect_uris.length,c=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:o,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),J(t,{eventType:B.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:o,redirectUriCount:i,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return nt(t,"oauth_register_failed",r),Pa(r)}}n(jf,"registerHandler");async function Df(e,t){try{return xs(await Ca(e,{context:t}))}catch(r){return nt(t,"oauth_authorize_failed",r),Aa(e,t,r)}}n(Df,"authorizeHandler");async function $f(e,t){try{let r=ai(e.params.routePath);return xs(await Ca(e,{operationId:r.operationId,context:t}))}catch(r){return nt(t,"oauth_authorize_scoped_failed",r),Aa(e,t,r)}}n($f,"scopedAuthorizeHandler");async function Lf(e,t){try{let r=await mf(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),xs(r)}catch(r){return pC(t,r),Uf(e,t,r)}}n(Lf,"callbackHandler");async function Hf(e,t){try{return zf(await hf(e))}catch(r){return nt(t,"oauth_dev_login_failed",r),Aa(e,t,r)}}n(Hf,"devLoginHandler");async function Bf(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await ff({request:e,body:e.method==="POST"?await Ea(e):void 0,context:t});return xs(r)}catch(r){return nt(t,"oauth_setup_failed",r),Uf(e,t,r)}}n(Bf,"setupHandler");async function Ff(e,t){try{return Response.json(await kf({body:await Ea(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 nt(t,"oauth_token_failed",r),Pa(r)}}n(Ff,"tokenHandler");async function Gf(e,t){try{return await Ef({body:await Ea(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 nt(t,"oauth_revoke_failed",r),Pa(r)}}n(Gf,"revokeHandler");var Jf="0.0.0",mC=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function uo(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}n(uo,"firstNonBlank");function lo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}n(lo,"clampToCodePoints");function hC(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(hC,"shortHash");function Vf(e,t){let r=[...e];if(r.length<=t)return e;let o=`-${hC(e)}`;return t<=o.length?r.slice(0,t).join(""):`${r.slice(0,t-o.length).join("")}${o}`}n(Vf,"clampNameSegment");function fC(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}n(fC,"sanitizeRegistryNameSegment");var gC=/^\d{1,3}(\.\d{1,3}){3}$/u;function yC(e){let t=new URL(e).hostname.toLowerCase();if(gC.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(yC,"buildRegistryNamespaceFromOrigin");function SC(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(SC,"sanitizeWebsiteUrl");function _C(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&&!mC.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(_C,"sanitizeIcons");function wC(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}n(wC,"localNameFromRoutePath");function Kf(e){return e.includes("{")||e.includes(":")}n(Kf,"isParameterizedRoutePath");var RC=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Wf(e){let t=uo(e)??Jf;return RC.test(t)?Jf:lo(t,255)}n(Wf,"sanitizeRegistryVersion");function Zf(e){let t=Vf(yC(e.origin),150),r=200-t.length-1,o=new Set,s=[];function i(a){let u=Vf(fC(a),r),p=u;for(let h=2;o.has(p);h++){let f=`-${h}`;p=`${[...u].slice(0,r-f.length).join("")}${f}`}return o.add(p),p}n(i,"claimLocalName");function c(a,u){let p=`${t}/${i(a)}`;s.push({name:p,response:{server:{...u,name:p},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}n(c,"pushEntry");for(let a of e.registry.byRoutePath.values()){if(Kf(a.routePath))continue;let u=a.connection,p=u?.serverInfo,h=lo(uo(u?.description,p?.description,u?.displayName,a.operationId)??a.operationId,100),f=uo(p?.title,u?.displayName),y=SC(p?.websiteUrl),S=_C(p?.icons);c(a.operationId,{description:h,...f===void 0?{}:{title:lo(f,100)},version:Wf(p?.version),...y===void 0?{}:{websiteUrl:y},...S===void 0?{}:{icons:S},remotes:[{type:"streamable-http",url:new URL(a.routePath,e.origin).toString()}]})}for(let a of e.registry.standaloneMcpRoutes){if(Kf(a.routePath))continue;let u=a.operationId??wC(a.routePath),p=lo(uo(a.summary,a.description,a.serverName,a.operationId,u)??u,100),h=uo(a.serverName);c(u,{description:p,...h===void 0?{}:{title:lo(h,100)},version:Wf(a.serverVersion),remotes:[{type:"streamable-http",url:new URL(a.routePath,e.origin).toString()}]})}return s}n(Zf,"buildMcpRegistryDirectory");var bC=30,Yf=100;function Ne(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}n(Ne,"registryErrorResponse");function Ua(e){return Zf({registry:Se(),origin:Y(e.url,e.headers)})}n(Ua,"readEntries");function xa(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}n(xa,"decodePathParam");function Xf(e,t){return e.find(r=>r.name===t)}n(Xf,"findEntryByName");function vC(e){let t=e.get("limit");return t===null?{ok:!0,value:bC}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Yf)}}n(vC,"parseLimit");function IC(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(IC,"parseCursor");var CC=/^(\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 TC(e){let t=CC.exec(e);if(!t)return!1;let[,r,o,s,i,c,a]=t,u=new Date(Date.UTC(Number(r),Number(o)-1,Number(s),Number(i),Number(c),Number(a)));return u.getUTCFullYear()===Number(r)&&u.getUTCMonth()===Number(o)-1&&u.getUTCDate()===Number(s)&&u.getUTCHours()===Number(i)&&u.getUTCMinutes()===Number(c)&&u.getUTCSeconds()===Number(a)}n(TC,"isValidRfc3339Timestamp");async function Qf(e,t){let r=new URL(e.url).searchParams,o=vC(r);if(!o.ok)return Ne(400,`Invalid 'limit' parameter: expected a positive integer (max ${Yf}).`);let s=IC(r);if(!s.ok)return Ne(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&&!TC(i))return Ne(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let c=r.get("search")?.toLowerCase(),a=r.get("version"),u=Ua(e).sort((f,y)=>f.name<y.name?-1:f.name>y.name?1:0);c!==void 0&&c!==""&&(u=u.filter(f=>f.name.toLowerCase().includes(c))),a!==null&&a!=="latest"&&(u=u.filter(f=>f.response.server.version===a));let p=u.slice(s.value,s.value+o.value),h=s.value+o.value;return Response.json({servers:p.map(f=>f.response),metadata:{count:p.length,...h<u.length?{nextCursor:String(h)}:{}}})}n(Qf,"listMcpRegistryServersHandler");async function eg(e,t){let r=xa(e.params.serverName);if(!r.ok)return Ne(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=Xf(Ua(e),r.value);return o===void 0?Ne(404,"Server not found"):Response.json({servers:[o.response],metadata:{count:1}})}n(eg,"listMcpRegistryServerVersionsHandler");async function tg(e,t){let r=xa(e.params.serverName);if(!r.ok)return Ne(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=xa(e.params.version);if(!o.ok)return Ne(400,"Invalid version: malformed encoding.");let s=Xf(Ua(e),r.value);return s===void 0?Ne(404,"Server not found"):o.value!=="latest"&&o.value!==s.response.server.version?Ne(404,"Server or version not found"):Response.json(s.response)}n(tg,"getMcpRegistryServerVersionHandler");function Us(e,t){return(r,o)=>Ne(e,t)}n(Us,"createWriteNotSupportedHandler");async function rg(e,t){return Ne(404,"Not found")}n(rg,"mcpRegistryNotFoundHandler");var ng=Us(501,"Publishing is not supported by this registry"),og=Us(501,"Updates are not supported by this registry"),sg=Us(501,"Deletion is not supported by this registry"),Oa=Us(403,"You do not have publish or edit permissions for this server");function ig(e){return $`<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(ig,"renderBrowserResult");var kC="text/html; charset=utf-8";function EC(e){return Nr({title:e.title,iconHref:Hi(e.host),styles:qr,headerIcon:Is("success"),heading:e.title,subhead:$`<p class="card__subtitle">${e.detail}</p>`,body:ig({steps:Mr(e.steps.map(t=>$`<li>${t}</li>`))}),footer:""})}n(EC,"browserResultHtml");function PC(e,t=200){return new Response(zr(e),{status:t,headers:{"content-type":kC,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(PC,"browserResultResponse");function ag(e){return PC(EC(e))}n(ag,"browserConnectionSuccessResponse");function Os(e,t,r={}){let o=Ju(t);return Fe({host:e,kind:AC(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(Os,"browserConnectionFailureResponse");function AC(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(AC,"readCallbackFailureBrowserErrorKind");var xC={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},cg=Symbol("upstream-request");function po(e,t){Object.defineProperty(e,cg,{configurable:!0,value:t})}n(po,"setUpstreamRequestContext");function UC(e){let t=e[cg];if(!t)throw new ye("Upstream request context has not been set");return t}n(UC,"readUpstreamRequestContext");function OC(e,t){return t.some(r=>r===e)}n(OC,"requestContextMatchesKind");function MC(e){return typeof e=="string"?[e]:e}n(MC,"toExpectedKinds");function mo(e,t){let r=UC(e),o=MC(t);if(!OC(r.kind,o)){let s=xC[o[0]];throw new ye(`${s} request context has not been set`)}return r}n(mo,"requireUpstreamRequestContext");function It(e){if(typeof e=="string"&&e.length!==0)return e}n(It,"readOptionalQueryString");function zC(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new ye(`Validated path parameter ${t} is missing`);return qC(r,t)}n(zC,"requirePathString");function qC(e,t){try{return decodeURIComponent(e)}catch(r){throw new v({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[C]:"invalid_request"}},{cause:r})}}n(qC,"decodePathString");function NC(e){let t=It(e);return t?Jo.parse(t):void 0}n(NC,"readOptionalOperationId");function jC(e){let t=Se().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new v({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[C]:"unknown_upstream_server"}})}n(jC,"readRegisteredAuthProfileId");function DC(e){let t=NC(e);if(!t)throw new v({message:"operationId query parameter is required.",extensionMembers:{[C]:"invalid_request"}});return t}n(DC,"readRequiredOperationId");async function $C(e,t){let r=bs(t,DC(e.query.operationId));if(r.authMode==="id-jag")throw new v({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[C]:"invalid_request"}});let o=e.query.redirect==="true",s=It(e.query.browserTicket);if(e.user){if(s)throw new v({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[C]:"invalid_request"}});let a=Lt(e.user,e.url),u={kind:"connect",...Or(r,a.subjectId),redirect:o},p=Zu(It(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!s)throw new v({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[C]:"authentication_required"}});let i=await lm(s);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.operationId!==r.operationId)throw new v({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[C]:"oauth_callback_mismatch"}});await pm(i);let c=Vo(i);switch(r.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new v({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[C]:"oauth_callback_mismatch"}});let a={kind:"connect",...r,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(a.returnTo=i.returnTo),a}case"user-oauth":{if(c.mode!=="user")throw new v({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[C]:"oauth_callback_mismatch"}});let a={kind:"connect",...r,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(a.returnTo=i.returnTo),a}}}n($C,"resolveConnectContext");async function LC(e,t,r){let o=Wu.parse(zC(e,"connection"));switch(r){case"connect":po(e,await $C(e,o));return;case"callback":{let s=It(e.query.error);if(s){let a={kind:"callback_provider_error",upstreamServerId:o,error:s},u=It(e.query.error_description);u!==void 0&&(a.errorDescription=u),po(e,a);return}let i=It(e.query.code),c=It(e.query.state);if(i&&c){let a=It(e.query.iss);po(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:c,...a===void 0?{}:{iss:a}});return}po(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":po(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:jC(o)});return}}n(LC,"resolveUpstreamRequestInbound");async function HC(e,t,r){try{await LC(e,t,r);return}catch(o){let s=o instanceof v?o.extensionMembers?.[C]:void 0,i=o instanceof Error?o.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return jt.badRequest(e,t,{code:s,detail:i});case"authentication_required":return jt.unauthorized(e,t,{code:s,detail:i});default:throw o}}}n(HC,"applyUpstreamRequestContext");function Ms(e,t){return n(async(o,s)=>{let i=await HC(o,s,e);return i||t(o,s)},"wrapped")}n(Ms,"withUpstreamRequestContext");var BC=["callback_authorization_code","callback_provider_error","callback_invalid"];function Ma(e){try{return new URL(e.url).pathname}catch{return}}n(Ma,"readBrowserRequestPath");function FC(e){return"cause"in e?e.cause:void 0}n(FC,"readErrorCause");function GC(e){return e.stack?.split(`
29
- `).slice(1,4).map(t=>t.trim()).join(" | ")}n(GC,"readFirstStackFrame");function dg(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=GC(r))}n(dg,"addErrorAttributes");function za(e){if(!(e instanceof v))return;let t=e.extensionMembers?.[C];return Fo(t)?t:void 0}n(za,"readRuntimeGatewayCode");function ho(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(ho,"readRuntimeErrorExtensionString");function JC(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(JC,"readRuntimeErrorExtensionNumber");function VC(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"),J(t,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),Os(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:Ma(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"),Os(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:Ma(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n(VC,"requireAuthorizationCallbackRequest");function KC(e,t){J(e,{eventType:B.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(KC,"emitCallbackReceivedAnalyticsEvent");function WC(e,t){J(e,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(WC,"emitTokenExchangeSucceededAnalyticsEvent");function ZC(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return ag({host:jr(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(ZC,"buildSuccessfulCallbackResponse");function YC(e){let t={detail:e instanceof Error?e.message:void 0};return dg(t,"error",e),e instanceof Error&&dg(t,"cause",FC(e)),t}n(YC,"buildTokenExchangeFailureAttributes");function XC(e){J(e.context,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:za(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:YC(e.error)})}n(XC,"emitTokenExchangeFailedAnalyticsEvent");function QC(e){let t=e.error,r=za(t),o=Gu(r)?r:"upstream_token_exchange_failed",s={code:o,requestId:e.context.requestId,routePath:Ma(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof v?{httpStatus:JC(t,Ke),contentType:ho(t,_r),upstreamUrl:ho(t,We),metadataUrl:ho(t,Rr),providerError:ho(t,br),providerErrorDescription:ho(t,vr)}:{}};return Os(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:eT(t)})}n(QC,"tokenExchangeFailureResponse");function eT(e){if(!(e instanceof v))return;let t=e.extensionMembers?.[wr];return typeof t=="string"?t:void 0}n(eT,"readUpstreamHtmlError");async function qa(e,t){let r=mo(e,BC),o=jr(e.url),s=VC(e,t,r,o);if(s instanceof Response)return s;KC(t,s);try{let i=await Ym({request:e,callbackRequest:s});return WC(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,operationId:i.operationId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),ZC(e,i)}catch(i){let c={event:"upstream_oauth_token_exchange_failed",code:za(i)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return pe(c,"error",i),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),XC({context:t,callbackRequest:s,error:i}),QC({request:e,context:t,host:o,callbackRequest:s,error:i})}}n(qa,"callbackHandler");function tT(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(tT,"clientMetadataProblemDetail");async function ug(e,t){let r=mo(e,"connect"),o=await Zm({request:e,connectRequest:r});if(J(t,{eventType:B.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let s=await Ss({requestUrl:e.url,requestHeaders:e.headers,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(s,{status:428})}n(ug,"connectHandler");async function lg(e,t){let r=mo(e,"client_metadata");try{let o=Y(e.url,e.headers),s=wm(o,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(o){if(!(o instanceof K))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"),jt.notFound(e,t,{code:"not_found",detail:tT(o)})}}n(lg,"oauthClientMetadataHandler");function rT(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(rT,"resolveInternalRoutePath");var nT={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function oT(){return new Response(null,{status:204,headers:nT})}n(oT,"buildWellKnownPreflightResponse");function sT(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(sT,"withWellKnownCorsHeaders");function Jt(e){return async(t,r)=>t.method==="OPTIONS"?oT():sT(await e(t,r))}n(Jt,"wrapWellKnownHandler");var pg=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Jt(qf),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:Jt(Nf),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:Jt(pl),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:jf},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Df},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:$f},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Lf},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Hf},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Bf},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Ff},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Gf},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ms("client_metadata",lg)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ms("connect",ug)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ms("callback",qa)}],iT=pg.filter(e=>!e.routeName.startsWith("upstream_")),aT=pg.filter(e=>e.routeName.startsWith("upstream_"));function cT(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:Jt(Qf),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:Jt(eg),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:Jt(tg),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:ng},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:og},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:sg},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Oa},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Oa},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:Jt(rg),corsPolicy:"anything-goes"}]}n(cT,"buildMcpRegistryInternalRoutes");function dT(e){let t=tl({routes:e.routes,policies:e.policies,gateway:e.gateway});return rl(t),t}n(dT,"initializeMcpGatewayConnectionRegistry");function uT(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(uT,"hasDownstreamOAuthRoutes");function lT(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(lT,"hasIdJagDownstreamOAuth");function pT(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 ye("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 K(`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(pT,"readSingletonDownstreamOAuthConfig");function mT(e,t,r){let o=String(t.params.routePath??""),s=e.byRoutePath.get(al(o));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?Go(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(mT,"readScopedDownstreamOAuthConfig");function hT(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(hT,"routeUsesScopedOAuthConfig");function Na(e,t,r){return async(o,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let u=await r(o,s);if(u instanceof Response)return u;u&&Hu(s,u)}let i=o.method==="OPTIONS",c=Date.now();i||s.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let a=await t(o,s);return i||s.log.info({event:`${e}_responded`,status:a.status,durationMs:Date.now()-c},`MCP gateway: ${e} responded`),a}}n(Na,"wrapInternalHandler");function ja(e,t,r,o){e.addPluginRoute({path:rT(t,r),methods:t.methods,handler:o,processors:[Va],corsPolicy:t.corsPolicy??"none"})}n(ja,"addInternalRoute");function mg(e,t){let r=dT(t);if(r.gateway.registry.enabled){Le("plugin.mcp-gateway.registry");for(let a of cT(r.gateway.registry))ja(e,a,r.gateway,Na(a.routeName,a.handler))}let o=uT(r),s=r.connectionsById.size>0,i,c=n(()=>(i===void 0&&(i=pT(r)),i),"readSingletonOAuthConfig");if(o){Le("plugin.mcp-gateway.downstream-oauth"),lT(r)&&Le("plugin.mcp-gateway.downstream-oauth.id-jag");for(let a of iT){let u=hT(a)?(p,h)=>mT(r,p,h):c;ja(e,a,r.gateway,Na(a.routeName,a.handler,u))}}if(s){Le("plugin.mcp-gateway.upstream-auth");for(let a of r.connectionsById.values())Le(`plugin.mcp-gateway.upstream-auth.${a.authMode}`);for(let a of aT)ja(e,a,r.gateway,Na(a.routeName,a.handler))}}n(mg,"registerMcpGatewayInternalRoutes");var Da=class extends Ga{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),Le("plugin.mcp-gateway"),this.#e=Bu(t)}registerRoutes(t){let r=t.parsedRouteData;r&&mg(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var fT=new TextDecoder;function gT(e){if(e)try{return JSON.parse(fT.decode(e))}catch{return}}n(gT,"readBodyJson");function ot(e){return e&&typeof e=="object"?e:void 0}n(ot,"readRecord");function fo(e,t){let r=ot(e)?.[t];return typeof r=="string"?r:void 0}n(fo,"readStringProperty");function fg(e,t){let r=ot(e)?.[t];return typeof r=="number"?r:void 0}n(fg,"readNumberProperty");function hg(e,t){return fg(e,"code")??(t.status>=400?t.status:void 0)}n(hg,"readErrorCode");function gg(e){return Array.isArray(e)?e.map(gg).find(t=>t?.method):ot(e)}n(gg,"readJsonRpcMessage");function yg(e){let t=gg(gT(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:fo(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:fo(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=fo(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}n(yg,"buildBaseCapabilityInput");function Sg(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(Sg,"isCapabilityListMethod");function yT(e,t,r){let i=ot(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(yT,"readItemCount");async function ST(e){try{return await e.clone().json()}catch{return}}n(ST,"readResponseJson");function _g(e){let t=yg(e);return!t||Sg(t.mcpMethod)?null:{eventType:B.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(_g,"buildCapabilityInvokedAnalyticsInput");async function wg(e,t){let r=yg(e);if(!r)return null;let o=ot(await ST(t)),s=ot(o?.error),i=ot(s?.data),c=o?.result,a=r.mcpMethod==="tools/call"&&ot(c)?.isError===!0;if(ot(i?.connectRequired))return{eventType:B.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:fg(s,"code"),mcpErrorType:fo(s,"message")};if(Sg(r.mcpMethod)){let u=t.status>=400?void 0:yT(r.mcpMethod,r.capabilityType,c);return{eventType:B.MCP_CAPABILITY_LISTED,outcome:t.status>=400||s?"failure":"success",...r,httpStatusCode:t.status,...t.status>=400||s?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorCode:hg(s,t)}:{},...u===void 0?{}:{attributes:{itemCount:u}}}}return t.status>=400||s?{eventType:B.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:hg(s,t),mcpErrorType:fo(s,"message")}:{eventType:B.MCP_CAPABILITY_COMPLETED,outcome:a?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:a,applicationError:a}}n(wg,"buildCapabilityFinalAnalyticsInput");var _T={Allow:"POST"};async function wT(e){try{return await e.clone().arrayBuffer()}catch{return}}n(wT,"readRequestBody");function Rg(e){try{let t=nl(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(Rg,"readRouteAnalyticsFields");function bg(e){return fl(e.user,e.url,e.headers)?.subjectId}n(bg,"readRequestSubjectId");function RT(e){let t=_g(e.requestBody);t&&J(e.context,{...t,...Rg(e.context),httpMethod:e.request.method,subjectId:bg(e.request),transport:"http"})}n(RT,"emitCapabilityInvokedAnalytics");async function bT(e){let t=await wg(e.requestBody,e.response);t&&J(e.context,{...t,...Rg(e.context),httpMethod:e.request.method,subjectId:bg(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(bT,"emitCapabilityFinalAnalytics");async function vT(e,t){if(Le("handler.mcp-gateway-proxy"),e.method==="GET")return jt.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},_T);let r=Date.now(),o=await wT(e);RT({context:t,request:e,requestBody:o});let s=await Du(e,t);return await bT({context:t,request:e,requestBody:o,response:s,startedAt:r}),s}n(vT,"McpProxyHandler");export{Mg as McpAuth0OAuthInboundPolicy,Di as McpCapabilityFilterInboundPolicy,Ig as McpClerkOAuthInboundPolicy,Cg as McpCognitoOAuthInboundPolicy,Tg as McpEntraOAuthInboundPolicy,Da as McpGatewayPlugin,kg as McpGoogleOAuthInboundPolicy,Eg as McpKeycloakOAuthInboundPolicy,Pg as McpLogtoOAuthInboundPolicy,zg as McpOAuthInboundPolicy,Ag as McpOktaOAuthInboundPolicy,xg as McpOneLoginOAuthInboundPolicy,Ug as McpPingOAuthInboundPolicy,vT as McpProxyHandler,ca as McpTokenExchangeInboundPolicy,Og as McpWorkosOAuthInboundPolicy,$p as claimsCapabilityResolver};
43
+ </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(Vr,"renderShell");function ni(e){return V`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?ag:cg}</div>`}n(ni,"renderStatusIcon");var tT="text/html; charset=utf-8";function Ut(e){try{return new URL(e).host}catch{return""}}n(Ut,"safeHostFromUrl");function Fe(e){let t=e.kind??"authorization_failed",r=nT(t),o=rT(e),s=e.title??r.title;return new Response(Fr(Vr({title:s,iconHref:"",styles:Gr,headerIcon:ni(t==="access_denied"?"neutral":"error"),heading:s,subhead:V`<p class="card__subtitle">${e.detail}</p>`,body:ig({steps:Jr(r.steps.map(i=>V`<li>${i}</li>`)),action:iT(e.action),reference:aT(o),diagnostics:cT({diagnostic:o,detail:e.detail}),upstreamResponse:dT(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":tT,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Fe,"browserErrorPageResponse");function rT(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??oT(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??sT(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(rT,"buildBrowserErrorDiagnostic");function nT(e){switch(e){case"session_expired":return{title:"Authorization expired",steps:["Return to your MCP client and reconnect.","Expired authorization requests cannot be resumed, so start a new connection instead of reloading this page."]};case"access_denied":return{title:"Authorization canceled",steps:["Return to your MCP client.","If you want to grant access, start the connection again and approve the request."]};case"configuration_error":return{title:"Configuration needs attention",steps:["Contact your workspace admin and share the reference below.","The gateway or upstream configuration must be fixed before retrying."]};case"connection_failed":return{title:"Connection failed",steps:["Return to your MCP client and reconnect this upstream.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"invalid_request":return{title:"Authorization request invalid",steps:["Return to your MCP client and try connecting again.","If this keeps happening, the client request may need to be fixed."]};case"admin_required":return{title:"Admin setup required",steps:["Contact your workspace admin and share the reference below.","This connection cannot be completed until setup is finished."]};case"internal_error":return{title:"Gateway error",steps:["Try again later from your MCP client.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"authorization_failed":return{title:"Authorization failed",steps:["Return to your MCP client and start authorization again.","If this keeps happening, contact your gateway administrator and share the reference below."]}}}n(nT,"readBrowserErrorPagePresentation");function oT(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(oT,"readBrowserErrorStage");function sT(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}n(sT,"readBrowserErrorSuggestedFix");function iT(e){return e===void 0?Je:V`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(iT,"renderAction");function oi(e){if(e.value===void 0||e.value==="")return Je;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return V`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}n(oi,"renderRow");function Ne(e){return oi({label:e.label,value:e.value===void 0?void 0:V`<code>${e.value}</code>`})}n(Ne,"renderCodeRow");function aT(e){return Jr([oi({label:"Error code",value:V`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Ne({label:"Request ID",value:e.requestId}),Ne({label:"Time",value:e.timestamp})])}n(aT,"renderReference");function cT(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return Jr([oi({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),oi({label:"Reason",value:r,block:!0}),Ne({label:"Stage",value:t.stage}),Ne({label:"Gateway route",value:t.routePath}),Ne({label:"Operation ID",value:t.operationId}),Ne({label:"Upstream",value:t.upstreamServerId}),Ne({label:"Auth profile",value:t.authProfileId}),Ne({label:"Upstream URL",value:t.upstreamUrl}),Ne({label:"Metadata URL",value:t.metadataUrl}),Ne({label:"HTTP status",value:t.httpStatus}),Ne({label:"Content type",value:t.contentType}),Ne({label:"Provider error",value:t.providerError}),Ne({label:"Provider error description",value:t.providerErrorDescription})])}n(cT,"renderDiagnostics");function dT(e){return e===void 0?Je:V`<details class="provider-response"><summary class="provider-response__summary">Show the provider's response</summary><iframe title="Upstream HTML error response" sandbox class="provider-response__frame" srcdoc="${e}"></iframe></details>`}n(dT,"renderUpstreamHtml");var dg="application/json",uT="application/x-www-form-urlencoded";function si(e,t){return new T({message:e,extensionMembers:{[E]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(si,"invalidRequestError");function lT(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(lT,"normalizeContentType");function pT(e,t){return e===t?!0:t===dg&&e.endsWith("+json")}n(pT,"contentTypeMatches");function mT(e,t){if(!t||t.length===0)return;let r=lT(e.headers.get("content-type"));if(!t.some(o=>pT(r,o)))throw si(`Request body must be ${t.join(" or ")}.`)}n(mT,"assertExpectedContentType");function hT(e,t,r){let o=e.headers.get("content-length");if(!o)return;let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>t)throw si(`${r} exceeded the maximum allowed size.`)}n(hT,"assertContentLengthWithinLimit");async function ug(e,t){let r=t.label??"Request body";mT(e,t.expectedContentTypes),hT(e,t.maxBytes,r);let o=await Vs(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>si(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ug,"readBoundedTextBody");async function lg(e,t){let r=await ug(e,{...t,expectedContentTypes:[dg]});try{return JSON.parse(r)}catch(o){throw si("Request body must be valid JSON.",o)}}n(lg,"readBoundedJsonBody");async function pg(e,t){let r=await ug(e,{...t,expectedContentTypes:[uT]});return new URLSearchParams(r)}n(pg,"readBoundedFormUrlEncodedBody");import{errors as hg,jwtVerify as fg,SignJWT as ac}from"jose";import{base64url as fT}from"jose";var gT="mcp-browser-login-pkce:",yT=new TextEncoder;async function ST(e){return crypto.subtle.importKey("raw",he(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}n(ST,"importHmacKey");async function ic(e){let t=await ST(e.signingKey),r=yT.encode(`${gT}${e.stateId}`),o=await crypto.subtle.sign("HMAC",t,he(r));return kr.parse(fT.encode(new Uint8Array(o)))}n(ic,"deriveBrowserLoginPkceVerifier");async function mg(e){let t=await ic(e),r=await vs(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Er}}n(mg,"deriveBrowserLoginPkceParams");var _T={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},v=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=_T[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var wT=300,RT=p.object({purpose:p.literal("gateway_browser_login"),transactionId:Mi,stateId:Ss,binding:vo,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),bT=p.object({purpose:p.literal("gateway_browser_login_return"),stateId:Ss,binding:vo,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),vT=p.discriminatedUnion("purpose",[RT,bT]),CT=p.object({purpose:p.literal("gateway_authorization_setup"),transactionId:Mi,stateId:Ss,exp:p.number().int().positive(),iat:p.number().int().positive().optional()});async function Kr(){return tt({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-login"),"derive")})}n(Kr,"getBrowserLoginKey");async function gg(){return tt({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"authorization-csrf"),"derive")})}n(gg,"getCsrfKey");function yg(e){return{now:e.now??new Date,ttlSeconds:cc()}}n(yg,"readPendingTransactionDependencies");function cc(){return ve().browserLogin.stateTtlSeconds}n(cc,"readBrowserLoginStateTtlSeconds");function IT(e){let t=me();return qe(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(IT,"isLoopbackDevLoginUrl");async function Sg(e){let t=ve().browserLogin,r=me(),o=new URL(bt("url")),s=new URL(r.actionPath("/oauth/callback"),qr(e.requestUrl,e.requestHeaders));if(IT(o))return o.searchParams.set("redirect_uri",s.toString()),o.searchParams.set("state",e.state),o;if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",bt("clientId")),o.searchParams.set("redirect_uri",s.toString()),o.searchParams.set("scope",t.scope),o.searchParams.set("state",e.state),o.searchParams.set("nonce",e.nonce),t.audience&&o.searchParams.set("audience",t.audience),t.pkce===Er){let i=await mg({stateId:e.stateId,signingKey:await Kr()});o.searchParams.set("code_challenge",i.codeChallenge),o.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return o}n(Sg,"buildBrowserLoginUrl");function TT(e,t){return e.subjectId===t.subjectId}n(TT,"principalsMatch");function _g(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(_g,"toPendingPrincipal");function wg(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:J(e.now),expiresAt:J(st(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw M("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:_g(e.principal)}}n(wg,"createTransactionRecord");async function Rg(e){let{id:t,...r}=e.record,o=await H().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw M("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new v("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new v("invalid_request","redirect_uri is not registered for the client.")}}n(Rg,"startPendingTransaction");async function ET(e){return new ac({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Kr())}n(ET,"signBrowserLoginState");async function bg(e){return new ac({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:ws()}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await gg())}n(bg,"signCsrfToken");async function dc(e){try{let{payload:t}=await fg(e,await Kr(),{algorithms:[xe],issuer:Te,audience:Pe}),r=vT.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof hg.JWTExpired?M("oauth_state_expired","Browser login state has expired.",t):M("oauth_state_invalid","Browser login state could not be verified.",t)}}n(dc,"verifyAnyBrowserLoginStateToken");async function kT(e){let t=await dc(e);if(t.kind!=="authorization")throw M("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding}}n(kT,"verifyBrowserLoginStateToken");async function ii(e){try{let{payload:t}=await fg(e,await gg(),{algorithms:[xe],issuer:Te,audience:Pe});return{transactionId:CT.parse(t).transactionId}}catch(t){throw t instanceof hg.JWTExpired?M("oauth_state_expired","Authorization setup state has expired.",t):M("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(ii,"verifyCsrfToken");function uc(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(uc,"pendingStateErrorCode");function AT(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(AT,"toPendingAuthorizationGetResult");function PT(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(PT,"toPendingAuthorizationAdvanceResult");function lc(e){return e==="principal_mismatch"?"oauth_callback_mismatch":uc(e==="consumed_already"?"consumed_already":e)}n(lc,"setupDecisionErrorCode");async function vg(e){let t=e.now??new Date,r=await ii(e.csrfToken),o=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(o.kind!=="marked")throw M(lc(o.kind),"Authorization setup state is invalid, expired, or already used.");return Cg({kind:"available",record:o.transaction})}n(vg,"markSetupApproved");function Cg(e){if(e.kind!=="available")throw M(uc(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Cg,"requireAwaitingSetup");function xT(e){if(!TT(e.currentBrowserPrincipal,e.transaction.principal))throw M("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(xT,"requireCurrentPrincipalMatches");async function Ig(e){let t=e.now??new Date,r=cc(),o=qi(),s=ws(),i=await Io({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await ET({transactionId:o,stateId:s,binding:i.claim,ttlSeconds:r}),c=wg({id:o,transaction:e.transaction,currentStateHash:await oe(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw M("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await Rg({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw M("oauth_state_invalid","Authorization transaction did not start in login phase.");let l=await Sg({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:l,browserBindingCookie:i.setCookie}}n(Ig,"startAwaitingLogin");async function Tg(e){let t=cc(),r=ws(),o=await Io({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new ac({purpose:"gateway_browser_login_return",stateId:r,binding:o.claim}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Kr());return{browserLoginUrl:await Sg({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:o.setCookie}}n(Tg,"startReturnToBrowserLogin");async function Eg(e){let{now:t,ttlSeconds:r}=yg(e),o=qi(),s=await bg({transactionId:o,ttlSeconds:r}),i=wg({id:o,transaction:e.transaction,currentStateHash:await oe(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await Rg({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}n(Eg,"startAwaitingSetup");async function kg(e){let{now:t,ttlSeconds:r}=yg(e),o=await kT(e.browserLoginStateToken),s=await bg({transactionId:o.transactionId,ttlSeconds:r}),i=PT(await H().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await oe(e.browserLoginStateToken),nextStateHash:await oe(s),nextPhase:"awaiting_setup",principal:_g(e.principal),now:J(t)}));if(i.kind!=="advanced")throw M(uc(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw M("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}n(kg,"completeLogin");async function Ag(e){let t=await pc(e);return xT({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Ag,"getSetup");async function pc(e){let t=e.now??new Date,r=await ii(e.csrfToken);return Cg(AT(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await oe(e.csrfToken),now:J(t)})))}n(pc,"getSetupTransaction");async function OT(e){let t=await ii(e.csrfToken),r=at(),o=J(st(e.now,wT)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await oe(r),authorizationCodeExpiresAt:o,grantId:bp(),now:J(e.now)});if(s.kind!=="approved")throw M(s.kind==="cancelled"?"oauth_state_invalid":lc(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),i}n(OT,"createAuthorizationCodeRedirectWithDecision");async function UT(e){let t=await ii(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw M(r.kind==="approved"?"oauth_state_invalid":lc(r.kind),"Authorization setup state is invalid, expired, or already used.");return MT({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(UT,"createCancelRedirectWithDecision");function MT(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(MT,"buildClientCancelRedirect");async function Pg(e){let t=e.now??new Date;return OT({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Pg,"approve");async function xg(e){let t=e.now??new Date;return UT({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(xg,"cancel");import{createRemoteJWKSet as qT,errors as Wr,jwtVerify as Og,SignJWT as zT}from"jose";var NT="zuplo_mcp_session",jT=p.object({purpose:p.literal("gateway_browser_session"),sub:to,browserLoginOrigin:p.string().min(1),roles:p.array(p.string().min(1)).optional(),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),DT=p.object({id_token:p.string().min(1),token_type:p.string().min(1).optional(),expires_in:p.number().optional(),access_token:p.string().min(1).optional(),refresh_token:p.string().min(1).optional(),scope:p.string().min(1).optional()}),$T=p.object({error:p.string().min(1).optional(),error_description:p.string().min(1).optional(),error_uri:p.string().min(1).optional()}),LT=p.object({sub:to,nonce:p.string().min(1)}).catchall(p.unknown()),mc;async function Ug(){return tt({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-session"),"derive")})}n(Ug,"getBrowserSessionKey");function fc(e,t){let r=Fs(e,t);return{name:ja(NT,r),secure:r}}n(fc,"browserSessionCookieName");function hc(e,t){let{name:r,secure:o}=fc(e,t);return Co({name:r,value:"",maxAgeSeconds:0,secure:o})}n(hc,"buildBrowserSessionEvictionCookie");function HT(e){let{name:t,secure:r}=fc(e.requestUrl,e.requestHeaders);return Co({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}n(HT,"serializeSessionCookie");function Mg(){return new URL(bt("url")).origin}n(Mg,"readBrowserLoginOrigin");function BT(e){let t=$T.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}n(BT,"readIdpErrorFields");function JT(e){return e instanceof Wr.JWTExpired?"expired":e instanceof Wr.JWTClaimValidationFailed?"claim":e instanceof Wr.JWSSignatureVerificationFailed?"signature":e instanceof Wr.JWKSNoMatchingKey?"jwks_no_match":e instanceof Wr.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(JT,"readJwtFailureKind");function FT(e){return e instanceof Error&&"cause"in e?e.cause:e}n(FT,"readErrorCause");function GT(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(GT,"readRuntimeGatewayCode");function VT(){if(!mc){let e=ve();mc=qT(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return mc}n(VT,"readFederatedJwks");function qg(e){if(!e.user)throw M("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Yt(e.user,e.url)}n(qg,"resolveCurrentRequestPrincipal");async function Zr(e,t={}){let r=Da(e.headers.get("cookie")).get(fc(e.url,e.headers).name);if(!r)return{};try{let{payload:o}=await Og(r,await Ug(),{algorithms:[xe],issuer:Te,audience:Pe}),s=jT.parse(o);if(s.browserLoginOrigin!==Mg())return{evictCookie:hc(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(o){return o instanceof Wr.JWTExpired?{evictCookie:hc(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:hc(e.url,e.headers)})}}n(Zr,"readBrowserSession");async function ko(e){let t=ve().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:Mg()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new zT(r).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Ug());return HT({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(ko,"createBrowserSessionCookie");async function KT(e){let t=ve(),r=bt("tokenUrl"),o=bt("clientId"),s=bt("clientSecret"),i=new URL(me().actionPath("/oauth/callback"),qr(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:o,client_secret:s});if(t.browserLogin.pkce===Er){let c=await ic({stateId:e.stateId,signingKey:await Kr()});a.set("code_verifier",c)}try{let{response:c,json:d}=await Ks(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let f=BT(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ce(r),idpStatus:c.status,...f},"Federated browser login token exchange returned non-2xx from the identity provider"),M({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${f.idpError?` idp_error=${f.idpError}`:""}${f.idpErrorDescription?` idp_error_description=${f.idpErrorDescription}`:""})`)})}let l=DT.parse(d),m;try{({payload:m}=await Og(l.id_token,VT(),{issuer:t.oidc.issuer,audience:o}))}catch(f){let R={};throw Ce(R,"error",f),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:JT(f),idpHost:ce(r),expectedIssuer:t.oidc.issuer,...R},"Federated id_token failed jose verification"),f}if(m.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ce(r),nonceMissingFromIdToken:m.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),M("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=LT.parse(m);return{principal:Yt({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:l.id_token,tokenType:oo,expiresAt:typeof m.exp=="number"?J(new Date(m.exp*1e3)):void 0}}}catch(c){let d=ot(c)??GT(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:M("browser_login_verification_failed","Federated browser login callback could not be verified.",FT(c))}}n(KT,"exchangeFederatedAuthorizationCode");async function gc(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return KT({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await Zr(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw M("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(gc,"resolveBrowserLoginCallbackIdentity");var WT=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function ZT(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(ZT,"readScheme");function YT(e){return e.protocol==="https:"}n(YT,"isSpecCompliantRedirectUri");function XT(e){let t=ZT(e);return t.length>0&&t!=="http"&&t!=="https"&&!WT.has(t)}n(XT,"isNativeAppCustomSchemeRedirectUri");var Ng=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>YT(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>qe(e),"accepts"),matches:n((e,t)=>qe(e)&&qe(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>XT(e),"accepts")}];function jg(e){let t=Ng.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(jg,"evaluateBuiltInRedirectUriCompatibility");function zg(e){try{return new URL(e)}catch{return}}n(zg,"parseUrl");function Dg(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=zg(e.registeredRedirectUri),r=zg(e.requestedRedirectUri);return t===void 0||r===void 0?!1:Ng.some(o=>o.matches?.(t,r))}n(Dg,"redirectUriMatchesBuiltInCompatibility");var QT=1e4,eE=5*1024,tE=0,rE=2160*60*60,$g=["authorization_code","refresh_token",gs,vt],nE=["authorization_code","refresh_token"],Lg=[_p],oE=["code"],sE=p.object({client_name:p.string().min(1).optional(),redirect_uris:p.array(p.string().min(1)).min(1),grant_types:p.array(p.enum($g)).min(1).max($g.length).optional(),authorization_grant_profiles_supported:p.array(p.enum(Lg)).min(1).max(Lg.length).optional(),response_types:p.array(p.enum(oE)).min(1).max(1).optional(),scope:p.literal(ue).optional(),token_endpoint_auth_method:Rp.optional(),jwks_uri:p.string().min(1).optional()});function iE(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&qe(t))&&t.pathname!=="/"}catch{return!1}}n(iE,"isCimdClientIdCandidate");function Hg(e,t){throw new v("invalid_client",Pp({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Hg,"invalidCimdClientError");function Yr(e,t="invalid_request"){if(aE(e))throw new v(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new v(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new v(t,"redirect_uris must not include credentials or fragments.");if(jg({url:r}).kind==="rejected")throw new v(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Yr,"assertValidRedirectUri");function aE(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(aE,"hasForbiddenRawRedirectUriCharacter");async function cE(e){let{response:t,json:r}=await Jh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:tE,maxResponseBytes:eE,timeoutMs:QT});if(!t.ok)throw M("invalid_request","CIMD metadata could not be fetched.");let o=_s(r);for(let s of o.redirect_uris)Yr(s,"invalid_request");if(o.jwks_uri!==void 0&&io(o.jwks_uri),o.client_id!==e.clientId)throw M("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(cE,"fetchCimdMetadata");async function dE(e){let t=Rs(e),r=await cE({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(dE,"resolveCimdClient");async function ai(e,t){let r=it.parse(e);if(iE(r)){ve().gateway.downstreamCimdEnabled||Hg(r);try{return await dE(r)}catch(s){Hg(r,s)}}let o=await H().readClient({clientId:r});if(o.kind==="found"){let s=o.client,i=Op(s.clientId),a=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",c=s.jwksUri??i;if(a==="private_key_jwt"&&c===void 0)throw new v("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=_s({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),l={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(l.hashedClientSecret=s.hashedClientSecret),l}throw new v("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(ai,"resolveClient");function Bg(e,t){if(!e.metadata.redirect_uris.some(r=>Dg({registeredRedirectUri:r,requestedRedirectUri:t})))throw M("invalid_request","redirect_uri is not registered for the client.")}n(Bg,"assertRedirectRegistered");function uE(e){return e===void 0?[...nE]:Array.from(new Set(e))}n(uE,"normalizeGrantTypes");function lE(e){try{io(e)}catch(t){throw new v("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}n(lE,"assertValidDcrJwksUri");function pE(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?it.parse(xp({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):it.parse(`dcr:${crypto.randomUUID()}`)}n(pE,"createDcrClientId");function Xr(e){if(e===void 0||e===ue)return ue;throw new v("invalid_request",`Only the ${ue} scope is supported.`)}n(Xr,"assertSupportedOAuthScope");function tr(e,t,r){let o;try{o=new URL(t)}catch{throw new v("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new v("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!qe(o))throw new v("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ne(e,r),i=yp(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new v("invalid_target","resource must match a published MCP route.");return a}n(tr,"resolveResource");async function Jg(e){let t;try{t=sE.parse(e)}catch(f){if(f instanceof p.ZodError){let R=f.issues.some(S=>S.path[0]==="redirect_uris");throw new v(R?"invalid_redirect_uri":"invalid_client_metadata",f.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:f})}throw f}for(let f of t.redirect_uris)Yr(f,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new v("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&lE(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",s=o==="private_key_jwt"?"none":o,i=pE({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),a=_s({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:o,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=st(r,rE),d=Math.floor(r.getTime()/1e3),l=Math.floor(c.getTime()/1e3),m={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:uE(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:ue,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:J(r),clientExpiresAt:J(c)};if(o==="client_secret_basic"||o==="client_secret_post"){let f=at();h.hashedClientSecret=await oe(f),h.clientSecretExpiresAt=J(c),m.client_secret=f,m.client_secret_expires_at=l,m.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw M("invalid_request","OAuth client is already registered.");return m}n(Jg,"registerDownstreamClient");function mE(e){return e?.metadata?.idpSubjectTokenType!==zr&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}n(mE,"hasStoredIdJagSubjectTokenBinding");async function Fg(e){let t=Mr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Fg,"readIdJagSubjectConnection");async function yc(e){let t=_e().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Fg({connection:t.connection,principal:e.principal});return!mE(r)}n(yc,"requiresIdJagSubjectTokenBinding");async function Gg(e){if(e.subjectToken===void 0)return;let t=_e().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await Fg({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??bs(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await pt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Gg,"bindIdJagSubjectTokenForAuthorizationTransaction");function Vg(e){return V`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(Vg,"renderShellIcon");function Kg(e){return V`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Kg,"renderActions");var Wg=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function Zg(e){return V`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}n(Zg,"renderBannerWarning");var Wz=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),Zz=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var Yz=Be('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var hE="data:,",Yg=V`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Xg=V`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function fE(e,t,r){if(e)try{let o=new URL(t).origin,s=new URL(e,o);return s.origin!==o||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}n(fE,"safeGatewayConnectHref");function gE(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(gE,"deriveMode");function yE(e){return Kg({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Yg,authorizeAttrs:Je})}n(yE,"renderActions");function Sc(e,t,r,o){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=fE(s.connectUrl,t,o);if(i)return i}}n(Sc,"firstUserConnectHref");function SE(e){let t=e.connectHref===void 0?Je:V`<a class="button button--primary" href="${e.connectHref}" ${Xg}>Connect</a>`;return V`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Yg}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(SE,"renderSetupActions");function _E(e){return e?V`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Xg}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Je}n(_E,"renderReconnectAction");function wE(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}n(wE,"isRenderableIconHref");function Qg(e){return e?.find(t=>wE(t.src))?.src}n(Qg,"readIconHref");function RE(e){return Qg(e.serverIcons)??(e.transportHost===void 0?void 0:Na(e.transportHost).src)}n(RE,"readUpstreamIconHref");function bE(e){let t=Qg(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=RE(r);if(o!==void 0)return o}}n(bE,"readHeaderIconHref");function vE(e){let t=e.setupMessage===void 0?Je:Zg({icon:Wg,message:e.setupMessage});return V`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(vE,"renderBody");function _c(e){let t=gE(e.upstreams),r=Sc(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=Sc(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=Sc(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o:void 0,a=t==="setup"?e.upstreams.find(l=>l.ownerMode==="user"&&l.status!=="active"&&l.connectUrl===void 0&&l.setupMessage!==void 0)?.setupMessage:void 0,c=bE({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?V`<footer class="card__footer">${SE({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:V`<footer class="card__footer">${_E(s)}${yE({state:e.state,gateway:e.gateway})}</footer>`;return Fr(Vr({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??hE,styles:Gr,headerIcon:c===void 0?Je:Vg({iconHref:c,fallbackIconHref:Mh}),heading:"Authorize access",subhead:Je,body:vE({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}n(_c,"renderConsentPage");var CE=1e4,ey="mcp-session-id",IE;function sy(){return{tools:[],prompts:[],resources:[]}}n(sy,"emptyCapabilities");function ty(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":zi})}n(ty,"buildReadinessHeaders");async function ry(e){if(e.type==="bearer_token"){let o=ty();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=ty();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(ry,"buildAsyncCredentialHeaders");function ny(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Wt.parse({jsonrpc:vr,id:1,method:"initialize",params:{protocolVersion:zi,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(ny,"buildInitializePreflight");async function wc(e){so(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),CE);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await Yc.fetch(o)}finally{clearTimeout(r)}}n(wc,"runPreflight");function Rc(e){e.body?.cancel().catch(()=>{})}n(Rc,"releasePreflightBody");async function TE(e){let t=e.response.headers.get(ey);if(!t)return;let r=new Headers(e.headers);r.set(ey,t),r.delete("content-type");try{let o=await wc(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Rc(o)}catch{}}n(TE,"terminatePreflightSession");async function iy(e){let{response:t}=e;return Rc(t),t.status>=200&&t.status<300?(await TE(e),{kind:"ready",upstreamStatus:t.status,capabilities:sy()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(iy,"classifyResponse");function oy(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(oy,"connectRequiredResult");async function EE(e){try{return iy({response:await wc(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(EE,"classifyPreflight");async function kE(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:sy()};let r=ti(t.upstreamServerId,e.route.operationId),o=Br(r,e.subjectId),s=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await Hr({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return oy(a.payload);let c=await ry(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d=ny({upstreamUrl:t.mcpUrl,headers:c}),l;try{l=await wc(d)}catch(y){return{kind:"upstream_unavailable",message:y instanceof Error?y.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return iy({response:l,upstreamUrl:t.mcpUrl,headers:c});Rc(l);let m=await Hr({request:i,routeAuth:s,forceRefresh:!0});if(m.kind==="connect_required")return oy(m.payload);let h=await ry(m.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:EE({request:ny({upstreamUrl:t.mcpUrl,headers:h}),upstreamUrl:t.mcpUrl,headers:h})}n(kE,"checkUpstreamRouteReadinessImpl");function ay(e){return(IE??kE)(e)}n(ay,"checkUpstreamRouteReadiness");function AE(e){try{return new URL(e).host}catch{return}}n(AE,"safeUrlHost");function cy(e){return e!==void 0&&e.length>0}n(cy,"hasItems");function PE(e){let t=e.serverInfo?.icons;if(cy(t))return t;let r=Hs(e.mcpUrl);return r===void 0?void 0:[r]}n(PE,"readServerIcons");async function xE(e){let{authConfig:t,authMode:r,description:o,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,l=a==="user",m=l&&r!=="id-jag",h=e.readiness??(l?Np(e.connection):{connected:!0,status:"active"}),y=m?e.readiness?.connectUrl??(e.returnTo!==void 0?await Ha({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,f=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:o,transportHost:AE(i),scopesRequested:cy(f)?f:void 0,serverIcons:PE(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:y,setupMessage:e.setupMessage,updatedAt:l&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}n(xE,"buildSetupRequirement");function dy(e){let t=_e().byOperationId.get(e);if(!t)throw M("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(dy,"requireRoute");async function bc(e){let t=dy(e.transaction.operationId),r=Mr(e.transaction.principal.subjectId),o=t.connection;if(o===void 0)return[];let i=o.ownerMode==="user"?(await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:o.upstreamServerId,authProfileId:o.authProfileId}]))[0]:void 0,a=await ay({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),c="connectionStatus"in a?a.connectionStatus:void 0,d=(a.kind==="connect_required"||a.kind==="admin_setup_required")&&a.payload.authUrl!==void 0?a.payload.authUrl:void 0,l=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await xE({connection:i,registeredConnection:o,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:l,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}n(bc,"requirementsForSetup");async function vc(e){let t=dy(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ne(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:o?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}n(vc,"consentContext");function Cc(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Cc,"hasUnresolvedUserUpstream");var OE=["mcp_user"],UE="dev-browser-user",ME=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),qE=p.object({response_type:p.literal("code"),client_id:p.string().min(1),redirect_uri:p.string().min(1),resource:p.url(),code_challenge:p.string().min(43),code_challenge_method:sp,state:p.string().min(1).optional(),scope:p.literal(ue).default(ue)}),zE=p.enum(["continue","approve","cancel"]).default("continue"),NE=p.object({state:p.string().min(1),decision:zE}),Mt=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function uy(e){return typeof e=="string"&&e.length>0?e:void 0}n(uy,"readQueryString");function jE(e,t){let r=uy(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new v("invalid_target",ME)}let o=Tp(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new v("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(jE,"requireAuthorizeResource");async function DE(e,t){let r={};t!==void 0&&(r.context=t);let o=await Zr(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let s=qg(e);return{principal:s,setCookie:await ko({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(DE,"resolveBrowserPrincipal");async function $E(e,t){let r={};t!==void 0&&(r.context=t);let o=await Zr(e,r);if(!o.principal)throw M("authentication_required","Authorization setup requires a current browser session.");return o.principal}n($E,"requireSetupPrincipal");function ly(e){return`${me().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(ly,"buildSetupReturnTo");async function py(e){let t=await bc({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:ly(e.csrfToken)}),r=await vc({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:_c({state:e.csrfToken,operationId:e.transaction.operationId,gateway:me(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(o.setCookies=e.setCookies),o}n(py,"renderSetup");function LE(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(LE,"toAuthorizationTransactionClient");async function Ic(e,t={}){let r=qE.parse({...e.query,resource:jE(e,t.operationId),state:uy(e.query.state)}),o=Xr(r.scope);Yr(r.redirect_uri,"invalid_request");let s=new Date,i=it.parse(r.client_id),a=await ai(r.client_id,s);Bg(a,r.redirect_uri);try{let c=tr(e.url,r.resource,e.headers),d=LE(a);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&X(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type}});let l={clientId:a?.clientId??i,...d===void 0?{}:{client:d},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:h}=await DE(e,t.context),y=m===void 0?!1:await yc({operationId:c.operationId,principal:m});if(!m||y){let R=await Ig({transaction:l,requestUrl:e.url,requestHeaders:e.headers,now:s});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,operationId:c.operationId,reason:m?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:R.browserLoginUrl,setCookies:[...h===void 0?[]:[h],R.browserBindingCookie]}}let f=await Eg({transaction:l,principal:m,now:s});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&X(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),py({transaction:f.transaction,csrfToken:f.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:h===void 0?void 0:[h]})}catch(c){throw HE({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Ic,"authorizeDownstreamClient");function HE(e){if(e.cause instanceof Mt)return e.cause;let t=BE(e.cause);return t?new Mt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(HE,"toDownstreamAuthorizeRedirectError");function BE(e){if(e instanceof v)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof p.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(BE,"mapToOAuthRedirectError");async function my(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let l=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...l===void 0?{}:{idpErrorDescription:l},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),M("provider_access_denied",l??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),M("oauth_state_invalid","Browser login callback is missing state.");let s=await dc(o),i=await Gs({purpose:"login",claim:s.binding,request:e});if(!i.matched&&At())throw t.context?.log.warn({event:"browser_login_callback_binding_mismatch",code:"oauth_callback_mismatch",stateKind:s.kind},"Browser login callback arrived in a browser that did not start the login"),M("oauth_callback_mismatch","Browser login was not started in this browser.");let a={request:e,stateId:s.stateId};if(t.context!==void 0&&(a.context=t.context),s.kind==="return_to"){let l=JE(i.payload),m=await gc(a);return{kind:"redirect",location:new URL(l,ne(e.url,e.headers)),setCookies:[await ko({principal:m.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await gc(a),d=await kg({browserLoginStateToken:o,principal:c.principal});if(await Gg({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await yc({operationId:d.transaction.operationId,principal:c.principal}))throw M("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return py({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await ko({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}n(my,"completeBrowserLoginCallback");function JE(e){let t=ro(e),r=me().actionPath("/auth/connections/"),o=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||o===void 0||!o.startsWith(r)||!/^[^/]+\/connect$/u.test(o.slice(r.length)))throw M("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}n(JE,"readConnectReturnTo");async function hy(e){let t=await Tg(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}n(hy,"startConnectBrowserLogin");async function fy(e){let t=ve(),r=new URL(e.url);if(!qe(r))throw M("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw M("oauth_state_invalid","Local browser login is missing state.");let s=me().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ne(e.url)),a=new URL(ne(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw M("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",o);let c={subjectId:to.parse(UE),roles:OE};return{kind:"redirect",location:i,setCookies:[await ko({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}n(fy,"completeLocalDevBrowserLogin");function FE(e){let t=e.method==="POST"?e.body:e.query;return NE.parse(t)}n(FE,"readSetupContinueRequest");async function gy(e){let{state:t,decision:r}=FE({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,s=await pc({csrfToken:t,now:o}),i=await $E(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await xg({csrfToken:t,currentBrowserPrincipal:i,now:o})};let a=await Ag({csrfToken:t,currentBrowserPrincipal:i,now:o}),c=await bc({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:ly(t)});if(r==="approve"&&Cc(c)&&await vg({csrfToken:t,currentBrowserPrincipal:i,now:o}),Cc(c)){let d=await vc({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:_c({state:t,operationId:a.operationId,gateway:me(),upstreams:c,...d})}}return{kind:"redirect",location:await Pg({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(gy,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as ok,decodeJwt as sk,errors as Po,jwtVerify as ik}from"jose";import{createRemoteJWKSet as GE,decodeJwt as VE,decodeProtectedHeader as KE,errors as Ao,jwtVerify as WE}from"jose";var Ry=30,se=p.string().min(1),ZE=p.union([se,p.array(se).min(1)]),YE=p.union([se,p.array(se).min(1)]),XE=p.object({type:se,locations:p.array(se).optional(),actions:p.array(se).optional(),datatypes:p.array(se).optional(),identifier:se.optional(),privileges:p.array(se).optional()}).passthrough(),QE=p.object({iss:p.url(),sub:se,aud:ZE,client_id:se,resource:YE.optional(),scope:se.optional(),authorization_details:p.array(XE).optional(),jti:se,iat:p.number().int(),nbf:p.number().int().optional(),exp:p.number().int(),tenant:se.optional(),aud_tenant:se.optional(),aud_sub:se.optional(),sub_id:se.optional(),act:p.unknown().optional(),email:se.optional(),auth_time:p.number().int().optional(),acr:se.optional(),amr:p.array(se).optional(),cnf:p.unknown().optional()}).passthrough();function je(e){throw new v("invalid_grant",e)}n(je,"throwInvalidGrant");function ek(e){return e instanceof Ao.JWTExpired?"expired":e instanceof Ao.JWTClaimValidationFailed?"claim":e instanceof Ao.JWSSignatureVerificationFailed?"signature":e instanceof Ao.JWKSNoMatchingKey?"jwks_no_match":e instanceof Ao.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(ek,"readJwtFailureKind");function tk(e){return Array.isArray(e.aud)?(e.aud.length!==1&&je("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(tk,"readSingleAudience");function yy(e){try{let t=QE.parse(e);return tk(t),t}catch(t){if(t instanceof v)throw t;je("ID-JAG claims are invalid.")}}n(yy,"parseIdJagClaims");function rk(e,t){e.idJag.enabled||je("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&je("ID-JAG issuer is not trusted."),r}n(rk,"readTrustedIssuer");function nk(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(o=>r.has(o.type))}n(nk,"readGrantedAuthorizationDetails");function Sy(e){if(e.clientAuth.method==="none")throw new v("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&je("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&je("ID-JAG client_id is not allowed for this issuer.")}n(Sy,"assertClientBinding");function _y(e){e.cnf!==void 0&&je("ID-JAG cnf-bound assertions require DPoP support.")}n(_y,"assertProofOfPossessionNotDeferred");function wy(e){let t=Math.floor(e.now.getTime()/1e3)+Ry;e.claims.iat>t&&je("ID-JAG iat must not be in the future.")}n(wy,"assertIssuedAtNotInFuture");async function by(e){let t;try{t=KE(e.assertion)}catch{je("ID-JAG assertion is malformed.")}t.typ!==Oi&&je('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=yy(VE(e.assertion))}catch(c){if(c instanceof v)throw c;je("ID-JAG assertion is malformed.")}let o=qr(e.requestUrl,e.requestHeaders),s=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&s.push(e.requestedResource);let i=rk(e.config,r.iss);s.includes(r.iss)&&je("ID-JAG issuer must be different from the gateway."),Sy({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),_y(r),wy({claims:r,now:e.now});let a;try{let c=GE(new URL(i.jwksUrl)),{payload:d}=await WE(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:Ry,typ:Oi});a=yy(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:ek(c)},"OAuth ID-JAG assertion verification failed"),je("ID-JAG assertion verification failed.")}return Sy({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),_y(a),wy({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:Ep({issuer:a.iss,subject:a.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:nk({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(by,"verifyIdJagAssertion");var ak=new Set(["authorization_code","refresh_token",vt]),ck=1e4,dk=32*1024,uk=2,lk=3600,Tc=p.object({client_id:p.string().min(1).optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),pk=p.discriminatedUnion("grant_type",[Tc.extend({grant_type:p.literal("authorization_code"),code:p.string().min(1),redirect_uri:p.string().min(1),code_verifier:kr,resource:p.url().optional(),scope:p.literal(ue).optional()}),Tc.extend({grant_type:p.literal("refresh_token"),refresh_token:p.string().min(1),resource:p.url().optional(),scope:p.literal(ue).optional()}),Tc.extend({grant_type:p.literal(vt),assertion:p.string().min(1),resource:p.url().optional(),scope:p.literal(ue).optional(),authorization_details:p.string().min(1).optional()})]);function mk(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!ak.has(t)))throw new v("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(mk,"assertSupportedGrantType");var hk=p.object({token:p.string().min(1),client_id:p.string().min(1).optional(),token_type_hint:p.string().optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),fk=p.object({keys:p.array(p.record(p.string(),p.unknown())).min(1)}).passthrough();function Cy(){return ve().gateway.accessTokenTtlSeconds}n(Cy,"readAccessTokenTtlSeconds");function gk(){return ve().gateway.refreshTokenTtlSeconds}n(gk,"readRefreshTokenTtlSeconds");function vy(e,t){let r=Cy(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,o);return{expiresAt:J(st(e,s)),expiresIn:s}}n(vy,"calculateAccessTokenExpiresAt");function yk(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new v("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new v("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new v("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}n(yk,"readIdJagResource");function Sk(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new v("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}n(Sk,"readIdJagGrantedAuthorizationDetails");function _k(e){if(e.claimScope?.split(/\s+/).includes(ue)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return ue;if(e.claimScope===void 0)throw new v("invalid_grant",`ID-JAG must include ${ue} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(ue))throw new v("invalid_grant",`ID-JAG scope must include ${ue}.`);return ue}n(_k,"readIdJagGrantedScope");function wk(e){if(e!==void 0&&e.get("dpop")!==null)throw new v("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}n(wk,"assertNoDpopProofForIdJag");function Iy(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new v("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new v("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new v("invalid_client","Malformed HTTP Basic client authentication.")}}n(Iy,"readBasicClientSecret");function Ty(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new v("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=sk(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new v("invalid_client","Malformed private_key_jwt client assertion.")}throw new v("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new v("invalid_client","Client authentication or client_id is required.")}n(Ty,"resolveAuthenticatedClientId");function Rk(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new v("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(Rk,"resolveClientSecretInput");function bk(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(bk,"hasClientAssertion");function vk(e){if(e.requestUrl===void 0)throw new v("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(me().actionPath(e.pathname),ne(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(vk,"buildEndpointAudience");function Ck(e){return e instanceof Po.JWTExpired?"expired":e instanceof Po.JWTClaimValidationFailed?"claim":e instanceof Po.JWSSignatureVerificationFailed?"signature":e instanceof Po.JWKSNoMatchingKey?"jwks_no_match":e instanceof Po.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(Ck,"readJwtFailureKind");async function Ik(e){let{response:t,json:r}=await Fh(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:uk,maxResponseBytes:dk,timeoutMs:ck});if(!t.ok)throw new v("invalid_client","Client JWKS could not be fetched.");return fk.parse(r)}n(Ik,"fetchClientJwks");async function Tk(e){if(e.clientAssertionType!==ys||e.clientAssertion===void 0)throw new v("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=it.parse(e.clientId),r=await ai(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new v("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new v("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=vk({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await Ik({jwksUri:o,context:e.context}),{payload:a}=await ik(e.clientAssertion,ok(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+lk;if(typeof a.exp!="number"||a.exp>c)throw new v("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Ck(i)},"OAuth private_key_jwt client authentication failed"),new v("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(Tk,"verifyPrivateKeyJwtClientAssertion");async function Ek(e){let t=it.parse(e.clientId);if(Up(t))throw new v("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await oe(e.clientSecret)}}n(Ek,"buildRuntimeHttpClientAuth");async function Ey(e){if(bk({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new v("invalid_request","Use only one client authentication method per request.");return Tk(e)}let t=Rk({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Ek({clientId:e.clientId,...t})}n(Ey,"resolveRuntimeHttpClientAuth");async function ky(e){mk(e.body);let t=pk.parse(e.body),r=Iy(e.authorizationHeader),o=Ty({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await Ey({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:s,context:e.context});return kk({parsed:t,clientId:o,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(ky,"exchangeDownstreamToken");async function kk(e){if(e.parsed.grant_type==="authorization_code"){Yr(e.parsed.redirect_uri,"invalid_request"),Xr(e.parsed.scope),e.parsed.resource!==void 0&&tr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=at(),d=at(),l=J(st(e.now,gk())),m=vy(e.now,l),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await oe(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await vs(e.parsed.code_verifier),currentRefreshTokenHash:await oe(c),accessTokenHash:await oe(d),grantExpiresAt:l,accessTokenExpiresAt:m.expiresAt,now:J(e.now)});if(h.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new v("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:m.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===vt){Xr(e.parsed.scope),wk(e.requestHeaders);let c=await by({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:ve()}),d=yk({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),l=tr(e.requestUrl??d,d,e.requestHeaders),m=Sk({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=_k({claimScope:c.claims.scope,grantedAuthorizationDetails:m}),y=at(),f=J(new Date(c.claims.exp*1e3)),R=vy(e.now,f),S=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await oe(y),subjectId:c.subjectId,resource:d,operationId:l.operationId,scope:h,authorizationDetails:m,accessTokenExpiresAt:R.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:f}});if(S.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(S.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:y,token_type:"Bearer",expires_in:R.expiresIn,scope:S.grant.scope,resource:S.grant.resource,...m===void 0?{}:{authorization_details:m}}}Xr(e.parsed.scope),e.parsed.resource!==void 0&&tr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await oe(e.parsed.refresh_token),r=e.parsed.refresh_token,o=at(),s=J(st(e.now,Cy())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await oe(o),resource:e.parsed.resource,accessTokenExpiresAt:s,now:J(e.now)});if(i.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new v("invalid_grant","Refresh token is invalid, expired, or revoked.");tr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:o,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}n(kk,"exchangeDownstreamTokenWithRuntimeHttp");async function Ay(e){let t=hk.parse(e.body),r=Iy(e.authorizationHeader),o=Ty({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await Ey({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:s,context:e.context}),tokenHash:await oe(t.token),now:J(s)})).kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Ay,"revokeDownstreamToken");var Ak=64*1024,Pk=16*1024,xk="text/html; charset=utf-8";function Ok(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Ok,"formDataToObject");async function Uk(e){return lg(e,{maxBytes:Ak,label:"Request body"})}n(Uk,"readJsonBody");async function kc(e){return Ok(await pg(e,{maxBytes:Pk,label:"Request body"}))}n(kc,"readFormBody");async function Py(e,t,r){let o=ot(r),s=r instanceof p.ZodError?qt(r):void 0,i={code:o??(r instanceof p.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),ms(e,t,i)}n(Py,"handleProblem");function xy(e){return e?.requestId}n(xy,"readBrowserRequestId");function Oy(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[Pr];return typeof t=="string"?t:void 0}n(Oy,"readUpstreamHtmlError");function Qr(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Qr,"readRuntimeErrorExtensionString");function Mk(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(Mk,"readRuntimeErrorExtensionNumber");function qk(e){try{return new URL(e.url).pathname}catch{return}}n(qk,"readBrowserRequestPath");function rr(e){let t={code:e.code,requestId:e.requestId,routePath:qk(e.request),underlyingError:e.underlyingError};return e.error instanceof T&&(t.httpStatus=Mk(e.error,rt),t.contentType=Qr(e.error,Ar),t.upstreamUrl=Qr(e.error,nt),t.upstreamServerId=Qr(e.error,ls),t.metadataUrl=Qr(e.error,xr),t.providerError=Qr(e.error,Or),t.providerErrorDescription=Qr(e.error,Ur)),t}n(rr,"buildBrowserErrorDiagnostic");function xo(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(xo,"oauthErrorResponse");function zk(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(zk,"readOAuthProtocolHeaders");function Nk(e,t){let r=We("internal_server_error");return xo({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:zk(e,t)})}n(Nk,"oauthProtocolErrorResponse");function Ec(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Ec,"readZodOAuthErrorCode");function jk(e){let t={error:Ec(e)},r=qt(e);return r!==void 0&&(t.errorDescription=r),xo(t)}n(jk,"oauthZodErrorResponse");function Dk(e){let t=ot(e);if(t===void 0)return;let r=We(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:Lk(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,xo(o)}n(Dk,"oauthGatewayProblemResponse");function $k(){let t={error:"server_error",status:500,errorDescription:We("internal_server_error").publicDetail};return xo(t)}n($k,"oauthFallbackErrorResponse");function Lk(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(Lk,"readOAuthStatus");function Ac(e,t={}){return e instanceof Mt?qy(e):e instanceof v?Nk(e,t):e instanceof p.ZodError?jk(e):Dk(e)??$k()}n(Ac,"oauthProblemResponse");function Pc(e,t,r){let o=Ut(e.url),s=xy(t);if(r instanceof Mt)return qy(r);if(r instanceof v){let c=We("internal_server_error");return Fe({host:o,kind:Hk(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?c.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?c.publicDetail:r.message,code:r.errorCode,diagnostic:rr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof p.ZodError)return Fe({host:o,kind:"invalid_request",detail:qt(r)??"The authorization request was invalid.",developerDetail:qt(r)??"The authorization request was invalid.",code:Ec(r),diagnostic:rr({request:e,requestId:s,code:Ec(r),underlyingError:qt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=ot(r);if(i!==void 0){let c=We(i);return Fe({host:o,kind:My(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Oy(r),status:c.status})}let a=We("internal_server_error");return Fe({host:o,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:rr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}n(Pc,"browserOAuthProblemResponse");function Uy(e,t,r){let o=Ut(e.url),s=xy(t),i=ot(r);if(i!==void 0){let c=We(i);return Fe({host:o,kind:My(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Oy(r),status:c.status})}if(r instanceof p.ZodError)return Fe({host:o,kind:"invalid_request",detail:qt(r)??"The authorization request was invalid.",developerDetail:qt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:rr({request:e,requestId:s,code:"invalid_request",underlyingError:qt(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=We("internal_server_error");return Fe({host:o,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:rr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}n(Uy,"browserGatewayProblemResponse");function Hk(e){return e==="server_error"?"internal_error":"invalid_request"}n(Hk,"readOAuthBrowserErrorKind");function My(e){if(We(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(My,"readGatewayBrowserErrorKind");function ft(e,t,r){let o={event:t},s=!1;if(r instanceof v)o.oauthError=r.errorCode,o.status=r.status,Ce(o,"error",r);else if(r instanceof Mt)o.oauthError=r.errorCode,Ce(o,"error",r);else if(r instanceof p.ZodError){o.code="invalid_request",Ce(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=ot(r);if(i!==void 0){let a=We(i);o.code=i,o.status=a.status,a.oauthError!==void 0&&(o.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",Ce(o,"error",r)}else s=!0,Ce(o,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,i.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(ft,"logUnexpectedOAuthHandlerError");function qy(e){let t;try{t=new URL(e.redirectUri)}catch{return xo({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(qy,"downstreamAuthorizeRedirectErrorResponse");function qt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(qt,"formatZodErrorDetail");function Bk(e,t){let r={event:"browser_login_callback_failed",code:ot(t)??"invalid_request"};Ce(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Bk,"logBrowserLoginCallbackFailure");function zy(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(null,{status:302,headers:t})}n(zy,"redirectResultResponse");function ci(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":xk,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(e.html,{status:200,headers:t})}return zy(e)}n(ci,"authorizeResultResponse");async function Ny(e,t){try{return Response.json(vp(e.url,e.headers))}catch(r){return ft(t,"oauth_authorization_server_metadata_failed",r),Py(e,t,r)}}n(Ny,"authorizationServerMetadataHandler");async function jy(e,t){try{let r=Ni(e.params.routePath);return Response.json(Cp({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return ft(t,"oauth_authorization_server_metadata_failed",r),Py(e,t,r)}}n(jy,"scopedAuthorizationServerMetadataHandler");async function Dy(e,t){try{let r=await Jg(await Uk(e)),o=r.client_id,s=r.client_name,i=r.redirect_uris.length,a=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:o,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),X(t,{eventType:F.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:o,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return ft(t,"oauth_register_failed",r),Ac(r)}}n(Dy,"registerHandler");async function $y(e,t){try{return ci(await Ic(e,{context:t}))}catch(r){return ft(t,"oauth_authorize_failed",r),Pc(e,t,r)}}n($y,"authorizeHandler");async function Ly(e,t){try{let r=Ni(e.params.routePath);return ci(await Ic(e,{operationId:r.operationId,context:t}))}catch(r){return ft(t,"oauth_authorize_scoped_failed",r),Pc(e,t,r)}}n(Ly,"scopedAuthorizeHandler");async function Hy(e,t){try{let r=await my(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),ci(r)}catch(r){return Bk(t,r),Uy(e,t,r)}}n(Hy,"callbackHandler");async function By(e,t){try{return zy(await fy(e))}catch(r){return ft(t,"oauth_dev_login_failed",r),Pc(e,t,r)}}n(By,"devLoginHandler");async function Jy(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await gy({request:e,body:e.method==="POST"?await kc(e):void 0,context:t});return ci(r)}catch(r){return ft(t,"oauth_setup_failed",r),Uy(e,t,r)}}n(Jy,"setupHandler");async function Fy(e,t){try{return Response.json(await ky({body:await kc(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return ft(t,"oauth_token_failed",r),Ac(r)}}n(Fy,"tokenHandler");async function Gy(e,t){try{return await Ay({body:await kc(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return ft(t,"oauth_revoke_failed",r),Ac(r)}}n(Gy,"revokeHandler");var Vy="0.0.0",Jk=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function Oo(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}n(Oo,"firstNonBlank");function Uo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}n(Uo,"clampToCodePoints");function Fk(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}n(Fk,"shortHash");function Ky(e,t){let r=[...e];if(r.length<=t)return e;let o=`-${Fk(e)}`;return t<=o.length?r.slice(0,t).join(""):`${r.slice(0,t-o.length).join("")}${o}`}n(Ky,"clampNameSegment");function Gk(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}n(Gk,"sanitizeRegistryNameSegment");var Vk=/^\d{1,3}(\.\d{1,3}){3}$/u;function Kk(e){let t=new URL(e).hostname.toLowerCase();if(Vk.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(o=>o.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(o=>o.length>0);return r.length>0?r.join("."):"local"}n(Kk,"buildRegistryNamespaceFromOrigin");function Wk(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}n(Wk,"sanitizeWebsiteUrl");function Zk(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let o;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;o=i.toString()}catch{continue}if(o.length>255||r.mimeType!==void 0&&!Jk.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:o,...r.mimeType===void 0?{}:{mimeType:r.mimeType},...s===void 0||s.length===0?{}:{sizes:s},...r.theme===void 0?{}:{theme:r.theme}})}return t.length>0?t:void 0}n(Zk,"sanitizeIcons");function Yk(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}n(Yk,"localNameFromRoutePath");function Wy(e){return e.includes("{")||e.includes(":")}n(Wy,"isParameterizedRoutePath");var Xk=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Zy(e){let t=Oo(e)??Vy;return Xk.test(t)?Vy:Uo(t,255)}n(Zy,"sanitizeRegistryVersion");function Yy(e){let t=Ky(Kk(e.origin),150),r=200-t.length-1,o=new Set,s=[];function i(c){let d=Ky(Gk(c),r),l=d;for(let m=2;o.has(l);m++){let h=`-${m}`;l=`${[...d].slice(0,r-h.length).join("")}${h}`}return o.add(l),l}n(i,"claimLocalName");function a(c,d){let l=`${t}/${i(c)}`;s.push({name:l,response:{server:{...d,name:l},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}n(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(Wy(c.routePath))continue;let d=c.connection,l=d?.serverInfo,m=Uo(Oo(d?.description,l?.description,d?.displayName,c.operationId)??c.operationId,100),h=Oo(l?.title,d?.displayName),y=Wk(l?.websiteUrl),f=Zk(l?.icons);a(c.operationId,{description:m,...h===void 0?{}:{title:Uo(h,100)},version:Zy(l?.version),...y===void 0?{}:{websiteUrl:y},...f===void 0?{}:{icons:f},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(Wy(c.routePath))continue;let d=c.operationId??Yk(c.routePath),l=Uo(Oo(c.summary,c.description,c.serverName,c.operationId,d)??d,100),m=Oo(c.serverName);a(d,{description:l,...m===void 0?{}:{title:Uo(m,100)},version:Zy(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}n(Yy,"buildMcpRegistryDirectory");var Qk=30,Xy=100;function Ye(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}n(Ye,"registryErrorResponse");function Oc(e){return Yy({registry:_e(),origin:ne(e.url,e.headers)})}n(Oc,"readEntries");function xc(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}n(xc,"decodePathParam");function Qy(e,t){return e.find(r=>r.name===t)}n(Qy,"findEntryByName");function eA(e){let t=e.get("limit");return t===null?{ok:!0,value:Qk}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Xy)}}n(eA,"parseLimit");function tA(e){let t=e.get("cursor");return t===null?{ok:!0,value:0}:/^\d+$/u.test(t)?{ok:!0,value:Number.parseInt(t,10)}:{ok:!1}}n(tA,"parseCursor");var rA=/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(\.\d+)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;function nA(e){let t=rA.exec(e);if(!t)return!1;let[,r,o,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(o)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(o)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}n(nA,"isValidRfc3339Timestamp");async function eS(e,t){let r=new URL(e.url).searchParams,o=eA(r);if(!o.ok)return Ye(400,`Invalid 'limit' parameter: expected a positive integer (max ${Xy}).`);let s=tA(r);if(!s.ok)return Ye(400,"Invalid 'cursor' parameter: pass the exact 'metadata.nextCursor' value returned by a previous list response.");let i=r.get("updated_since");if(i!==null&&!nA(i))return Ye(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let a=r.get("search")?.toLowerCase(),c=r.get("version"),d=Oc(e).sort((h,y)=>h.name<y.name?-1:h.name>y.name?1:0);a!==void 0&&a!==""&&(d=d.filter(h=>h.name.toLowerCase().includes(a))),c!==null&&c!=="latest"&&(d=d.filter(h=>h.response.server.version===c));let l=d.slice(s.value,s.value+o.value),m=s.value+o.value;return Response.json({servers:l.map(h=>h.response),metadata:{count:l.length,...m<d.length?{nextCursor:String(m)}:{}}})}n(eS,"listMcpRegistryServersHandler");async function tS(e,t){let r=xc(e.params.serverName);if(!r.ok)return Ye(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=Qy(Oc(e),r.value);return o===void 0?Ye(404,"Server not found"):Response.json({servers:[o.response],metadata:{count:1}})}n(tS,"listMcpRegistryServerVersionsHandler");async function rS(e,t){let r=xc(e.params.serverName);if(!r.ok)return Ye(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=xc(e.params.version);if(!o.ok)return Ye(400,"Invalid version: malformed encoding.");let s=Qy(Oc(e),r.value);return s===void 0?Ye(404,"Server not found"):o.value!=="latest"&&o.value!==s.response.server.version?Ye(404,"Server or version not found"):Response.json(s.response)}n(rS,"getMcpRegistryServerVersionHandler");function di(e,t){return(r,o)=>Ye(e,t)}n(di,"createWriteNotSupportedHandler");async function nS(e,t){return Ye(404,"Not found")}n(nS,"mcpRegistryNotFoundHandler");var oS=di(501,"Publishing is not supported by this registry"),sS=di(501,"Updates are not supported by this registry"),iS=di(501,"Deletion is not supported by this registry"),Uc=di(403,"You do not have publish or edit permissions for this server");function aS(e){return V`<section class="page-section" aria-labelledby="result-next-steps"><h2 class="section-label" id="result-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol></section>`}n(aS,"renderBrowserResult");var oA="text/html; charset=utf-8";function sA(e){return Vr({title:e.title,iconHref:za(e.host),styles:Gr,headerIcon:ni("success"),heading:e.title,subhead:V`<p class="card__subtitle">${e.detail}</p>`,body:aS({steps:Jr(e.steps.map(t=>V`<li>${t}</li>`))}),footer:""})}n(sA,"browserResultHtml");function iA(e,t=200){return new Response(Fr(e),{status:t,headers:{"content-type":oA,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(iA,"browserResultResponse");function cS(e){return iA(sA(e))}n(cS,"browserConnectionSuccessResponse");function ui(e,t,r={}){let o=ap(t);return Fe({host:e,kind:aA(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(ui,"browserConnectionFailureResponse");function aA(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}n(aA,"readCallbackFailureBrowserErrorKind");var cA={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},dS=Symbol("upstream-request");function Mo(e,t){Object.defineProperty(e,dS,{configurable:!0,value:t})}n(Mo,"setUpstreamRequestContext");function dA(e){let t=e[dS];if(!t)throw new be("Upstream request context has not been set");return t}n(dA,"readUpstreamRequestContext");function uA(e,t){return t.some(r=>r===e)}n(uA,"requestContextMatchesKind");function lA(e){return typeof e=="string"?[e]:e}n(lA,"toExpectedKinds");function qo(e,t){let r=dA(e),o=lA(t);if(!uA(r.kind,o)){let s=cA[o[0]];throw new be(`${s} request context has not been set`)}return r}n(qo,"requireUpstreamRequestContext");function zt(e){if(typeof e=="string"&&e.length!==0)return e}n(zt,"readOptionalQueryString");function pA(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new be(`Validated path parameter ${t} is missing`);return mA(r,t)}n(pA,"requirePathString");function mA(e,t){try{return decodeURIComponent(e)}catch(r){throw new T({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[E]:"invalid_request"}},{cause:r})}}n(mA,"decodePathString");function hA(e){let t=zt(e);return t?hs.parse(t):void 0}n(hA,"readOptionalOperationId");function fA(e){let t=_e().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new T({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[E]:"unknown_upstream_server"}})}n(fA,"readRegisteredAuthProfileId");function gA(e){let t=hA(e);if(!t)throw new T({message:"operationId query parameter is required.",extensionMembers:{[E]:"invalid_request"}});return t}n(gA,"readRequiredOperationId");async function Mc(e){return e.redirect?Fe({host:Ut(e.request.url),kind:"authorization_failed",title:e.title,detail:e.detail,code:e.status===401?"authentication_required":"forbidden",requestId:e.context.requestId,status:e.status}):e.status===401?He.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):He.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}n(Mc,"browserConnectRefusal");function yA(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let o of t)r.append("set-cookie",o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}n(yA,"withSetCookies");async function SA(e){let{request:t,context:r,ticket:o,redirect:s}=e;if(np(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await Mc({request:t,context:r,redirect:s,status:403,title:"Ask an administrator",detail:"This gateway cannot confirm who opened this link, so it cannot connect an account from it. Ask an administrator to connect this service."});let i=await Zr(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return yA(await Mc({request:t,context:r,redirect:s,status:401,title:"Sign in required",detail:"Open this connect link in a browser. The gateway asks you to sign in before it connects an account."}),a);let d=new URL(t.url),l=ro(`${d.pathname}${d.search}`);if(l===void 0)throw new be("Connect request path is empty");let m=await hy({returnTo:l,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:m.location.toString(),"cache-control":"no-store"});for(let y of[...a,m.setCookie])h.append("set-cookie",y);return new Response(null,{status:302,headers:h})}let c=o.ownerMode==="user"?o.ownerSubjectId:o.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await Mc({request:t,context:r,redirect:s,status:403,title:"This link is for another account",detail:"This connect link was created for a different gateway user, so it cannot connect an account in this browser. Ask your MCP client for its own connect link, or sign in to the gateway as the user who received this one."})}n(SA,"requireTicketOwnerBrowser");async function _A(e,t,r){let o=ti(r,gA(e.query.operationId));if(o.authMode==="id-jag")throw new T({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[E]:"invalid_request"}});let s=e.query.redirect==="true",i=zt(e.query.browserTicket);if(e.user){if(i)throw new T({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[E]:"invalid_request"}});let d=Yt(e.user,e.url),l={kind:"connect",...Br(o,d.subjectId),redirect:s},m=ro(zt(e.query.returnTo));return m!==void 0&&(l.returnTo=m),l}if(!i)throw new T({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[E]:"authentication_required"}});let a=await af(i);if(a.ownerMode!==o.ownerMode||a.upstreamServerId!==o.upstreamServerId||a.authProfileId!==o.authProfileId||a.operationId!==o.operationId)throw new T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});if(At()){let d=await SA({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await cf(a);let c=fs(a);switch(o.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});let d={kind:"connect",...o,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}case"user-oauth":{if(c.mode!=="user")throw new T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});let d={kind:"connect",...o,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}n(_A,"resolveConnectContext");async function wA(e,t,r){let o=dp.parse(pA(e,"connection"));switch(r){case"connect":{let s=await _A(e,t,o);if(s instanceof Response)return s;Mo(e,s);return}case"callback":{let s=zt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:o,error:s},d=zt(e.query.error_description);d!==void 0&&(c.errorDescription=d),Mo(e,c);return}let i=zt(e.query.code),a=zt(e.query.state);if(i&&a){let c=zt(e.query.iss);Mo(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:a,...c===void 0?{}:{iss:c}});return}Mo(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Mo(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:fA(o)});return}}n(wA,"resolveUpstreamRequestInbound");async function RA(e,t,r){try{return await wA(e,t,r)}catch(o){let s=o instanceof T?o.extensionMembers?.[E]:void 0,i=o instanceof Error?o.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return He.badRequest(e,t,{code:s,detail:i});case"authentication_required":return He.unauthorized(e,t,{code:s,detail:i});default:throw o}}}n(RA,"applyUpstreamRequestContext");function li(e,t){return n(async(o,s)=>{let i=await RA(o,s,e);return i||t(o,s)},"wrapped")}n(li,"withUpstreamRequestContext");var bA=["callback_authorization_code","callback_provider_error","callback_invalid"];function qc(e){try{return new URL(e.url).pathname}catch{return}}n(qc,"readBrowserRequestPath");function vA(e){return"cause"in e?e.cause:void 0}n(vA,"readErrorCause");function CA(e){return e.stack?.split(`
44
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}n(CA,"readFirstStackFrame");function uS(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=CA(r))}n(uS,"addErrorAttributes");function zc(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[E];return ps(t)?t:void 0}n(zc,"readRuntimeGatewayCode");function zo(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(zo,"readRuntimeErrorExtensionString");function IA(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(IA,"readRuntimeErrorExtensionNumber");function TA(e,t,r,o){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),X(t,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),ui(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:qc(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),ui(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:qc(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n(TA,"requireAuthorizationCallbackRequest");function EA(e,t){X(e,{eventType:F.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(EA,"emitCallbackReceivedAnalyticsEvent");function kA(e,t){X(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(kA,"emitTokenExchangeSucceededAnalyticsEvent");function AA(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return cS({host:Ut(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}n(AA,"buildSuccessfulCallbackResponse");function PA(e){let t={detail:e instanceof Error?e.message:void 0};return uS(t,"error",e),e instanceof Error&&uS(t,"cause",vA(e)),t}n(PA,"buildTokenExchangeFailureAttributes");function xA(e){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:zc(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:PA(e.error)})}n(xA,"emitTokenExchangeFailedAnalyticsEvent");function OA(e){let t=e.error,r=zc(t),o=ip(r)?r:"upstream_token_exchange_failed",s={code:o,requestId:e.context.requestId,routePath:qc(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof T?{httpStatus:IA(t,rt),contentType:zo(t,Ar),upstreamUrl:zo(t,nt),metadataUrl:zo(t,xr),providerError:zo(t,Or),providerErrorDescription:zo(t,Ur)}:{}};return ui(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:UA(t)})}n(OA,"tokenExchangeFailureResponse");function lS(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}n(lS,"withSetCookie");function UA(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[Pr];return typeof t=="string"?t:void 0}n(UA,"readUpstreamHtmlError");async function Nc(e,t){let r=qo(e,bA),o=Ut(e.url),s=TA(e,t,r,o);if(s instanceof Response)return s;EA(t,s);let i;try{let a=await Zf({request:e,callbackRequest:s,onBrowserBinding:n(c=>{i=c},"onBrowserBinding")});return kA(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),lS(AA(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:zc(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return Ce(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),xA({context:t,callbackRequest:s,error:a}),lS(OA({request:e,context:t,host:o,callbackRequest:s,error:a}),i)}}n(Nc,"callbackHandler");function MA(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(MA,"clientMetadataProblemDetail");async function pS(e,t){let r=qo(e,"connect"),o=r.redirect?await Io({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:Ws/1e3}):void 0,s=await Wf({request:e,connectRequest:r,...o===void 0?{}:{browserBinding:o.claim}});if(X(t,{eventType:F.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),o!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":o.setCookie,"cache-control":"no-store"}});let i=await Ys({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(pS,"connectHandler");async function mS(e,t){let r=qo(e,"client_metadata");try{let o=ne(e.url,e.headers),s=_f(o,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(o){if(!(o instanceof Y))throw o;let s=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),He.notFound(e,t,{code:"not_found",detail:MA(o)})}}n(mS,"oauthClientMetadataHandler");function qA(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(qA,"resolveInternalRoutePath");var zA={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function NA(){return new Response(null,{status:204,headers:zA})}n(NA,"buildWellKnownPreflightResponse");function jA(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(jA,"withWellKnownCorsHeaders");function nr(e){return async(t,r)=>t.method==="OPTIONS"?NA():jA(await e(t,r))}n(nr,"wrapWellKnownHandler");var hS=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:nr(Ny),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:nr(jy),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:nr(Ip),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Dy},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:$y},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Ly},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Hy},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:By},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Jy},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Fy},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Gy},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:li("client_metadata",mS)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:li("connect",pS)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:li("callback",Nc)}],DA=hS.filter(e=>!e.routeName.startsWith("upstream_")),$A=hS.filter(e=>e.routeName.startsWith("upstream_"));function LA(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:nr(eS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:nr(tS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:nr(rS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:oS},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:sS},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:iS},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Uc},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Uc},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:nr(nS),corsPolicy:"anything-goes"}]}n(LA,"buildMcpRegistryInternalRoutes");function HA(e){let t=hp({routes:e.routes,policies:e.policies,gateway:e.gateway});return fp(t),t}n(HA,"initializeMcpGatewayConnectionRegistry");function BA(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(BA,"hasDownstreamOAuthRoutes");function JA(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(JA,"hasIdJagDownstreamOAuth");function FA(e){let t=new Map;for(let o of e.byOperationId.values())o.downstreamOAuth&&t.set(o.downstreamOAuth.policyName,o.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new be("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(o=>`"${o}"`).join(", ");throw new Y(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}n(FA,"readSingletonDownstreamOAuthConfig");function GA(e,t,r){let o=String(t.params.routePath??""),s=e.byRoutePath.get(wp(o));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?ms(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(GA,"readScopedDownstreamOAuthConfig");function VA(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(VA,"routeUsesScopedOAuthConfig");function jc(e,t,r){return async(o,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let d=await r(o,s);if(d instanceof Response)return d;d&&rp(s,d)}let i=o.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}n(jc,"wrapInternalHandler");function Dc(e,t,r,o){e.addPluginRoute({path:qA(t,r),methods:t.methods,handler:o,processors:[nd],corsPolicy:t.corsPolicy??"none"})}n(Dc,"addInternalRoute");function fS(e,t){let r=HA(t);if(r.gateway.registry.enabled){Qe("plugin.mcp-gateway.registry");for(let c of LA(r.gateway.registry))Dc(e,c,r.gateway,jc(c.routeName,c.handler))}let o=BA(r),s=r.connectionsById.size>0,i,a=n(()=>(i===void 0&&(i=FA(r)),i),"readSingletonOAuthConfig");if(o){Qe("plugin.mcp-gateway.downstream-oauth"),JA(r)&&Qe("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of DA){let d=VA(c)?(l,m)=>GA(r,l,m):a;Dc(e,c,r.gateway,jc(c.routeName,c.handler,d))}}if(s){Qe("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())Qe(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of $A)Dc(e,c,r.gateway,jc(c.routeName,c.handler,o?a:void 0))}}n(fS,"registerMcpGatewayInternalRoutes");var $c=class extends rd{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),Qe("plugin.mcp-gateway"),this.#e=op(t)}registerRoutes(t){let r=t.parsedRouteData;r&&fS(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var _S=new Set(["jsonrpc","method","id"]),wS=new Set(["name","uri"]),KA=9,WA=[..._S,...wS,"params"],ZA=44,YA=1024,XA=1e3,gS=new TextDecoder("utf-8",{fatal:!0}),Lc=class{constructor(t){this.bytes=t}bytes;static{n(this,"EnvelopeScanner")}pos=0;scan(){let t=this.bytes;t[0]===239&&t[1]===187&&t[2]===191&&(this.pos=3),this.skipWhitespace();let r;return t[this.pos]===123?r=this.readObject():t[this.pos]===91?r=this.readBatch():this.fail(),this.skipWhitespace(),this.expect(this.pos===t.length),r}readBatch(){let t=[];if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===93)return this.pos++,t;for(;;){if(this.skipWhitespace(),this.bytes[this.pos]===123){let o=this.readObject();(o.id!==void 0||o.method!==void 0)&&(this.expect(t.length<XA),t.push(o))}else this.skipValue();this.skipWhitespace();let r=this.bytes[this.pos++];if(r===93)return t;this.expect(r===44)}}fail(){throw new SyntaxError("Unscannable request body")}expect(t){t||this.fail()}skipWhitespace(){for(;;){let t=this.bytes[this.pos];if(t!==32&&t!==10&&t!==13&&t!==9)return;this.pos++}}skipString(){this.expect(this.bytes[this.pos]===34),this.pos++;let t=!1;for(;;){let r=this.bytes[this.pos++];if(r===34)return t;r===92?(t=!0,this.pos++):this.expect(r!==void 0)}}skipValue(){this.skipWhitespace();let t=this.bytes[this.pos];if(t===34){this.skipString();return}if(t!==void 0&&t!==123&&t!==91&&t!==125&&t!==93&&t!==44&&t!==58){for(;!yS(this.bytes[this.pos]);)this.pos++;return}let r=[];for(;;){this.skipWhitespace();let o=this.bytes[this.pos];if(this.expect(o!==void 0),o===34)this.skipString();else if(o===123||o===91){r.push(o),this.pos++;continue}else if(o===125||o===93)this.expect(r.pop()===(o===125?123:91)),this.pos++;else if(o===44||o===58){this.expect(r.length>0),this.pos++;continue}else for(;!yS(this.bytes[this.pos]);)this.pos++;if(r.length===0)return}}readKey(){let t=this.pos,r=this.skipString(),o=this.pos-t;if(r)return o>ZA?void 0:JSON.parse(gS.decode(this.bytes.subarray(t,this.pos)));if(o>KA)return;let s=o-2;for(let i of WA){if(i.length!==s)continue;let a=0;for(;a<s&&this.bytes[t+1+a]===i.charCodeAt(a);)a++;if(a===s)return i}}readObject(t=_S,r=!0){let o={};if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===125)return this.pos++,o;for(;;){this.skipWhitespace();let s=this.readKey();this.skipWhitespace(),this.expect(this.bytes[this.pos++]===58),this.skipWhitespace();let i=this.pos;if(r&&s==="params")if(delete o.params,this.bytes[i]===123){let c=this.readObject(wS,!1);Object.keys(c).length>0&&(o.params=c)}else this.skipValue();else if(this.skipValue(),s!==void 0&&t.has(s)){delete o[s];let c=this.readPrimitive(i);(typeof c=="string"||typeof c=="number"&&s==="id")&&(o[s]=c)}this.skipWhitespace();let a=this.bytes[this.pos++];if(a===125)return o;this.expect(a===44)}}readPrimitive(t){let r=this.bytes[t];if(!(r===34||r===45||r>=48&&r<=57)||this.pos-t>YA)return;let s=gS.decode(this.bytes.subarray(t,this.pos)),i=JSON.parse(s);return typeof i=="number"&&!tP(s,i)?void 0:i}};function yS(e){return e===void 0||e===44||e===125||e===93||e===32||e===10||e===13||e===9}n(yS,"isDelimiter");function QA(e){try{return new Lc(new Uint8Array(e)).scan()}catch{return{}}}n(QA,"sniffEnvelope");var eP=/^(-)?(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function SS(e){let t=eP.exec(e);if(!t)return;let[,r,o,s="",i]=t,a=`${o}${s}`.replace(/^0+/,""),c=Number(i??0)-s.length;if(a==="")return"0";let d=/0*$/.exec(a)?.[0].length??0;return a=a.slice(0,a.length-d),c+=d,`${r??""}${a}e${c}`}n(SS,"canonicalDecimal");function tP(e,t){if(!Number.isFinite(t))return!1;let r=SS(e),o=SS(JSON.stringify(t));return r!==void 0&&r===o}n(tP,"isLosslessNumberLiteral");function RS(e){if(!(e===void 0||e.byteLength===0)){if(e.byteLength>262144)return{value:QA(e)};try{return{value:JSON.parse(new TextDecoder().decode(e))}}catch{return}}}n(RS,"parseRequestJson");var rP="zuplo_mcp_",nP=["__host-","__secure-"];function oP(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let o of nP)r.startsWith(o)&&(r=r.slice(o.length));return r.startsWith(rP)}n(oP,"setsGatewayCookie");function bS(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!oP(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let o=new Headers(e.headers);o.delete("clear-site-data"),o.delete("set-cookie");for(let s of r)o.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:o})}n(bS,"stripUpstreamOriginStateHeaders");function gt(e){return e&&typeof e=="object"?e:void 0}n(gt,"readRecord");function No(e,t){let r=gt(e)?.[t];return typeof r=="string"?r:void 0}n(No,"readStringProperty");function CS(e,t){let r=gt(e)?.[t];return typeof r=="number"?r:void 0}n(CS,"readNumberProperty");function vS(e,t){return CS(e,"code")??(t>=400?t:void 0)}n(vS,"readErrorCode");function IS(e){return Array.isArray(e)?e.map(IS).find(t=>t?.method):gt(e)}n(IS,"readJsonRpcMessage");function Hc(e){let t=IS(e),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:No(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:No(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=No(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}n(Hc,"buildBaseCapabilityInput");function pi(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(pi,"isCapabilityListMethod");function sP(e,t,r){let i=gt(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(sP,"readItemCount");function TS(e){let t=Hc(e);return!t||pi(t.mcpMethod)?null:{eventType:F.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(TS,"buildCapabilityInvokedAnalyticsInput");function iP(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}n(iP,"readMissingResponseFailure");function ES(e,t){let r=Hc(e);if(!r)return null;let o=gt(t.message),s=gt(o?.error),i=gt(s?.data),a=o?.result,c=r.mcpMethod==="tools/call"&&gt(a)?.isError===!0;if(gt(i?.connectRequired))return{eventType:F.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:CS(s,"code"),mcpErrorType:No(s,"message")};let d=t.status<400?iP(t):void 0;if(d&&!s)return{eventType:pi(r.mcpMethod)?F.MCP_CAPABILITY_LISTED:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,...d};if(pi(r.mcpMethod)){let l=t.status>=400?void 0:sP(r.mcpMethod,r.capabilityType,a),m=t.status<400&&!s&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:F.MCP_CAPABILITY_LISTED,outcome:t.status>=400||s?"failure":"success",...r,httpStatusCode:t.status,...m?{mcpStatus:"not_parsed"}:{},...t.status>=400||s?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:vS(s,t.status)}:{},...l===void 0?{}:{attributes:{itemCount:l}}}}return t.status>=400||s?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:vS(s,t.status),mcpErrorType:No(s,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:"success",...r,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:c?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:c,applicationError:c}}n(ES,"buildCapabilityFinalAnalyticsInput");function kS(e,t){let r=Hc(e);return r?{eventType:pi(r.mcpMethod)?F.MCP_CAPABILITY_LISTED:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}n(kS,"buildCapabilityThrownAnalyticsInput");var AS={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},PS={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var Fc=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),xS=64*1024,Gc=1024*1024,aP=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function OS(e){return e!==void 0&&aP.has(e)?Gc:xS}n(OS,"tapMaxBytesForMethod");function cP(e){let t=It(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}n(cP,"readTapMode");function dP(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(dP,"isPlainObject");function uP(e){return dP(e)&&!("method"in e)&&("result"in e||"error"in e)}n(uP,"isResponseShaped");function lP(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}n(lP,"isSameJsonRpcIdValue");function US(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(uP);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>lP(a.id,t));if(i||r)return i}return s[0]}n(US,"selectResponse");function MS(e){try{return JSON.parse(e)}catch{return}}n(MS,"tryParseJson");var Bc=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{n(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let o of this.#e)t.set(o,r),r+=o.byteLength;this.#e=[],this.#n=US(MS(new TextDecoder().decode(t)),this.requestId,!1)}},Jc=class{constructor(t,r){this.requestId=t;this.#e=new yo({maxEventChars:r,onOversize:"discard"})}requestId;static{n(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let o=t(r);this.#r||=r.discardedEvents>0;for(let s of o){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=US(MS(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},pP={push(){},end(){},message:void 0,truncated:!1};function mP(e,t,r){switch(e){case"json":return new Bc(t,r);case"sse":return new Jc(t,r);case"passthrough":return pP}}n(mP,"createObserver");function qS(e,t={}){let r=e.body;if(r===null){let I=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:I,outcome:I}}let o=Tt(e.headers)?"passthrough":cP(e),s=mP(o,t.requestId,t.maxBytes??xS),i,a=new Promise(I=>{i=I}),c,d=new Promise(I=>{c=I}),l=!1,m=n(()=>{l||s.message===void 0||(l=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,y=!1,f=n((I,O)=>{if(y)return;if(y=!0,I==="complete")try{s.end()}catch{}let N={ended:I,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...o==="passthrough"&&h>0?{uninspected:!0}:{},...O===void 0?{}:{error:O}};i(N),l||(l=!0,c(N))},"settle"),R=r.getReader(),S=new ReadableStream({async pull(I){let O;try{O=await R.read()}catch(N){f("errored",N),I.error(N);return}if(O.done){f("complete"),I.close();return}if(h+=O.value.byteLength,!y)try{s.push(O.value)}catch{}I.enqueue(O.value),m()},async cancel(I){f(I===Fc?"released":"cancelled"),await R.cancel(I)}},{highWaterMark:0}),w=Qm(new Headers(e.headers)),x;try{x=new Response(S,{status:e.status,statusText:e.statusText,headers:w})}catch(I){throw R.cancel(I).catch(()=>{}),I}return{response:x,done:a,outcome:d}}n(qS,"tapJsonRpcResponse");var hP=-32603,fP="The upstream MCP server ended the response stream without a response to this request.",gP="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function zS(e){return`${typeof e}:${String(e)}`}n(zS,"idKey");function yP(e,t){if(e.delete(zS(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}n(yP,"clearAnsweredRequest");function NS(e){let t=Array.isArray(e)?e:[e],r=[];for(let o of t){if(!jS(o)||typeof o.method!="string"||typeof o.id!="string"&&typeof o.id!="number")continue;let s=go(o);s!==void 0&&r.push(s)}return r}n(NS,"readJsonRpcRequestIds");function jS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(jS,"isRecord");function SP(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],o=[];for(let s of r)jS(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&o.push(s.id);return o}n(SP,"readResponseIds");function _P(e){let t=e.getReader();return new ReadableStream({async pull(r){let o;try{o=await t.read()}catch{r.close();return}if(o.done){r.close();return}r.enqueue(o.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}n(_P,"endOnError");function DS(e,t,r=Gc,o){let s=new Map;for(let a of t)s.set(zS(a),a);let i=!1;return va(_P(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of SP(a.data))yP(s,c)},{failureMode:"open",maxEventChars:r,onFailure:n((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:n(()=>{if(s.size===0||i)return[];let a=o?.aborted?gP:fP;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:hP,message:a}})}))},"end")})}n(DS,"answerUnansweredRequests");var wP={Allow:"POST"},$S="mcp-session-id";async function RP(e){try{return await e.clone().arrayBuffer()}catch{return}}n(RP,"readRequestBody");function Vc(e){try{let t=gp(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}n(Vc,"readRouteAnalyticsFields");function Kc(e){return kp(e.user,e.url,e.headers)?.subjectId}n(Kc,"readRequestSubjectId");function bP(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}n(bP,"readRequestMethod");function LS(e,t){let r=e.get(t);return r===null||r===""?void 0:r}n(LS,"readHeader");function Wc(e){let t=LS(e.request.headers,$S)??(e.response?LS(e.response.headers,$S):void 0),r=e.tapResult?.message?.result,o=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=eo(e.request.headers,e.requestJson?.value)??o;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}n(Wc,"readMcpProtocolFields");function vP(e){let t=TS(e.requestJson?.value);t&&X(e.context,{...t,...Vc(e.context),...Wc({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http"})}n(vP,"emitCapabilityInvokedAnalytics");function CP(e){let t=ES(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended});t&&$p(e.context,{...t,...Vc(e.context),...Wc(e),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(CP,"emitCapabilityFinalAnalytics");function HS(e){let t=kS(e.requestJson?.value,e.details);t&&X(e.context,{...t,...Vc(e.context),...Wc({request:e.request}),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(HS,"emitCapabilityThrownAnalytics");async function BS(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let o=new _r(e.request,{headers:t,...r===void 0?{}:{body:r}});return Ql(o,e.context,s=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=s)})}n(BS,"callUpstream");async function FS(e){try{await e.body?.cancel()}catch{}}n(FS,"discardBody");async function IP(e){let t=await BS(e);if(t.status!==401)return t;let r=Qf(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return t;await FS(t);let o=await r.refresh(t,new Headers(e.request.headers));return o.kind==="response"?o.response:BS({...e,headers:o.headers})}n(IP,"forwardToUpstream");function TP(e,t,r){if(e.body===null||e.status<200||e.status>299||It(e.headers.get("content-type"))!=="text/event-stream"||Tt(e.headers))return e;let o=NS(t?.value);if(o.length===0)return e;let s=dt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(DS(e.body,o,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}n(TP,"withUnansweredRequestErrors");function EP(e,t){od.findContextExtensions(e)?.addPipelineExitHook(r=>{let o=t.body;r===t||o===null||r?.body===o||o.locked||o.cancel(Fc).catch(()=>{})})}n(EP,"releaseBodyIfNotSent");function JS(e){return e instanceof Y?PS:AS}n(JS,"thrownDetails");async function kP(e,t){if(Qe("handler.mcp-gateway-proxy"),e.method==="GET")return He.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},wP);let r=Date.now(),o=await RP(e),s=RS(o);Lp(t,eo(e.headers,s?.value)),vP({context:t,request:e,requestJson:s});let i={},a;try{a=bS(await IP({request:e,context:t,bodyBytes:o,upstreamTimeout:i}))}catch(l){throw HS({context:t,request:e,requestJson:s,startedAt:r,details:JS(l)}),l}let c,d;try{c=qS(a,{requestId:go(s?.value),maxBytes:OS(bP(s))}),d=TP(c.response,s,i.signal),EP(t,d)}catch(l){throw await FS(c?.response??a),HS({context:t,request:e,requestJson:s,startedAt:r,details:JS(l)}),l}return t.waitUntil(c.outcome.then(l=>{CP({context:t,request:e,requestJson:s,response:a,tapResult:l,startedAt:r})}).catch(l=>{try{td.getLogger(t).error(l,"Error emitting MCP gateway capability analytics")}catch{}})),d}n(kP,"McpProxyHandler");export{n_ as McpAuth0OAuthInboundPolicy,xa as McpCapabilityFilterInboundPolicy,VS as McpClerkOAuthInboundPolicy,KS as McpCognitoOAuthInboundPolicy,WS as McpEntraOAuthInboundPolicy,$c as McpGatewayPlugin,ZS as McpGoogleOAuthInboundPolicy,YS as McpKeycloakOAuthInboundPolicy,XS as McpLogtoOAuthInboundPolicy,o_ as McpOAuthInboundPolicy,QS as McpOktaOAuthInboundPolicy,e_ as McpOneLoginOAuthInboundPolicy,t_ as McpPingOAuthInboundPolicy,kP as McpProxyHandler,sc as McpTokenExchangeInboundPolicy,r_ as McpWorkosOAuthInboundPolicy,bh as claimsCapabilityResolver};
30
45
  /*! For license information please see index.js.LEGAL.txt */
31
46
  //# sourceMappingURL=index.js.map