@zuplo/runtime 7.8.0 → 7.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as lr,$a as jc,$b as Nd,$c as Tu,$e as ve,$f as tl,$g as Ye,A as Ga,Aa as pc,Ab as ld,Ac as Qd,Af as wg,Ag as cl,Ba as mc,Bb as pd,Bc as eu,Bf as Rg,Bg as dl,C as Mo,Ca as hc,Cb as md,Cc as tu,Cf as bg,Cg as os,Da as fc,Db as hd,Dc as ru,Df as vg,Dg as ul,Ea as gc,Eb as fd,Ec as nu,Ef as Ig,Eg as ll,Fa as yc,Fb as gd,Fc as ou,Ff as Cg,Fg as is,Ga as Sc,Gb as yd,Gc as iu,Gf as Tg,Gg as pl,Ha as _c,Hb as Sd,Hc as su,Hf as kg,Hg as $t,Ia as wc,Ib as _d,Ic as au,If as Eg,Ig as ml,Ja as Rc,Jb as wd,Jc as cu,Jf as Gu,Jg as Fn,Ka as bc,Kb as Rd,Kc as du,Kf as Ju,Kg as hl,La as vc,Lb as bd,Lc as uu,Lf as Vu,Lg as Wo,Ma as Ic,Mb as vd,Mc as lu,Mf as Fo,Mg as Gn,Na as Cc,Nb as Id,Nc as pu,Nf as Ln,Ng as fl,Oa as Li,Ob as Cd,Oc as mu,Of as Ku,Og as gl,P as Ja,Pa as Tc,Pb as Td,Pc as hu,Pf as vr,Pg as yl,Qa as kc,Qb as kd,Qc as fu,Qf as Wu,Qg as Sl,Ra as Ec,Rb as Ed,Rc as gu,Rf as Yi,Rg as _l,Sa as Pc,Sb as Pd,Sc as yu,Sf as Zu,Sg as wl,Ta as Ac,Tb as Ad,Tc as Su,Tf as Hn,Tg as Rl,Ua as xc,Ub as xd,Uc as _u,Uf as Go,Ug as bl,Va as Uc,Vb as Ud,Vc as wu,Vf as Yu,Vg as Zo,W as qo,Wa as Oc,Wb as Od,Wc as Ru,Wf as Xu,Wg as vl,X as Ni,Xa as Mc,Xb as Hi,Xc as bu,Xf as Qu,Xg as Il,Y as dr,Ya as qc,Yb as Md,Yc as vu,Yf as el,Yg as N,Z as Nn,Za as zc,Zb as qd,Zc as Iu,Zf as Se,Zg as J,_ as ur,_a as Nc,_b as zd,_c as Cu,_e as ju,_f as de,_g as me,aa as jn,ab as Dc,ac as jd,ad as ku,af as Du,ag as rl,ah as X,ba as pr,bb as $c,bc as Dd,bd as Eu,bf as $u,bg as D,bh as Yo,ca as Va,cb as Lc,cc as $d,cd as Pu,cf as Y,cg as We,ch as Pg,da as Ka,db as Hc,dc as Ld,dd as Au,df as Lu,dg as Ir,dh as Ag,ea as Wa,eb as Bc,ec as Hd,ed as xu,ef as gr,eg as pe,fa as Za,fb as Fc,fc as Bd,fd as Uu,ff as Hu,fg as te,ga as Ya,gb as Gc,gc as Fd,gd as mr,gf as yr,gg as nl,ha as Xa,hb as Jc,hc as Gd,hd as hr,hf as C,hg as W,ia as Qa,ib as Vc,ic as Jd,id as Ou,if as Sr,ig as ol,ja as ec,jb as Kc,jc as Vd,jd as fr,jf as _r,jg as pt,ka as tc,kb as Wc,kc as Kd,kd as ut,kf as Je,kg as Xi,l as De,la as rc,lb as Zc,lc as Wd,ld as Zi,lf as Ve,lg as Jo,ma as nc,mb as Yc,mc as Bi,md as $o,mf as Lo,mg as Qi,na as oc,nb as Xc,nc as zo,nd as Mu,nf as wr,ng as Vo,oa as ic,ob as Qc,oc as No,od as $n,of as Rr,og as Bn,pa as sc,pb as ed,pc as Fi,pd as Dt,pf as br,pg as Cr,qa as ac,qb as td,qc as Gi,qd as qu,qf as Ho,qg as il,ra as cc,rb as rd,rc as Ji,rd as zu,rf as Bu,rg as Ze,s as Nt,sa as jt,sb as nd,sc as Zd,sf as Oe,sg as es,t as Ba,ta as ji,tb as od,tc as Vi,tf as Fu,tg as ts,ua as Di,ub as id,uc as Ki,uf as Ke,ug as sl,v as H,va as Dn,vb as sd,vc as Yd,vf as x,vg as Ko,wa as $i,wb as ad,wc as Xd,wf as Bo,wg as rs,xa as dc,xb as cd,xc as Wi,xd as Nu,xf as le,xg as ns,ya as uc,yb as dd,yc as jo,yf as lt,yg as al,za as lc,zb as ud,zc as Do,zf as _g,zg as ne}from"../chunk-BB77BBJC.js";import"../chunk-B5DKYXCI.js";import{a as Cl}from"../chunk-6SNZ4DOC.js";import{a as Fa}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as l,b as Mi,c as qn,d as $a,e as d,f as La,g as Ha,h as b,i as A,j as Uo,l as M,m as _,n as m,o as z,p as E,q as qi,r as zn,s as T,t as j,u as g,v as q,w as zi,x as Oo}from"../chunk-GCOWKKQW.js";import{$ as xo,X as ye,Y as v,Z as K,_ as Da}from"../chunk-HWNKBEMX.js";import{a as n}from"../chunk-TYV53J3B.js";var xg=Object.create,Xo=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,Og=Object.getOwnPropertyNames,Mg=Object.getPrototypeOf,qg=Object.prototype.hasOwnProperty,Tl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),kl=n((e,t)=>{let r={};for(var o in e)Xo(r,o,{get:e[o],enumerable:!0});return t&&Xo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),zg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Og(t),s=0,c=i.length,a;s<c;s++)a=i[s],!qg.call(e,a)&&a!==r&&Xo(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=Ug(t,a))||o.enumerable});return e},"__copyProps"),El=n((e,t,r)=>(r=e!=null?xg(Mg(e)):{},zg(t||!e||!e.__esModule?Xo(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Ng=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Pl(e){return typeof e=="string"&&Ng.has(e.replace(/#$/,""))}n(Pl,"declares2019Dialect");var ls=Symbol.for("mcp.sdk.errorBrands");function Lt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let i=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof i=="string"&&r.add(i),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,ls,{value:r,enumerable:!1,configurable:!0})}n(Lt,"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,ls)){let r=t[ls];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})({}),ht=class Dl 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",Lt(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 Dl(t.error,t.error_description??t.error,t.error_uri)}},ie=(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",Lt(this,new.target)}},Wg=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 $l(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n($l,"resourceUrlFromServerUrl");function ni({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 i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(s)}n(ni,"checkResourceAllowed");var Zg="2026-07-28";function Ll(e){return e>=Zg}n(Ll,"isModernProtocolVersion");function Hl(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(Hl,"appendTextFallbackForNonObject");var Bl=["task","inputRequests","requestState"];function Yg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Bl.some(t=>t in e)?e:{...e,content:[]}}n(Yg,"normalizeContentlessToolResult");function Xg(){let e=zi(()=>E([d(),b(),A(),Uo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),c=z({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=m({_meta:c.optional()}),u=a.extend({task:i.optional()}),p=m({method:d(),params:a.loose().optional()}),h=m({_meta:c.optional()}),f=m({method:d(),params:h.loose().optional()}),y=z({_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()}),L=m({name:d(),title:d().optional()}),F=L.extend({...L.shape,...O.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ee=zn(m({applyDefaults:A().optional()}),t),G=Oo(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,zn(m({form:ee.optional(),url:t.optional()}),t.optional())),V=z({list:t.optional(),cancel:t.optional(),requests:z({sampling:z({createMessage:t.optional()}).optional(),elicitation:z({create:t.optional()}).optional()}).optional()}),Be=z({list:t.optional(),cancel:t.optional(),requests:z({tools:z({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()}),ze=a.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),$=p.extend({method:g("initialize"),params:ze}),Ae=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:Be.optional(),extensions:T(d(),t).optional()}),Lr=y.extend({protocolVersion:d(),capabilities:Ae,serverInfo:F,instructions:d().optional()}),Jt=f.extend({method:g("notifications/initialized"),params:h.optional()}),ot=p.extend({method:g("ping"),params:a.optional()}),It=m({progress:b(),total:q(b()),message:q(d())}),Ne=m({...h.shape,...It.shape,progressToken:r}),it=f.extend({method:g("notifications/progress"),params:Ne}),Vt=a.extend({cursor:o.optional()}),Fe=p.extend({params:Vt.optional()}),Ge=y.extend({nextCursor:o.optional()}),Kt=m({uri:d(),mimeType:q(d()),_meta:T(d(),M()).optional()}),Wt=Kt.extend({text:d()}),Ct=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zt=Kt.extend({blob:Ct}),je=j(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:qn.datetime({offset:!0}).optional()}),Tt=m({...L.shape,...O.shape,uri:d(),description:q(d()),mimeType:q(d()),size:q(b()),annotations:xe.optional(),_meta:q(z({}))}),Hr=m({...L.shape,...O.shape,uriTemplate:d(),description:q(d()),mimeType:q(d()),annotations:xe.optional(),_meta:q(z({}))}),Br=Fe.extend({method:g("resources/list")}),Fr=Ge.extend({resources:_(Tt)}),st=Fe.extend({method:g("resources/templates/list")}),Yt=Ge.extend({resourceTemplates:_(Hr)}),kt=a.extend({uri:d()}),Gr=kt,Jr=p.extend({method:g("resources/read"),params:Gr}),Vr=y.extend({contents:_(E([Wt,Zt]))}),Kr=f.extend({method:g("notifications/resources/list_changed"),params:h.optional()}),Wr=kt,Zr=p.extend({method:g("resources/subscribe"),params:Wr}),Yr=kt,Xr=p.extend({method:g("resources/unsubscribe"),params:Yr}),Qr=h.extend({uri:d()}),en=f.extend({method:g("notifications/resources/updated"),params:Qr}),tn=m({name:d(),description:q(d()),required:q(A())}),rn=m({...L.shape,...O.shape,description:q(d()),arguments:q(_(tn)),_meta:q(z({}))}),nn=Fe.extend({method:g("prompts/list")}),on=Ge.extend({prompts:_(rn)}),sn=a.extend({name:d(),arguments:T(d(),d()).optional()}),an=p.extend({method:g("prompts/get"),params:sn}),Et=m({type:g("text"),text:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),Pt=m({type:g("image"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),At=m({type:g("audio"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),cn=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),at=m({type:g("resource"),resource:E([Wt,Zt]),annotations:xe.optional(),_meta:T(d(),M()).optional()}),dn=Tt.extend({type:g("resource_link")}),Ee=E([Et,Pt,At,dn,at]),Xt=m({role:je,content:Ee}),Qt=y.extend({description:d().optional(),messages:_(Xt)}),xt=f.extend({method:g("notifications/prompts/list_changed"),params:h.optional()}),un=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),er=m({taskSupport:j(["required","optional","forbidden"]).optional()}),Ut=m({...L.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:un.optional(),execution:er.optional(),_meta:T(d(),M()).optional()}),tr=Fe.extend({method:g("tools/list")}),rr=Ge.extend({tools:_(Ut)}),nr=y.extend({content:_(Ee),structuredContent:T(d(),M()).optional(),isError:A().optional()}),ae=u.extend({name:d(),arguments:T(d(),M()).optional()}),ln=p.extend({method:g("tools/call"),params:ae}),ho=f.extend({method:g("notifications/tools/list_changed"),params:h.optional()}),or=j(["debug","info","notice","warning","error","critical","alert","emergency"]),pn=a.extend({level:or}),mn=p.extend({method:g("logging/setLevel"),params:pn}),hn=h.extend({level:or,logger:d().optional(),data:M()}),fn=f.extend({method:g("notifications/message"),params:hn}),gn=m({name:d().optional()}),yn=m({hints:_(gn).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Sn=m({mode:j(["auto","required","none"]).optional()}),fo=m({type:g("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(Ee),structuredContent:m({}).loose().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),_n=qi("type",[Et,Pt,At]),ct=qi("type",[Et,Pt,At,cn,fo]),wn=m({role:je,content:E([ct,_(ct)]),_meta:T(d(),M()).optional()}),Rn=u.extend({messages:_(wn),modelPreferences:yn.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:Sn.optional()}),bn=p.extend({method:g("sampling/createMessage"),params:Rn}),vn=y.extend({model:d(),stopReason:q(j(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:_n}),In=y.extend({model:d(),stopReason:q(j(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:E([ct,_(ct)])}),Cn=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),Tn=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()}),kn=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()}),Pn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),An=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),xn=E([En,Pn]),Ot=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()}),Mt=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()}),go=E([Ot,Mt]),yo=E([An,xn,go]),Re=E([yo,Cn,Tn,kn]),be=u.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),Re),required:_(d()).optional()}).catchall(M())}),Un=u.extend({mode:g("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=E([be,Un]),So=p.extend({method:g("elicitation/create"),params:Ue}),_o=h.extend({elicitationId:d()}),wo=f.extend({method:g("notifications/elicitation/complete"),params:_o}),Ro=y.extend({action:j(["accept","decline","cancel"]),content:Oo(ce=>ce===null?void 0:ce,T(d(),E([d(),b(),A(),_(d())])).optional())}),bo=m({type:g("ref/resource"),uri:d()}),vo=m({type:g("ref/prompt"),name:d()}),Io=a.extend({ref:E([vo,bo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),On=p.extend({method:g("completion/complete"),params:Io}),Co=y.extend({completion:z({values:_(d()).max(100),total:q(b().int()),hasMore:q(A())})}),To=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),ir=p.extend({method:g("roots/list"),params:a.optional()}),Mn=y.extend({roots:_(To)}),ko=f.extend({method:g("notifications/roots/list_changed"),params:h.optional()}),Eo=z({ttl:b().optional(),pollInterval:b().optional()}),Po=j(["working","input_required","completed","failed","cancelled"]),dt=m({taskId:d(),status:Po,ttl:E([b(),Uo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:q(b()),statusMessage:q(d())}),fe=y.extend({task:dt}),Ao=h.merge(dt),qt=f.extend({method:g("notifications/tasks/status"),params:Ao}),sr=p.extend({method:g("tasks/get"),params:a.extend({taskId:d()})}),ar=y.merge(dt),cr=p.extend({method:g("tasks/result"),params:a.extend({taskId:d()})}),Oi=y.loose(),ge=Fe.extend({method:g("tasks/list")}),Z=Ge.extend({tasks:_(dt)}),zt=p.extend({method:g("tasks/cancel"),params:a.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,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:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Be,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:ze,InitializeRequestSchema:$,ServerCapabilitiesSchema:Ae,InitializeResultSchema:Lr,InitializedNotificationSchema:Jt,PingRequestSchema:ot,ProgressSchema:It,ProgressNotificationParamsSchema:Ne,ProgressNotificationSchema:it,PaginatedRequestParamsSchema:Vt,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ge,ResourceContentsSchema:Kt,TextResourceContentsSchema:Wt,BlobResourceContentsSchema:Zt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:Tt,ResourceTemplateSchema:Hr,ListResourcesRequestSchema:Br,ListResourcesResultSchema:Fr,ListResourceTemplatesRequestSchema:st,ListResourceTemplatesResultSchema:Yt,ResourceRequestParamsSchema:kt,ReadResourceRequestParamsSchema:Gr,ReadResourceRequestSchema:Jr,ReadResourceResultSchema:Vr,ResourceListChangedNotificationSchema:Kr,SubscribeRequestParamsSchema:Wr,SubscribeRequestSchema:Zr,UnsubscribeRequestParamsSchema:Yr,UnsubscribeRequestSchema:Xr,ResourceUpdatedNotificationParamsSchema:Qr,ResourceUpdatedNotificationSchema:en,PromptArgumentSchema:tn,PromptSchema:rn,ListPromptsRequestSchema:nn,ListPromptsResultSchema:on,GetPromptRequestParamsSchema:sn,GetPromptRequestSchema:an,TextContentSchema:Et,ImageContentSchema:Pt,AudioContentSchema:At,ToolUseContentSchema:cn,EmbeddedResourceSchema:at,ResourceLinkSchema:dn,ContentBlockSchema:Ee,PromptMessageSchema:Xt,GetPromptResultSchema:Qt,PromptListChangedNotificationSchema:xt,ToolAnnotationsSchema:un,ToolExecutionSchema:er,ToolSchema:Ut,ListToolsRequestSchema:tr,ListToolsResultSchema:rr,CallToolResultSchema:nr,CallToolRequestParamsSchema:ae,CallToolRequestSchema:ln,ToolListChangedNotificationSchema:ho,LoggingLevelSchema:or,SetLevelRequestParamsSchema:pn,SetLevelRequestSchema:mn,LoggingMessageNotificationParamsSchema:hn,LoggingMessageNotificationSchema:fn,ModelHintSchema:gn,ModelPreferencesSchema:yn,ToolChoiceSchema:Sn,ToolResultContentSchema:fo,SamplingContentSchema:_n,SamplingMessageContentBlockSchema:ct,SamplingMessageSchema:wn,CreateMessageRequestParamsSchema:Rn,CreateMessageRequestSchema:bn,CreateMessageResultSchema:vn,CreateMessageResultWithToolsSchema:In,BooleanSchemaSchema:Cn,StringSchemaSchema:Tn,NumberSchemaSchema:kn,UntitledSingleSelectEnumSchemaSchema:En,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:An,SingleSelectEnumSchemaSchema:xn,UntitledMultiSelectEnumSchemaSchema:Ot,TitledMultiSelectEnumSchemaSchema:Mt,MultiSelectEnumSchemaSchema:go,EnumSchemaSchema:yo,PrimitiveSchemaDefinitionSchema:Re,ElicitRequestFormParamsSchema:be,ElicitRequestURLParamsSchema:Un,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:So,ElicitationCompleteNotificationParamsSchema:_o,ElicitationCompleteNotificationSchema:wo,ElicitResultSchema:Ro,ResourceTemplateReferenceSchema:bo,PromptReferenceSchema:vo,CompleteRequestParamsSchema:Io,CompleteRequestSchema:On,CompleteResultSchema:Co,RootSchema:To,ListRootsRequestSchema:ir,ListRootsResultSchema:Mn,RootsListChangedNotificationSchema:ko,TaskCreationParamsSchema:Eo,TaskStatusSchema:Po,TaskSchema:dt,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:Ao,TaskStatusNotificationSchema:qt,GetTaskRequestSchema:sr,GetTaskResultSchema:ar,GetTaskPayloadRequestSchema:cr,GetTaskPayloadResultSchema:Oi,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:zt,CancelTaskResultSchema:y.merge(dt),ClientRequestSchema:E([ot,$,On,mn,an,nn,Br,st,Jr,Zr,Xr,ln,tr,sr,cr,ge,zt]),ClientNotificationSchema:E([I,it,Jt,ko,qt]),ClientResultSchema:E([k,vn,In,Ro,Mn,ar,Z,fe]),ServerRequestSchema:E([ot,bn,So,ir,sr,cr,ge,zt]),ServerNotificationSchema:E([I,it,fn,en,Kr,ho,xt,qt,wo]),ServerResultSchema:E([k,Lr,Co,Qt,on,Fr,Yt,Vr,nr,rr,ar,Z,fe]),CallToolResultWireSchema:M().superRefine((ce,Sg)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let ja of Bl)if(ja in ce){Sg.addIssue({code:"custom",message:`content is required when the body carries '${ja}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Yg).pipe(nr)}}n(Xg,"build$1");var Qg;function ys(){return Qg??=Xg()}n(ys,"buildSchemas2025");function Fl(e){return e.type!=="object"}n(Fl,"isNonObjectJsonSchemaRoot");var ey=new Set(["const","enum","default","examples"]),ty=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Al(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(Al,"establishesNewBase");function ry(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Al(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Pl(e.$schema)&&e.$recursiveAnchor!==!0,o=n((i,s)=>{if(Array.isArray(i))return i.map(u=>o(u,!1));if(i===null||typeof i!="object"||!s&&Al(i.$id))return i;let c={},a=!1;for(let[u,p]of Object.entries(i))s?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:ey.has(u)?c[u]=p:ty.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(ry,"wrapOutputSchemaForLegacy");var Gl={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},Jl={"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},ny={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},Qo;function oi(){if(Qo)return Qo;let e=ys();return Qo={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}},Qo}n(oi,"registryMaps");function oy(){oi()}n(oy,"warmRegistryMaps2025");function Vl(e){return Object.prototype.hasOwnProperty.call(Gl,e)}n(Vl,"hasRequestMethod2025");function Kl(e){return Object.prototype.hasOwnProperty.call(Jl,e)}n(Kl,"hasNotificationMethod2025");function iy(e){return Object.prototype.hasOwnProperty.call(ny,e)}n(iy,"hasResultMethod");function sy(e){return iy(e)?oi().resultSchemas[e]:void 0}n(sy,"getResultSchema");function ay(e){return Vl(e)?oi().requestSchemas[e]:void 0}n(ay,"getRequestSchema");function cy(e){return Kl(e)?oi().notificationSchemas[e]:void 0}n(cy,"getNotificationSchema");var ET=Object.keys(Gl),PT=Object.keys(Jl);function ps(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ps,"isPlainObject$4");function ei(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(ei,"triState$1");var xl={ok:!1,reason:"not-in-era"};function Ul(e){return ps(e)&&ps(e.outputSchema)&&Fl(e.outputSchema)}n(Ul,"toolNeedsLegacyWrap");var Ss={era:"2025-11-25",hasRequestMethod:Vl,hasNotificationMethod:Kl,validateRequest:n((e,t)=>ei(ay(e),t),"validateRequest"),validateResult:n((e,t)=>ei(sy(e),t),"validateResult"),validateNotification:n((e,t)=>ei(cy(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>xl,"validateInputRequest"),validateInputResponse:n(()=>xl,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=ys();return ei(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Hl(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Fl(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(ps(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=>Ul(o))?t:{...t,tools:r.map(o=>Ul(o)?{...o,outputSchema:ry(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function dy(){let e=zi(()=>E([d(),b(),A(),Uo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),i=E([d(),b().int()]),s=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=z({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()}),L=zn(m({applyDefaults:A().optional()}),t),F=Oo(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,zn(m({form:L.optional(),url:t.optional()}),t.optional())),ee=z({list:t.optional(),cancel:t.optional(),requests:z({sampling:z({createMessage:t.optional()}).optional(),elicitation:z({create:t.optional()}).optional()}).optional()}),G=z({list:t.optional(),cancel:t.optional(),requests:z({tools:z({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()}),Be=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:q(b()),message:q(d())}),ze=m({...S.shape,...oe.shape,progressToken:r}),$=k.extend({method:g("notifications/progress"),params:ze}),Ae=S.extend({level:c,logger:d().optional(),data:M()}),Lr=k.extend({method:g("notifications/message"),params:Ae}),Jt=m({uri:d(),mimeType:q(d()),_meta:T(d(),M()).optional()}),ot=Jt.extend({text:d()}),It=Jt.extend({blob:a}),Ne=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:qn.datetime({offset:!0}).optional()}),it=m({...U.shape,...I.shape,uri:d(),description:q(d()),mimeType:q(d()),size:q(b()),annotations:Ne.optional(),_meta:q(z({}))}),Vt=m({...U.shape,...I.shape,uriTemplate:d(),description:q(d()),mimeType:q(d()),annotations:Ne.optional(),_meta:q(z({}))}),Fe=k.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ge=S.extend({uri:d()}),Kt=k.extend({method:g("notifications/resources/updated"),params:Ge}),Wt=m({name:d(),description:q(d()),required:q(A())}),Ct=m({...U.shape,...I.shape,description:q(d()),arguments:q(_(Wt)),_meta:q(z({}))}),Zt=k.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),je=m({type:g("text"),text:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),xe=m({type:g("image"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Tt=m({type:g("audio"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Hr=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),Br=m({type:g("resource"),resource:E([ot,It]),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Fr=it.extend({type:g("resource_link")}),st=E([je,xe,Tt,Fr,Br]),Yt=m({role:s,content:st}),kt=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),Gr=k.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),Jr=m({name:d().optional()}),Vr=m({hints:_(Jr).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Kr=m({mode:j(["auto","required","none"]).optional()}),Wr=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),Zr=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()}),Yr=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Xr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Qr=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),en=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),tn=E([Xr,Qr]),rn=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()}),nn=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()}),on=E([rn,nn]),sn=E([en,tn,on]),an=E([sn,Wr,Zr,Yr]),Et=y.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),an),required:_(d()).optional()}).catchall(M())}),Pt=m({type:g("ref/resource"),uri:d()}),At=m({type:g("ref/prompt"),name:d()}),cn=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),at=V.shape,dn=m({experimental:at.experimental,sampling:at.sampling,elicitation:at.elicitation,roots:at.roots,extensions:at.extensions}),Ee=Be.shape,Xt=m({experimental:Ee.experimental,logging:Ee.logging,completions:Ee.completions,prompts:Ee.prompts,resources:Ee.resources,tools:Ee.tools,extensions:Ee.extensions}),Qt=z({progressToken:r.optional(),[dr]:d(),[Nn]:O.optional(),[lr]:dn,[jn]:c.optional()}),xt=m({...U.shape,...I.shape,description:d().optional(),inputSchema:z({$schema:d().optional(),type:g("object")}),outputSchema:z({$schema:d().optional()}).optional(),annotations:kt.optional(),_meta:T(d(),M()).optional()}),un=m({type:g("tool_result"),toolUseId:d(),content:_(st),structuredContent:M().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),er=E([je,xe,Tt,Hr,un]),Ut=m({role:s,content:E([er,_(er)]),_meta:T(d(),M()).optional()}),tr=d(),rr=z({[ur]:O.optional().catch(void 0)}),nr=rr.optional();function ae(Z){return z({_meta:nr,resultType:tr.default("complete"),...Z})}n(ae,"wireResult");let ln=ae({}),ho=ae({nextCursor:o.optional()}),or=ae({content:_(st),structuredContent:M().optional(),isError:A().optional()}),pn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(xt),nextCursor:o.optional()}),mn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),hn=ae({description:d().optional(),messages:_(Yt)}),fn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(it),nextCursor:o.optional()}),gn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Vt),nextCursor:o.optional()}),yn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([ot,It]))}),Sn=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:A().optional()}).loose()}),fo=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"])}),_n=ae({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Xt,instructions:d().optional()}),ct=m({messages:_(Ut),modelPreferences:Vr.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(xt).optional(),toolChoice:Kr.optional()}),wn=m({method:g("sampling/createMessage"),params:ct}),Rn=m({method:g("roots/list"),params:m({_meta:T(d(),M()).optional()}).optional()}),bn=m({...Ut.shape,model:d(),stopReason:d().optional()}),vn=m({roots:_(cn)}),In=m({action:j(["accept","decline","cancel"]),content:T(d(),E([d(),b(),A(),_(d())])).optional()}),Cn=m({mode:g("url"),message:d(),url:d().url()}),Tn=E([Et,Cn]),kn=m({method:g("elicitation/create"),params:Tn}),En=E([wn,Rn,kn]),Pn=E([bn,vn,In]),An=T(d(),En),xn=T(d(),Pn),Ot=ae({inputRequests:An.optional(),requestState:d().optional()}),Mt={inputResponses:xn.optional(),requestState:d().optional()},go=m({_meta:Qt,...Mt}),yo=z({progressToken:r.optional()});function Re(Z,zt){return m({method:g(Z),params:m({_meta:Qt,...zt})})}n(Re,"wireRequest");function be(Z,zt){return m({method:g(Z),params:m({_meta:yo.optional(),...zt}).optional()})}n(be,"dispatchRequest");let Un={name:d(),arguments:T(d(),M()).optional(),...Mt},Ue={cursor:o.optional()},So=Re("tools/call",Un),_o=Re("tools/list",Ue),wo=Re("prompts/list",Ue),Ro=Re("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Mt}),bo=Re("resources/list",Ue),vo=Re("resources/templates/list",Ue),Io=Re("resources/read",{uri:d(),...Mt}),On={ref:E([At,Pt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},Co=Re("completion/complete",On),To=Re("server/discover",{}),ir=m({toolsListChanged:A().optional(),promptsListChanged:A().optional(),resourcesListChanged:A().optional(),resourceSubscriptions:_(d()).optional()}),Mn={notifications:ir},ko=Re("subscriptions/listen",Mn),Eo=rr.extend({"io.modelcontextprotocol/subscriptionId":i}),Po=z({_meta:Eo,resultType:tr.default("complete")}),dt={"tools/call":be("tools/call",Un),"tools/list":be("tools/list",Ue),"prompts/get":be("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":be("prompts/list",Ue),"resources/list":be("resources/list",Ue),"resources/templates/list":be("resources/templates/list",Ue),"resources/read":be("resources/read",{uri:d()}),"completion/complete":be("completion/complete",On),"server/discover":be("server/discover",{}),"subscriptions/listen":be("subscriptions/listen",Mn)};function fe(Z){return z({_meta:nr,...Z})}n(fe,"liftedResult");let Ao={"tools/call":fe({content:_(st),structuredContent:M().optional(),isError:A().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(xt),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Yt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),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:_(Vt),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([ot,It]))}),"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:Xt,instructions:d().optional()}),"subscriptions/listen":fe({})},qt=z({"io.modelcontextprotocol/subscriptionId":i.optional()}),sr=m({method:g("notifications/subscriptions/acknowledged"),params:m({_meta:qt.optional(),notifications:ir})}),ar=m({_meta:qt.optional(),requestId:i,reason:d().optional()}),cr=m({method:g("notifications/cancelled"),params:ar}),Oi={"notifications/cancelled":cr,"notifications/progress":$,"notifications/message":Lr,"notifications/resources/updated":Kt,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":Gr,"notifications/prompts/list_changed":Zt,"notifications/subscriptions/acknowledged":sr},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:i,RoleSchema:s,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:Be,ProgressSchema:oe,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:$,LoggingMessageNotificationParamsSchema:Ae,LoggingMessageNotificationSchema:Lr,ResourceContentsSchema:Jt,TextResourceContentsSchema:ot,BlobResourceContentsSchema:It,AnnotationsSchema:Ne,ResourceSchema:it,ResourceTemplateSchema:Vt,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:Kt,PromptArgumentSchema:Wt,PromptSchema:Ct,PromptListChangedNotificationSchema:Zt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:Tt,ToolUseContentSchema:Hr,EmbeddedResourceSchema:Br,ResourceLinkSchema:Fr,ContentBlockSchema:st,PromptMessageSchema:Yt,ToolAnnotationsSchema:kt,ToolListChangedNotificationSchema:Gr,ModelHintSchema:Jr,ModelPreferencesSchema:Vr,ToolChoiceSchema:Kr,BooleanSchemaSchema:Wr,StringSchemaSchema:Zr,NumberSchemaSchema:Yr,UntitledSingleSelectEnumSchemaSchema:Xr,TitledSingleSelectEnumSchemaSchema:Qr,LegacyTitledEnumSchemaSchema:en,SingleSelectEnumSchemaSchema:tn,UntitledMultiSelectEnumSchemaSchema:rn,TitledMultiSelectEnumSchemaSchema:nn,MultiSelectEnumSchemaSchema:on,EnumSchemaSchema:sn,PrimitiveSchemaDefinitionSchema:an,ElicitRequestFormParamsSchema:Et,ResourceTemplateReferenceSchema:Pt,PromptReferenceSchema:At,RootSchema:cn,ClientCapabilities2026Schema:dn,ServerCapabilities2026Schema:Xt,RequestMetaEnvelopeSchema:Qt,ToolSchema:xt,ToolResultContentSchema:un,SamplingMessageContentBlockSchema:er,SamplingMessageSchema:Ut,ResultTypeSchema:tr,ResultMetaSchema:rr,ResultSchema:ln,PaginatedResultSchema:ho,CallToolResultSchema:or,ListToolsResultSchema:pn,ListPromptsResultSchema:mn,GetPromptResultSchema:hn,ListResourcesResultSchema:fn,ListResourceTemplatesResultSchema:gn,ReadResourceResultSchema:yn,CompleteResultSchema:Sn,CacheableResultSchema:fo,DiscoverResultSchema:_n,CreateMessageRequestParamsSchema:ct,CreateMessageRequestSchema:wn,ListRootsRequestSchema:Rn,CreateMessageResultSchema:bn,ListRootsResultSchema:vn,ElicitResultSchema:In,ElicitRequestURLParamsSchema:Cn,ElicitRequestParamsSchema:Tn,ElicitRequestSchema:kn,InputRequestSchema:En,InputResponseSchema:Pn,InputRequestsSchema:An,InputResponsesSchema:xn,InputRequiredResultSchema:Ot,InputResponseRequestParamsSchema:go,CallToolRequestSchema:So,ListToolsRequestSchema:_o,ListPromptsRequestSchema:wo,GetPromptRequestSchema:Ro,ListResourcesRequestSchema:bo,ListResourceTemplatesRequestSchema:vo,ReadResourceRequestSchema:Io,CompleteRequestSchema:Co,DiscoverRequestSchema:To,SubscriptionFilterSchema:ir,SubscriptionsListenRequestSchema:ko,SubscriptionsListenResultMetaSchema:Eo,SubscriptionsListenResultSchema:Po,dispatchRequestSchemas:dt,dispatchResultSchemas:Ao,NotificationMetaSchema:qt,SubscriptionsAcknowledgedNotificationSchema:sr,CancelledNotificationParamsSchema:ar,CancelledNotificationSchema:cr,notificationSchemas2026:Oi,JSONRPCResultResponseSchema:ge(ln),CallToolResultResponseSchema:ge(E([or,Ot])),ListToolsResultResponseSchema:ge(pn),ListPromptsResultResponseSchema:ge(mn),GetPromptResultResponseSchema:ge(E([hn,Ot])),ListResourcesResultResponseSchema:ge(fn),ListResourceTemplatesResultResponseSchema:ge(gn),ReadResourceResultResponseSchema:ge(E([yn,Ot])),CompleteResultResponseSchema:ge(Sn),DiscoverResultResponseSchema:ge(_n)}}n(dy,"build");var uy;function mt(){return uy??=dy()}n(mt,"buildSchemas2026");var ly=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function py(e){return ly.includes(e)}n(py,"isCacheableResultMethod");var _s=Symbol("modelcontextprotocol.resultCacheHintFallback");function my(e){return e[_s]}n(my,"cacheHintFallbackOf");function Wl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(Wl,"isValidCacheTtlMs");function Zl(e){return e==="public"||e==="private"}n(Zl,"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})({}),se=class Yl 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",Lt(this,new.target)}static fromError(t,r,o){if(t===P.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new ii(i.elicitations,r)}if(t===P.UnsupportedProtocolVersion&&o){let i=o;if(Array.isArray(i.supported)&&typeof i.requested=="string")return new Ql({supported:i.supported,requested:i.requested},r)}if(t===P.InvalidParams||t===P.ResourceNotFound){let i=o;if(typeof i?.uri=="string"&&(t===P.ResourceNotFound||Object.keys(i).length===1))return new Xl(i.uri,r)}if(t===P.MissingRequiredClientCapability&&o){let i=o;if(i.requiredCapabilities!==null&&typeof i.requiredCapabilities=="object"&&!Array.isArray(i.requiredCapabilities))return new ep({requiredCapabilities:i.requiredCapabilities},r)}return new Yl(t,r,o)}},Xl=class extends se{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}},ii=class extends se{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??[]}},Ql=class extends se{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}},ep=class extends se{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}},hy=0,fy="private",gy=["tools/call","prompts/get","resources/read"];function yy(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||gy.includes(e))return t;throw new se(P.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(yy,"stampResultType");function Sy(e,t){let r=my(t);if(t.resultType!=="complete"||!py(e))return r===void 0?t:vy(t);let o=t,i=Wl(o.ttlMs)?o.ttlMs:Ry(r),s=Zl(o.cacheScope)?o.cacheScope:by(r),c={...o,ttlMs:i,cacheScope:s};return delete c[_s],c}n(Sy,"fillCacheFields");function _y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(_y,"isPlainObject$3");function wy(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ur]:t}}:!_y(r)||r[ur]!==void 0?e:{...e,_meta:{...r,[ur]:t}}}n(wy,"stampServerInfoMeta");function Ry(e){return e!==void 0&&Wl(e.ttlMs)?e.ttlMs:hy}n(Ry,"resolveTtlMs");function by(e){return e!==void 0&&Zl(e.cacheScope)?e.cacheScope:fy}n(by,"resolveCacheScope");function vy(e){let t={...e};return delete t[_s],t}n(vy,"stripCacheHintFallback");var Iy=["elicitation/create","sampling/createMessage","roots/list"],ti;function ws(){if(ti)return ti;let e=mt();return ti={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:z({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ti}n(ws,"inputSchemaMaps");function Cy(){ws()}n(Cy,"warmInputSchemaMaps2026");function tp(e){return Iy.includes(e)}n(tp,"isInputRequestMethod2026");function ss(e){return tp(e)?ws().request[e]:void 0}n(ss,"getInputRequestSchema2026");function Ty(e){return tp(e)?ws().response[e]:void 0}n(Ty,"getInputResponseSchema2026");var Rs={"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},rp={"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 np(e){return Object.prototype.hasOwnProperty.call(Rs,e)}n(np,"hasRequestMethod2026");function op(e){return Object.prototype.hasOwnProperty.call(rp,e)}n(op,"hasNotificationMethod2026");function ky(e){return Object.prototype.hasOwnProperty.call(Rs,e)}n(ky,"hasResultMethod2026");function Ey(e){return np(e)?mt().dispatchRequestSchemas[e]:void 0}n(Ey,"getRequestSchema2026");function Py(e){return ky(e)?mt().dispatchResultSchemas[e]:void 0}n(Py,"getResultSchema2026");function Ay(e){return op(e)?mt().notificationSchemas2026[e]:void 0}n(Ay,"getNotificationSchema2026");var AT=Object.keys(Rs),xT=Object.keys(rp);function Kn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Kn,"isPlainObject$2");function Jn(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(Jn,"triState");var xy={ok:!1,reason:"not-in-era"},Uy=[dr,lr];function Oy(e,t){let r=t,o=!1,i=n(()=>(o||(r={...r},o=!0),r),"copy"),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Kn(a)&&"execution"in a)&&(i().tools=s.map(a=>{if(!Kn(a)||!("execution"in a))return a;let u={...a};return delete u.execution,u}));let c=t.capabilities;if(Kn(c)&&"tasks"in c){let a={...c};delete a.tasks,i().capabilities=a}return r}n(Oy,"enforceDeletedFields");var bs={era:"2026-07-28",hasRequestMethod:np,hasNotificationMethod:op,hasInputRequestMethod:n(e=>ss(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>Jn(Ey(e),t),"validateRequest"),validateResult:n((e,t)=>Jn(Py(e),t),"validateResult"),validateNotification:n((e,t)=>Jn(Ay(e),t),"validateNotification"),validateInputRequest:n((e,t)=>Jn(ss(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>Jn(Ty(e),t),"validateInputResponse"),samplingResultVariant:n(()=>xy,"samplingResultVariant"),outboundEnvelope(e){return{[dr]:e.protocolVersion,[Nn]:e.clientInfo,[lr]:e.clientCapabilities,...e.logLevel!==void 0&&{[jn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Uy)o in e||t.push({key:o,problem:"missing"});let r=mt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let i=o.path.map(String),s=i.length>0?i.join("."):"_meta";i.length===1&&t.some(c=>c.key===s&&c.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>Hl(e),"projectCallToolResult"),inputRequestSchema:ss,decodeResult(e,t){if(!Kn(t))return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new re(ie.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(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let c=t.inputRequests,a=Kn(c)?c:{},u=t.requestState;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new re(ie.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(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=ip(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let c=i.safeParse(t);if(!c.success)return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: ${c.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return wy(Sy(e,yy(e,Oy(e,t))),r)},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=mt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},ri;function ip(){if(ri)return ri;let e=mt();return ri={"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},ri}n(ip,"getWireResultSchemas");function My(){ip()}n(My,"warmWireResultSchemas2026");var vs="2026-07-28";function Zn(e){return e!==void 0&&Ll(e)?bs:Ss}n(Zn,"codecForVersion");function Ol(e){return e.revision!==void 0?Zn(e.revision).era:e.era==="modern"?bs.era:Ss.era}n(Ol,"classifiedWireEra");function as(e){return sp.some(t=>t.hasRequestMethod(e))}n(as,"isSpecRequestMethod");function cs(e){return sp.some(t=>t.hasNotificationMethod(e))}n(cs,"isSpecNotificationMethod");var sp=[Ss,bs],qy=kl({AnnotationsSchema:n(()=>Nc,"AnnotationsSchema"),AudioContentSchema:n(()=>gd,"AudioContentSchema"),BaseMetadataSchema:n(()=>fc,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>tc,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>qc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Bi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>xd,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Ud,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Pd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>Cu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>Tu,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>lc,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>pc,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>_c,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>Eu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>ku,"ClientRequestSchema"),ClientResultSchema:n(()=>Pu,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>yc,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>Ad,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>su,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>au,"CompleteRequestSchema"),CompleteResultSchema:n(()=>cu,"CompleteResultSchema"),ContentBlockSchema:n(()=>wd,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Jd,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Vd,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Kd,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>Wd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>gu,"CreateTaskResultSchema"),CursorSchema:n(()=>Ya,"CursorSchema"),DiscoverRequestSchema:n(()=>Cc,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Li,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>jo,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Qd,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>eu,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Do,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>nu,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>tu,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>ru,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Sd,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>uc,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Xd,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>pd,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>md,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>bd,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>Ru,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>bu,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>_u,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>wu,"GetTaskResultSchema"),IconSchema:n(()=>mc,"IconSchema"),IconsSchema:n(()=>hc,"IconsSchema"),ImageContentSchema:n(()=>fd,"ImageContentSchema"),ImplementationSchema:n(()=>gc,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>wc,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>Rc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>vc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>Ic,"InitializedNotificationSchema"),JSONArraySchema:n(()=>Wa,"JSONArraySchema"),JSONObjectSchema:n(()=>Ka,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Dn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>$i,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>ji,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>jt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>dc,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Di,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Va,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Ji,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>Hi,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>ud,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>ld,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>Hc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>Bc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>$c,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Lc,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>uu,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>lu,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>vu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>Iu,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>kd,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>Ed,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>Md,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Nd,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>jd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Dd,"ModelHintSchema"),ModelPreferencesSchema:n(()=>$d,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Yd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>ic,"NotificationSchema"),NotificationsParamsSchema:n(()=>oc,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>No,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>Ac,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>xc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Uc,"PaginatedResultSchema"),PingRequestSchema:n(()=>Tc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>Wi,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>Ec,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Pc,"ProgressNotificationSchema"),ProgressSchema:n(()=>kc,"ProgressSchema"),ProgressTokenSchema:n(()=>Za,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>cd,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>vd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>Rd,"PromptMessageSchema"),PromptReferenceSchema:n(()=>iu,"PromptReferenceSchema"),PromptSchema:n(()=>dd,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Gc,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Jc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Vc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Qa,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>cc,"RequestIdSchema"),RequestMetaSchema:n(()=>ec,"RequestMetaSchema"),RequestSchema:n(()=>nc,"RequestSchema"),ResourceContentsSchema:n(()=>Oc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>_d,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Kc,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Fc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>jc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>ou,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Dc,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>sd,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>ad,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>sc,"ResultMetaObjectSchema"),ResultSchema:n(()=>ac,"ResultSchema"),RoleSchema:n(()=>zc,"RoleSchema"),RootSchema:n(()=>du,"RootSchema"),RootsListChangedNotificationSchema:n(()=>pu,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>Bd,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Fd,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Gd,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>bc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>xu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>Au,"ServerRequestSchema"),ServerResultSchema:n(()=>Uu,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Sc,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>qd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>zd,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Zd,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>zo,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>Wc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Zc,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Qc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>rd,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>nd,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>ed,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>td,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>od,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>id,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>rc,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>mu,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>Xa,"TaskMetadataSchema"),TaskSchema:n(()=>fu,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>yu,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Su,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>hu,"TaskStatusSchema"),TextContentSchema:n(()=>hd,"TextContentSchema"),TextResourceContentsSchema:n(()=>Mc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Ki,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Gi,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>Id,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Ld,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>Cd,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>Od,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>Hd,"ToolResultContentSchema"),ToolSchema:n(()=>Td,"ToolSchema"),ToolUseContentSchema:n(()=>yd,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Yc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Xc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Vi,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Fi,"UntitledSingleSelectEnumSchemaSchema")});var ap=n(e=>jt.safeParse(e).success,"isJSONRPCRequest"),cp=n(e=>ji.safeParse(e).success,"isJSONRPCNotification"),ms=n(e=>Di.safeParse(e).success,"isJSONRPCResultResponse"),dp=n(e=>Dn.safeParse(e).success,"isJSONRPCErrorResponse");var Wn=-32020,UT=[{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:[Wn,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:[Wn],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:[Wn],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."}],OT={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Wn]:400};function Is(e,t){return $a(e,t)}n(Is,"parseSchema");function Vn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Vn,"shapeKeys");function hs(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(hs,"isStandardSchema");var Ml=!1,fs="draft-2020-12";function zy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:fs});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().");Ml||(Ml=!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=Mi(e,{target:fs,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:up(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(zy,"standardSchemaToJsonSchema");function up(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"||up(o)))}return!1}n(up,"isProvablyObjectShapedRoot");function Ny(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Ny,"formatIssue");async function ds(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Ny(o)).join(", ")}:{success:!0,data:r.value}}n(ds,"validateStandardSchema");function jy(e){let t=Mi(e,{target:fs,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(jy,"zodEmittedPattern");var Dy=/\\\.\\d\{(\d+)\}/;function $y(e){let t=Dy.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(i=>r.map(s=>qn.datetime({local:o,offset:i,precision:s}))))}n($y,"datetimeReferenceSchemas");function Ly(e,t){let r;switch(e){case"email":r=[La()];break;case"uri":r=[Ha()];break;case"date":r=[qn.date()];break;case"date-time":r=$y(t);break}return new Set(r.map(o=>jy(o)).filter(o=>o!==void 0))}n(Ly,"referencePatternsForFormat");function Hy(e,t,r){return r!=="zod"?!0:Ly(e,t).has(t)}n(Hy,"isLibraryFormatPattern");function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Yn,"isJsonObject");function By(e){try{return zy(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new se(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(By,"convertStandardElicitationSchema");var Fy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Cs(e){return Fy.has(e)||e.startsWith("x-")}n(Cs,"isAnnotationOnlyJsonSchemaKeyword");var Gy=new Set(["$schema",...Object.keys(jo.shape.requestedSchema.shape)]),ql={string:Vn([zo,Fi,Gi,Ji]),number:Vn([No]),integer:Vn([No]),boolean:Vn([Bi]),array:Vn([Vi,Ki])},Jy=new Set(zo.shape.format.unwrap().options);function Vy(e,t,r,o){if(!Yn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(ql,e.type)?ql[e.type]:void 0;if(i===void 0)return e;let s={};for(let[c,a]of Object.entries(e))i.has(c)||Cs(c)?s[c]=a:c==="pattern"&&e.type==="string"&&typeof e.format=="string"?Jy.has(e.format)?(typeof a!="string"||!Hy(e.format,a,r))&&o.push(`${t}.${c}`):s[c]=a:o.push(`${t}.${c}`);return s}n(Vy,"walkProperty");function Ky(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Yn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([c,a])=>[c,Vy(a,`properties.${c}`,t,o)])):Gy.has(i)?r[i]=s:Cs(i)||o.push(i);if(o.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(Ky,"walkRequestedSchema");function Wy(e,t){if(!Yn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Is(Wi,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(Wy,"describeUnsupportedProperties");function gs(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>gs(o,t[i],`${r}[${i}]`)):!Yn(e)||!Yn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?gs(i,t[o],s):Cs(o)?[]:[s]})}n(gs,"findDroppedConstraintPaths");function Zy(e){if(!hs(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Ky(By(e.requestedSchema),t),o=Is(jo.shape.requestedSchema,r);if(!o.success)throw new se(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Wy(r,o.error.message)}`);let i=gs(r,o.data);if(i.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(", ")}`);let s=(o.data.required??[]).filter(c=>!Object.prototype.hasOwnProperty.call(o.data.properties,c));if(s.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Zy,"normalizeElicitInputParams");function Yy(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(Yy,"buildInputRequired");var MT=Object.assign(Yy,{elicit(e){try{return{method:"elicitation/create",params:Zy(e)}}catch(t){throw t instanceof se?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 Xy=["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"],Qy={IdJagTokenExchangeResponseSchema:Zi,OAuthClientInformationFullSchema:Dt,OAuthClientInformationSchema:$n,OAuthClientMetadataSchema:Mu,OAuthClientRegistrationErrorSchema:qu,OAuthErrorResponseSchema:$o,OAuthMetadataSchema:hr,OAuthProtectedResourceMetadataSchema:mr,OAuthTokenRevocationRequestSchema:zu,OAuthTokensSchema:ut,OpenIdProviderDiscoveryMetadataSchema:fr,OpenIdProviderMetadataSchema:Ou},lp={},pp={};function mp(e,t){let r=e.slice(0,-6);lp[r]=t,pp[r]=o=>t.safeParse(o).success}n(mp,"register");for(let e of Xy)mp(e,qy[e]);for(let[e,t]of Object.entries(Qy))mp(e,t);var eS=Object.freeze(lp),tS=Object.freeze(pp);function rS(e){switch(e){case"initialize":case"notifications/initialized":return Zn(void 0);case"server/discover":return Zn(vs);default:return}}n(rS,"bootstrapOutboundCodec");var hp=6e4,nS=[dr,Nn,lr,jn],oS=["inputResponses","requestState"];function zl(e,t){let r=e.params;if(!us(r))return{message:e,lifted:{}};let o=r._meta,i=us(o)?nS.filter(u=>u in o):[],s=t==="request"?oS.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let c={},a={...r};if(i.length>0&&us(o)){let u={},p={...o};for(let h of i)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 s)u==="inputResponses"&&(c.inputResponses=a[u]),u==="requestState"&&(c.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:c}}n(zl,"liftWireOnlyMaterial");function Nl(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 i=e.validateResult(t,o);return i.ok?{value:i.value}:{issues:[{message:i.reason==="invalid"?i.message:`not-in-era: ${t}`}]}}}}}n(Nl,"codecResultValidator");function fp(e){return()=>e}n(fp,"requestStateAccessor");var iS=fp(void 0),sS,aS=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{sS=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ni,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(ie.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,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,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(ie.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=i=>{r?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),ms(i)||dp(i)?this._onresponse(i):ap(i)?this._onrequest(i,s):cp(i)?this._onnotification(i,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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(ie.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}=zl(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let c=Ol(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(cs(r.method)&&!o.hasNotificationMethod(r.method))return;let i=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;i===void 0&&s===void 0||Promise.resolve().then(()=>i===void 0?s(r):i(r,o)).catch(c=>this._onerror(new Error(`Uncaught error in notification handler: ${c}`)))}_onrequest(e,t){let{message:r,lifted:o}=zl(e,"request"),i=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 s=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}}};s?.send(O).catch(L=>this._onerror(new Error(`Failed to send an error response: ${L}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=Ol(t.classification);if(w!==i.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${i.era}`));let I=t.classification.revision??w;c(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${I}`,{supported:this._supportedProtocolVersions,requested:I});return}}if(as(r.method)&&!i.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=i.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:cS(o.inputResponses),S={sessionId:s?.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?iS:fp(o.requestState),signal:f.signal,send:n(((w,I,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),hs(I))return h(w,I,U);let L=Nl(O,w.method);if(L===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,L,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=i.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 s?.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:i.encodeErrorCode(I),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await s?.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),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}i(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),ms(e)?r(e):r(se.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),hs(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=Nl(o,e.method);if(i===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,i,t)}_negotiatedWireCodec(){return Zn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=rS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(as(t)&&!e.hasRequestMethod(t))throw new re(ie.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:i,resumptionToken:s,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(ie.RequestTimeout,String(G))}let k=e.era===vs&&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,L=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:i,resumptionToken:s,onresumptiontoken:c}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),y(G instanceof re?G:new re(ie.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(dS(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((ze,$)=>this._requestWithSchemaViaCodec(e,ze===void 0?{method:t.method}:{method:t.method,params:ze},r,$),"retry")};return f(this._resolveNonCompleteResult(V,oe))}let Be=V.result;ds(r,Be).then(oe=>{oe.success?f(oe.data):y(new re(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},y)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??hp,ee=n(()=>L(new re(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,ee,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,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(ie.NotConnected,"Not connected");if(cs(t.method)&&!e.hasNotificationMethod(t.method))throw new re(ie.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(i=>this._onerror(i))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!as(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let c=this._negotiatedWireCodec(),a=c.validateRequest(e,i);if(!a.ok&&a.reason==="not-in-era"&&(a=c.validateInputRequest(e,i)),!a.ok)throw a.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let c=await ds(t.params,{...i.params});if(!c.success)throw new se(P.InvalidParams,`Invalid params for ${e}: ${c.error}`);return r(c.data,s)},"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(!cs(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,i)=>{let s=i.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let i=await ds(t.params,{...o.params});if(!i.success)throw new se(P.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await r(i.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(us,"isPlainObject$1");function jl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(jl,"isPlainObject");function cS(e){let t={},r=[];if(!jl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!jl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(cS,"partitionInputResponses");function dS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(dS,"manualInputRequiredValue");var uS=Tl((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=i;function i(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?s(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(i,"parse");function s(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(s,"getcontenttype");function c(a){this.parameters=Object.create(null),this.type=a}n(c,"ContentType")})),qT=El(uS(),1);var lS=10*1024*1024;function Ts(){ys(),mt(),oy(),Cy(),My()}n(Ts,"preloadSchemas");var VT=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 pS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,mS=[0,31,28,31,30,31,30,31,31,30,31,30,31],hS=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,fS=/^(?=.{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,gS=/^(?:[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,yS=/^(?:(?:[^\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,SS=/^(?:(?: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,_S=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,RS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,bS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,vS=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(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),IS=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,CS=/^((([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,TS=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 $e(e){return e.test.bind(e)}n($e,"bind");var KT={date:gp,time:yp.bind(void 0,!1),"date-time":PS,duration:TS,uri:US,"uri-reference":$e(gS),"uri-template":$e(yS),url:$e(SS),email:vS,hostname:$e(fS),ipv4:$e(IS),ipv6:$e(CS),regex:MS,uuid:$e(_S),"json-pointer":$e(wS),"json-pointer-uri-fragment":$e(RS),"relative-json-pointer":$e(bS)};function kS(e){return e%4===0&&(e%100!==0||e%400===0)}n(kS,"isLeapYear");function gp(e){let t=e.match(pS);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&kS(r)?29:mS[o])}n(gp,"date");function yp(e,t){let r=t.match(hS);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],c=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||c)}n(yp,"time");var ES=/t|\s/i;function PS(e){let t=e.split(ES);return t.length==2&&gp(t[0])&&yp(!0,t[1])}n(PS,"date_time");var AS=/\/|:/,xS=/^(?:[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 US(e){return AS.test(e)&&xS.test(e)}n(US,"uri");var OS=/[^\\]\\Z/;function MS(e){if(OS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(MS,"regex");Ts();var Sp=!1;var ks;ks=globalThis.crypto;async function zS(e){return(await ks).getRandomValues(new Uint8Array(e))}n(zS,"getRandomValues");async function NS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await zS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(NS,"random");async function jS(e){return await NS(e)}n(jS,"generateVerifier");async function DS(e){let t=await(await ks).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(DS,"generateChallenge");async function Es(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await jS(e),r=await DS(t);return{code_verifier:t,code_challenge:r}}n(Es,"pkceChallenge");var Qn=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,Lt(this,new.target)}},Xn=class extends Qn{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}},Os=class extends Qn{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}},ai=class extends Qn{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}},Ps=class extends Qn{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}},qk=class extends Qn{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 _p(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):bp(e.issuer,t)?e:void 0}n(_p,"discardIfIssuerMismatch");function bp(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(bp,"issuersMatch");var zk=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",Lt(this,new.target)}};function vp(e){return e?.authorization_response_iss_parameter_supported===!0}n(vp,"isIssParameterSupported");function Ip({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Xn("authorization_response",t,void 0);return}if(e!==t)throw new Xn("authorization_response",t,e)}}n(Ip,"validateAuthorizationResponseIssuer");function $S(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n($S,"isClientAuthMethod");var As="code",xs="S256";function LS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&$S(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(LS,"selectClientAuthMethod");function HS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":BS(i,s,r);return;case"client_secret_post":FS(i,s,o);return;case"none":GS(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(HS,"applyClientAuthentication");function BS(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(BS,"applyBasicAuth");function FS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(FS,"applyPostAuth");function GS(e,t){t.set("client_id",e)}n(GS,"applyPublicAuth");function Cp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Cp,"isLoopbackHost");function JS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Cp(t.hostname))throw new ai(t.href);return t}n(JS,"assertSecureTokenEndpoint");function VS(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Cp(r.hostname))return"native"}return"web"}n(VS,"deriveApplicationType");function KS(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??VS(t.redirect_uris)}}n(KS,"resolveClientMetadata");async function wp(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=$o.parse(JSON.parse(r));return ht.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ht(ue.ServerError,i)}}n(wp,"parseErrorResponse");async function Ms(e,t){try{return await Us(e,t)}catch(r){if(r instanceof ht){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Us(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await Us(e,t)}throw r}}n(Ms,"auth");function WS(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:i}=e,s=t||r?.scopes_supported?.join(" ")||i.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&i.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}n(WS,"determineScope");async function Us(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:c,skipIssuerMetadataValidation:a,forceReauthorization:u}){let p=KS(e),h=await e.discoveryState?.(),f,y,S,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(y=h.authorizationServerUrl,f=h.resourceMetadata,S=h.authorizationServerMetadata??await Pp(y,{fetchFn:c,skipIssuerValidation:a}),!f)try{f=await kp(t,{resourceMetadataUrl:w},c)}catch($){if($ instanceof TypeError)throw $}(S!==h.authorizationServerMetadata||f!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S})}else{let $=await t_(t,{resourceMetadataUrl:w,fetchFn:c,skipIssuerMetadataValidation:a});y=$.authorizationServerUrl,S=$.authorizationServerMetadata,f=$.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 $=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if($===void 0){if(e.saveDiscoveryState!==void 0)throw new Ps("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(!bp($,I))throw new Ps($,I)}k&&await e.saveDiscoveryState?.(k);let O=await ZS(t,e,f);O&&await e.saveResourceUrl?.(String(O));let L=WS({requestedScope:i,resourceMetadata:f,authServerMetadata:S,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),ee=_p(F,I,{canPersistStamp:e.saveClientInformation!==void 0});if(ee===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new Ps(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 $=S?.client_id_metadata_document_supported===!0,Ae=e.clientMetadataUrl;if(Ae&&!qs(Ae))throw new ht(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ae}`);if($&&Ae)ee={client_id:Ae,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 s_(y,{metadata:S,clientMetadata:p,scope:L,fetchFn:c}),issuer:I},await e.saveClientInformation(ee,U)}}let G=!e.redirectUrl;if(r!==void 0||G){r!==void 0&&Ip({iss:o,expectedIssuer:S?.issuer,issParameterSupported:vp(S)});let $=await i_(e,y,{metadata:S,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:c});return await e.saveTokens({...$,issuer:I},U),"AUTHORIZED"}let V=_p(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 $=await o_(y,{metadata:S,clientInformation:ee,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:c});return await e.saveTokens({...$,issuer:I},U),"AUTHORIZED"}catch($){if($ instanceof ai||!(!($ instanceof ht)||$.code===ue.ServerError))throw $}let Be=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:ze}=await r_(y,{metadata:S,clientInformation:ee,state:Be,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(ze),await e.redirectToAuthorization(oe),"REDIRECT"}n(Us,"authInternal");function qs(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(qs,"isHttpsUrl");async function ZS(e,t,r){let o=$l(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ni({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(ZS,"selectResourceURL");function Tp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=si(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let c=si(e,"scope")||void 0,a=si(e,"error")||void 0,u=si(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:c,error:a,errorDescription:u}}n(Tp,"extractWWWAuthenticateParams");function si(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=r.match(o);if(i){let s=i[1]||i[2];if(s)return s}return null}n(si,"extractFieldFromWwwAuth");async function kp(e,t,r=fetch){let o=await QS(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 mr.parse(await o.json())}n(kp,"discoverOAuthProtectedResourceMetadata");async function Ep(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!Sp)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(Ep,"fetchWithCorsRetry");function YS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(YS,"buildWellKnownPath");async function Rp(e,t,r=fetch){return await Ep(e,{"MCP-Protocol-Version":t},r)}n(Rp,"tryMetadataDiscovery");function XS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(XS,"shouldAttemptFallback");async function QS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??qo,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=YS(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let a=await Rp(c,s,r);return!o?.metadataUrl&&XS(a,i.pathname)&&(a=await Rp(new URL(`/.well-known/${t}`,i),s,r)),a}n(QS,"discoverMetadataWithFallback");function e_(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 i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(e_,"buildDiscoveryUrls");async function Pp(e,{fetchFn:t=fetch,protocolVersion:r=qo,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=e_(e);for(let{url:c,type:a}of s){let u=await Ep(c,i,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"?hr.parse(await u.json()):fr.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 Xn("metadata",h,p.issuer)}return p}}n(Pp,"discoverAuthorizationServerMetadata");async function t_(e,t){let r,o;try{r=await kp(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let i=await Pp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(t_,"discoverOAuthServerInfo");async function r_(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:c}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(As))throw new Error(`Incompatible auth server: does not support response type ${As}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(xs))throw new Error(`Incompatible auth server: does not support code challenge method ${xs}`)}else a=new URL("/authorize",e);let u=await Es(),p=u.code_verifier,h=u.code_challenge;return a.searchParams.set("response_type",As),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",xs),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),i&&a.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),c&&a.searchParams.set("resource",c.href),{authorizationUrl:a,codeVerifier:p}}n(r_,"startAuthorization");function n_(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(n_,"prepareAuthorizationCodeRequest");async function Ap(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:c}){let a=JS(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",s.href),i?await i(u,r,a,t):o&&HS(LS(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 wp(p);let h=await p.json();try{return ut.parse(h)}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await wp(JSON.stringify(h)):f}}n(Ap,"executeTokenRequest");async function o_(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:c}){return{refresh_token:o,...await Ap(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:c})}}n(o_,"refreshAuthorization");async function i_(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:c,fetchFn:a}={}){i!==void 0&&Ip({iss:s,expectedIssuer:r?.issuer,issParameterSupported:vp(r)});let u=c??e.clientMetadata.scope,p;if(e.prepareTokenRequest&&(p=await e.prepareTokenRequest(u)),!p){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");p=n_(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return Ap(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(i_,"fetchToken");async function s_(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let c={...r,...o===void 0?{}:{scope:o}},a=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Os({status:a.status,body:await a.text(),submittedMetadata:c});return Dt.parse(await a.json())}n(s_,"registerClient");var Nk=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,Lt(this,new.target)}};function a_(e){let t=jt.safeParse(e);return t.success?t.data.id:void 0}n(a_,"parseJsonRpcRequestId");function xp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return a_(t)}catch{return}}n(xp,"readJsonRpcRequestIdFromBody");function ci(e){return Dn.parse({jsonrpc:pr,...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(ci,"jsonRpcErrorResponse");function Up(e){return new ii([Do.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Up,"urlElicitationRequiredError");var ui=l.record(l.string(),l.unknown()),c_=l.record(l.string(),l.unknown()),gt=l.array(l.string().min(1)).min(1).optional(),d_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:c_.optional(),_meta:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),u_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),l_=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:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),p_=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:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),m_=l.array(l.union([l.string(),d_])),h_=l.array(l.union([l.string(),u_])),f_=l.array(l.union([l.string(),l_])),g_=l.array(l.union([l.string(),p_])),y_=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),S_=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:y_.optional()}).strict(),__=l.object({tools:m_.optional(),prompts:h_.optional(),resources:f_.optional(),resourceTemplates:g_.optional(),accessControl:S_.optional()}).strict(),ft=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function w_(e,t){return Du(__,e,`MCP capability filter policy "${t}"`)}n(w_,"parseMcpCapabilityFilterOptions");function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(_e,"isRecord");function eo(e){return typeof e.method=="string"?e.method:void 0}n(eo,"messageMethod");function Op(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Op,"correlationKey");function Mp(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Mp,"asStringArray");function qp(e,t){if(!_e(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>_e(o)?o[i]: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(qp,"readClaimValues");function js(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:Mp(e.roles),groups:Mp(e.groups),public:e.public===!0}}n(js,"normalizeEntry");function R_(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(s=>t.has(s))||i.some(s=>r.has(s))}n(R_,"isCallerAllowed");function di(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let c=js(s,t);c!==void 0&&R_(c,r,o)&&i.push(c.key)}return i}n(di,"allowedKeys");var jp=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(qp(e.user?.data,o)),c=new Set(qp(e.user?.data,i));return{tools:di(r.tools,"name",s,c),prompts:di(r.prompts,"name",s,c),resources:di(r.resources,"uri",s,c),resourceTemplates:di(r.resourceTemplates,"uriTemplate",s,c)}},"claimsCapabilityResolver");function b_(e,t){let r=[];for(let o of ft){let i=e[o.option];if(i!==void 0)for(let s of i){let c=js(s,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(b_,"assertNoConflictingMarkup");function v_(e,t){let r=[];for(let o of ft){let i=e[o.option];if(i!==void 0)for(let s of i){let c=js(s,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(v_,"assertNoMarkup");function I_(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 i=o;return async(s,c,a)=>{let u=await i(s,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(I_,"buildCustomResolver");function C_(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 I_(r,t)}if(o==="rolesAndGroups")return b_(e,t),jp;v_(e,t)}n(C_,"buildCapabilityResolver");function T_(e){let t={};for(let r of ft){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let c=x_(s,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(T_,"buildProjectionMaps");function zs(e){return e===void 0?void 0:ft.find(t=>t.listMethod===e)}n(zs,"findListRule");function k_(e){return e===void 0?void 0:ft.find(t=>t.directMethods.includes(e))}n(k_,"findDirectRule");function E_(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(E_,"directCapabilityAccess");function P_(e){let t=k_(eo(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(P_,"rawDirectCapabilityAccess");function A_(e){return Response.json(ci({...e==null?{}:{id:e},error:{code:P.MethodNotFound,message:"Method not found"}}))}n(A_,"methodNotFoundResponse");function x_(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(x_,"buildProjection");function zp(e){let t=e.base[e.property],r=e.overlay[e.property];return _e(r)?_e(t)?{...t,...r}:r:t}n(zp,"mergeRecordProperty");function U_(e,t){let r={...e,...t.overlay},o=zp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=zp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(U_,"applyProjection");function Np(e,t,r,o){if(!_e(e))return e;let i=e.result;if(!_e(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(c=>_e(c)&&typeof c[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.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?[]:[U_(c,u)]})}}}n(Np,"filterAndProjectItems");function O_(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let p of t.messages){let h=zs(eo(p)),f=h===void 0?void 0:Op(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=Op(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:Np(p,f,y,i?.[f.option])})}if(t.shape!=="single"||!_e(r)||"error"in r)return r;let s=t.messages[0],c=zs(s===void 0?void 0:eo(s)),a=c===void 0?void 0:o[c.option];return c===void 0||a===void 0?r:Np(r,c,a,i?.[c.option])}n(O_,"filterResponseBody");function M_(e){return e.headers.get("content-type")?.includes("json")??!1}n(M_,"isJsonResponse");var Ns=class extends Mo{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=w_(t,r);super(o,r),this.#r=r,this.#e=T_(o),this.#t=C_(o,r)}async handler(t,r){let o=await Cl(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let c of o.messages){let a=c.type==="request"?E_(c):P_(c);if(a===void 0)continue;let u=this.#e[a.option];if(u===void 0)continue;let p=i?.[a.option];if(!u.has(a.target)||p!==void 0&&!p.has(a.target))return A_(c.type==="request"?c.id:c.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async c=>{if(!M_(c))return c;let a;try{a=await c.clone().json()}catch{return c}let u=O_({envelope:o,responseBody:a,projectionMaps:s,allowedSets:i});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=eo(r);return o===void 0?!1:ft.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#o(t){return t.messages.some(r=>{let o=zs(eo(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#i(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=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 ft)this.#e[u.option]!==void 0&&(a[u.option]=new Set);return a}let s={};for(let c of ft){let a=this.#e[c.option];if(a===void 0)continue;let u=i[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);s[c.option]=p}return s}};var Ds="zuplo.com",q_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),z_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Dp(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Dp,"s2FaviconHref");function N_(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(N_,"strictFaviconHref");var li=Dp(Ds);function $s(e){let t=e.toLowerCase();return t===Ds||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Dp(Ds):N_(e)}n($s,"resolveIconHref");function j_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(j_,"hostnameFromHost");function D_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(D_,"isLocalOrAddressHost");function $_(e){let t=j_(e).toLowerCase().replace(/\.$/,"");if(D_(t)||z_.some(s=>t===s.slice(1)||t.endsWith(s)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=q_.has(o)?3:2;return r.slice(-i).join(".")}n($_,"inferFaviconDomain");function Ls(e){return{src:$s($_(e)),mimeType:"image/png",sizes:["128x128"]}}n(Ls,"resolveMcpFaviconIcon");function pi(e){try{return Ls(new URL(e).host)}catch{return}}n(pi,"resolveMcpFaviconIconFromUrl");function yt(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(yt,"getUpstreamServerConfig");function mi(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(mi,"getUpstreamAuthConfig");function Tr(e,t){let r=mi({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(Tr,"requireUpstreamOAuthConfig");function $p(e,t){let r=mi({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($p,"requireUpstreamIdJagConfig");function Lp(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(Lp,"mergeAbortSignals");async function L_(e){try{await e.cancel()}catch{}}n(L_,"cancelReader");async function hi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,s=await r.read();for(;!s.done;){let u=s.value;if(i+=u.byteLength,i>t.maxBytes)throw await L_(r),t.createLimitError();o.push(u),s=await r.read()}let c=new Uint8Array(i),a=0;for(let u of o)c.set(u,a),a+=u.byteLength;return c}n(hi,"readBoundedByteStream");var H_=2,B_=1024*1024,F_=1e4,G_=new Set([301,302,303,307,308]),J_=["authorization","proxy-authorization","cookie","cookie2"];function Hs(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Hs,"readRequestUrl");function kr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(kr,"readRequestMethod");function V_(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}})}n(V_,"assertContentLengthWithinLimit");async function K_(e,t,r){return V_(e,t,r),hi(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}}),"createLimitError")})}n(K_,"readBoundedResponseBody");function W_(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(W_,"responseFromBufferedBody");function Z_(e,t){if(!G_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Z_,"resolveRedirectUrl");function Hp(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(Hp,"validateOutboundUrl");function Y_(e,t){throw e instanceof v&&Ho(e.extensionMembers?.[C])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[C]:t}},{cause:e})}n(Y_,"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,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&pe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(to,"logOutboundFailure");async function X_(e,t,r,o,i,s,c){let a=kr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";to(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:a,host:te(s),error:u,extra:{abortReason:c()}}),Y_(u,i)}}n(X_,"fetchWithNormalizedError");function Q_(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(Q_,"assertRedirectAllowed");function ew(e,t){let r=new Headers(e);for(let o of J_)r.delete(o);for(let o of t)r.delete(o);return r}n(ew,"stripCrossOriginHeaders");function tw(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=ew(e.headers,i)),s}n(tw,"buildRedirectInit");function rw(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(rw,"buildInitialRequestInit");function nw(e){let t=kr(e.currentInput,e.currentInit);Q_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Hp(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:tw(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(nw,"followRedirect");async function Bs(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??H_,s=r.maxResponseBytes??B_,c=r.timeoutMs??F_,a=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,f=Lp(h,t.signal),y=!1,S=setTimeout(()=>{y=!0,h.abort()},c),k=e,w=rw(e,t,h.signal),I;try{I=Hp(Hs(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw to(p,{event:"outbound_url_blocked",problemCode:o,method:kr(e,t),host:te(Hs(e)),error:O}),clearTimeout(S),f?.(),O}let U=0;try{for(;;){let O=await X_(p,a,k,w,o,I,()=>y?`timeout_after_${c}ms`:void 0),L=Z_(O,I);if(L!==void 0)try{let F=nw({currentInput:k,currentInit:w,currentUrl:I,redirectUrl:L,redirects:U,maxRedirects:i,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 to(p,{event:"outbound_redirect_blocked",problemCode:o,method:kr(k,w),host:te(I),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:te(L)}}),F}try{return W_(O,await K_(O,s,o))}catch(F){throw to(p,{event:"outbound_response_size_exceeded",problemCode:o,method:kr(k,w),host:te(I),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(S),f?.()}}n(Bs,"runSafeOutboundExchange");async function ro(e,t,r){let o=await Bs(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw to(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:kr(e,t),host:te(Hs(e)),error:i,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:i})}}n(ro,"runSafeOutboundJsonExchange");function Bp(e,t={},r={}){return Bs(e,t,{...r,validateUrl:Fn})}n(Bp,"fetchConfiguredOutbound");function Fp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Fn})}n(Fp,"fetchConfiguredOutboundJson");function fi(e,t={},r={}){return ro(e,t,{...r,validateUrl:hl})}n(fi,"fetchIdentityProviderJson");function Gp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Wo})}n(Gp,"fetchCimdClientMetadataJson");function Jp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Gn})}n(Jp,"fetchCimdClientJwksJson");import{errors as Xp,jwtVerify as Qp,SignJWT as em}from"jose";var we="zuplo-mcp-gateway",Ce=we,Te="HS256";import{base64url as ow}from"jose";var iw=new TextEncoder,sw="MCP gateway could not initialize secure key material.",aw=32,Vp=new Map,Kp=new Map,cw;function dw(){return cw??Da.instance.authPrivateKey}n(dw,"readAuthPrivateKey");function Wp(e){return new ye(sw,e===void 0?void 0:{cause:e})}n(Wp,"createGeneratedKeyMaterialError");function Zp(e,t){let r=ow.decode(t);if(r.byteLength!==aw)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Zp,"decodeJwkKeyField");function uw(e){let t=dw();if(!t)throw Wp();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=Zp("d",r.d);Zp("x",r.x);let i=iw.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),s=new Uint8Array(i.byteLength+o.byteLength);return s.set(i),s.set(o,i.byteLength),s}catch(r){throw Wp(r)}}n(uw,"decodeGeneratedKeyMaterial");function lw(e){let t=Vp.get(e);return t||(t=uw(e),Vp.set(e,t)),t}n(lw,"getMasterKeyMaterial");async function Le(e){let t=Kp.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(lw(e.keyMaterialPurpose));return Kp.set(e.purpose,r),r}n(Le,"readCachedDerivedKey");var pw="SHA-256",mw=32,hw="zuplo-mcp-gateway:",fw=new TextEncoder,Yp=new WeakMap;async function St(e,t){let r=Yp.get(e);r||(r=new Map,Yp.set(e,r));let o=r.get(t);if(o)return o;let i=await gw(e,t);return r.set(t,i),i}n(St,"deriveGatewaySigningKey");async function gw(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=fw.encode(`${hw}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:pw,salt:new Uint8Array,info:me(i)},o,mw*8);return new Uint8Array(s)}n(gw,"hkdfExpand");var tm=900,yw=900,Sw=Zu.extend({id:_l}),_w=Sw.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),rm=Yi.extend({id:wl,purpose:l.literal("browser_connect")}),ww=Yi.extend({purpose:l.literal("browser_connect")}),Rw=rm.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),nm=tm*1e3;async function om(){return Le({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>St(e,"oauth-state"),"derive")})}n(om,"getOAuthStateKey");async function im(){return Le({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>St(e,"browser-connect"),"derive")})}n(im,"getBrowserConnectKey");async function sm(e){let t=Math.floor(Date.now()/1e3)+tm;return new em(e).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await om())}n(sm,"signOAuthState");async function gi(e){try{let{payload:t}=await Qp(e,await om(),{algorithms:[Te],issuer:we,audience:Ce});return _w.parse(t)}catch(t){throw t instanceof Xp.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(gi,"verifyOAuthState");async function am(e){let t=Math.floor(Date.now()/1e3)+yw,r=ww.parse(e),o=rm.parse({...r,id:Il()});return new em(o).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await im())}n(am,"signBrowserConnectTicket");async function cm(e){try{let{payload:t}=await Qp(e,await im(),{algorithms:[Te],issuer:we,audience:Ce});return Rw.parse(t)}catch(t){throw t instanceof Xp.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(cm,"verifyBrowserConnectTicket");async function dm(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(dm,"consumeBrowserConnectTicket");function bw(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(bw,"buildConnectRequiredMessage");async function vw(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 am({...Hn(e),purpose:"browser_connect"})),r.toString()}n(vw,"buildGatewayBrowserTicketUrl");function Iw(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Iw,"buildGatewayConnectPath");async function Fs(e){return vw({...e,path:Iw(e.upstreamServerId),redirect:!0})}n(Fs,"buildGatewayConnectUrl");async function yi(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 Fs(t),message:bw(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(yi,"buildRedirectConnectRequiredResponse");function um(e){return Cw({...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(um,"buildAdminConnectRequiredResponse");function Cw(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(Cw,"buildAdminSetupRequiredResponse");var lm=12;async function pm(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(pm,"sha256Hex");async function Ht(e){if(e)return(await pm(e)).slice(0,lm)}n(Ht,"fingerprintSecret");async function Er(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await pm(t)).slice(0,lm)}n(Er,"fingerprintConnectionIdentity");var Tw=6e4;function Pr(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(Pr,"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()+Tw)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var mm=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function kw(e,t){return e&&e.length>0?e.join(t):void 0}n(kw,"joinOAuthScopes");function Ew(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of mm)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Ew,"sanitizeAuthorizationServerMetadata");function hm(e){let t=Ew(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(hm,"sanitizeOAuthDiscoveryState");function fm(e){let t=new URL(e);for(let r of mm){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(fm,"dedupeSingletonAuthorizationRequestParams");function Si(e){let t=new URL(e);return ve(t)&&ju(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Si,"normalizeLoopbackOAuthRedirectUri");function gm(e){return kw(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(gm,"readProtectedResourceMetadataScope");function Pw(e){return`Zuplo MCP Gateway - ${e}`}n(Pw,"buildGatewayOAuthClientName");function Aw(e,t){return e&&e.length>0?e.join(t):void 0}n(Aw,"joinOAuthScopeList");function xw(e){if(e.clientRegistration.mode!=="auto")return Aw(e.scopes,e.scopeDelimiter)}n(xw,"readPublicClientMetadataScope");function Gs(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Gs,"buildOAuthClientMetadataDocumentUrl");function Js(e){let t=yt(e.upstreamServerId);return{client_name:Pw(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(Js,"buildGatewayOAuthClientMetadata");function ym(e,t,r){let o=Tr(t,r),i=xw(o);return{client_id:Gs({origin:e,upstreamServerId:t}),...Js({origin:e,upstreamServerId:t,redirectUri:Si(new URL(o.redirectPath,e)).toString(),scope:i})}}n(ym,"buildOAuthClientMetadataDocument");import{base64url as _t}from"jose";var Uw="SHA-256",Ar="AES-GCM",Ow=12,Ks="zuplo-secret",Ws=1,Sm="generated:auth_private_key:token-encryption",Mw=l.object({version:l.literal(Ws),keyId:l.literal(Sm),algorithm:l.literal(Ar),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Vs(){return Le({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Uw,me(e));return crypto.subtle.importKey("raw",t,{name:Ar},!1,["encrypt","decrypt"])},"derive")})}n(Vs,"getEncryptionKey");function _m(e){return me(new TextEncoder().encode(`${Ks}:v${e.version}:${e.keyId}`))}n(_m,"getAssociatedData");function qw(e){return`${Ks}:v${e.version}:${_t.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(qw,"encodeEnvelope");function zw(e){let t=`${Ks}:v${Ws}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(_t.decode(r));return Mw.parse(JSON.parse(o))}n(zw,"decodeEnvelope");async function Xe(e){let t=await Vs(),r=crypto.getRandomValues(new Uint8Array(Ow)),o={version:Ws,keyId:Sm},i=await crypto.subtle.encrypt({name:Ar,iv:r,additionalData:_m(o)},t,new TextEncoder().encode(e));return qw({...o,algorithm:Ar,iv:_t.encode(r),ciphertext:_t.encode(new Uint8Array(i))})}n(Xe,"encryptSecret");async function Qe(e){let t=zw(e);if(t){let c=await Vs(),a=await crypto.subtle.decrypt({name:Ar,iv:me(_t.decode(t.iv)),additionalData:_m(t)},c,me(_t.decode(t.ciphertext)));return new TextDecoder().decode(a)}let[r,o]=e.split(".");if(!r||!o)throw new ye("Encrypted payload is malformed");let i=await Vs(),s=await crypto.subtle.decrypt({name:Ar,iv:me(_t.decode(r))},i,me(_t.decode(o)));return new TextDecoder().decode(s)}n(Qe,"decryptSecret");var wm={issuer:l.string().min(1).optional()},Nw=l.union([Dt.extend(wm),$n.extend(wm)]),Rm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:mr.optional(),authorizationServerMetadata:l.union([hr,fr]).optional()}).passthrough(),jw="Bearer",Dw="__zuplo_refresh_only_upstream_access_token__";function Zs(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Zs,"splitScopes");function Ys(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ys,"scopesCover");function $w(e){return yr.parse(e)}n($w,"parsePkceCodeVerifier");function Lw(e){if(typeof e.expires_in=="number")return D(new Date(Date.now()+e.expires_in*1e3))}n(Lw,"readTokenExpiry");async function bm(e){if(e!==void 0)return Xe(JSON.stringify(e))}n(bm,"encryptJson");async function vm(e,t){if(!e)return;let r=await Qe(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(vm,"decryptJson");function Hw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Hw,"clientInformationAllowsRedirectUri");function Bw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Bw,"clientInformationMatchesCurrentClientMetadataUrl");function Fw(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Fw,"isUrlBasedClientInformation");function Gw(e,t){return t===void 0?e:{...e,scope:t}}n(Gw,"applyOAuthClientMetadataScope");function Jw(e,t){return gm({state:e,delimiter:t})}n(Jw,"readResourceMetadataScope");function Vw(e,t){return e&&e.length>0?e.join(t):void 0}n(Vw,"joinOAuthScopeList");function Kw(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 Dt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Kw,"buildManualOAuthClientInformation");function Ww(e,t){let r=Gs({origin:new URL(t).origin,upstreamServerId:e});return qs(r)?r:void 0}n(Ww,"buildClientMetadataUrl");function Zw(e){for(let t of e)if(t!==void 0)return t}n(Zw,"firstDefined");function Yw(e){let t=Tr(e.target.upstreamServerId,e.target.authProfileId),r=Vw(t.scopes,t.scopeDelimiter),o=Js({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:Kw({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Ww(e.target.upstreamServerId,e.redirectUri);return i===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:i}}n(Yw,"buildInitialOAuthClientSetup");function Xw(e,t){if(t===void 0)return Zw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Xw,"readEncryptedClientInformation");function Qw(e){return e.pendingState?.encryptedDiscoveryState}n(Qw,"readEncryptedDiscoveryState");function Xs(e,t){return t===void 0?e:{...e,issuer:t}}n(Xs,"applyIssuerStamp");var wt=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=Yw({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=Xw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Qw(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=Zs(this.configuredScope??r??this.readEffectiveScope());return Ys(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 Er({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Ht(await Qe(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await N().conditionalUpsertUpstreamConnection(t,r)}catch(o){let i=W();if(i){let s=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});i.error(s,"Upstream OAuth conditional storage write failed")}throw o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Gw(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return sm({id:t.id,...Hn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?Xs(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"),!Fw({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await bm(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ni({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=hm(Rm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await bm(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=Jw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Zs(this.configuredScope).filter(s=>!o.includes(s));i.length>0&&W()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,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 Xs(r,t?.issuer)}async saveTokens(t){let r=ut.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await Xe(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:ut.parse({...r,refresh_token:await Qe(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:i?.id??Zo(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Xe(r.access_token),encryptedRefreshToken:c,scopes:Zs(r.scope??this.readEffectiveScope()),expiresAt:Lw(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},u=i?{expectedUpdatedAt:i.updatedAt}:{expectAbsent:!0},p=await this.conditionalUpsertCredential(a,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ys(p.connection.scopes,a.scopes)||!Pr(i,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:i?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:i?.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,Pr(i,p.connection)&&he(p.connection)==="usable"&&Ys(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:i?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:i?.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:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Ht(r.refresh_token),reusedSnapshotRefreshToken:s,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=fm(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:$w(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",i=t==="all"||t==="discovery",s=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(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(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:vl(),...Hn({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()+nm)),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 vm(this.encryptedClientInformation,Nw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!Hw(r,this.redirectUriValue)||!Bw({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=Xs($n.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 vm(this.encryptedDiscoveryState,Rm)}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 Qe(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Qe(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Ht(o):void 0,i?.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 s=ut.parse({access_token:r??Dw,token_type:jw,refresh_token:o,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=s,s}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let o=r.status,i=r.updatedAt,s={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&&(s.status="reconsent_required",s.encryptedAccessToken=void 0,s.encryptedRefreshToken=void 0,s.scopes=[],s.expiresAt=void 0),s.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let c=await this.conditionalUpsertCredential(s,{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,Pr(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:i,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 eR=3e4,tR=256*1024,rR=2,nR="does not support dynamic client registration",oR=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],iR=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],sR=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],aR="Protected resource ",cR=" does not match expected ",dR=["HTTP 403 Forbidden","Access Denied","permission to access"],uR=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function lR(e){return e instanceof Error&&e.message.includes(nR)}n(lR,"isDynamicClientRegistrationUnsupported");function pR(e){return e instanceof Error&&oR.some(t=>e.message.includes(t))}n(pR,"isProtectedResourceMetadataUnavailable");function mR(e){return e instanceof Error&&iR.some(t=>e.message.includes(t))}n(mR,"isAuthorizationServerMetadataUnavailable");function hR(e){return e instanceof Error&&sR.some(t=>e.message.includes(t))}n(hR,"isAuthorizationServerIncompatible");function fR(e){return e instanceof Error&&e.message.includes(aR)&&e.message.includes(cR)}n(fR,"isProtectedResourceMismatch");function gR(e){return e instanceof Error&&dR.some(t=>e.message.includes(t))}n(gR,"isUpstreamProviderAccessDenied");function yR(e){return e instanceof ht&&uR.has(e.code)}n(yR,"isStoredConnectionReconsentError");function et(e){let t=e.diagnostics??{};return new v({message:e.message,extensionMembers:{[C]:e.code,[Lo]:e.upstreamServerId,[wr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[Ve]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[Je]:t.httpStatus},...t.providerError===void 0?{}:{[Rr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[br]:t.providerErrorDescription}}},{cause:e.cause})}n(et,"buildUpstreamSetupProblem");function SR(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(SR,"describeIssuerMetadataMismatch");var _R=128,wR=256;function Im(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Im,"truncateProviderDetail");function RR(e){let{error:t,errorDescription:r}=Tm(e.body),o=Im(t,_R),i=Im(r,wR);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...i===void 0?{}:{providerErrorDescription:i}}}n(RR,"readRegistrationRejectionDiagnostics");function bR(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(bR,"describeRegistrationRejection");function vR(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(vR,"readDiscoveryEndpointUrl");function IR(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(lR(e.error))return et({...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 Os){let r=RR(e.error);return et({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${bR(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 Xn&&e.error.kind==="metadata")return et({...t,code:"upstream_oauth_issuer_mismatch",message:SR(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ai)return et({...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(hR(e.error))return et({...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(mR(e.error)){let r=vR(e.error.message);return et({...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(fR(e.error))return et({...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(pR(e.error))return et({...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(gR(e.error))return et({...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(IR,"mapUpstreamOAuthSetupError");function CR(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(CR,"readOAuthFetchRequest");function TR(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(TR,"readOAuthFetchMethod");function kR(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(kR,"responseLooksJson");function ER(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(ER,"responseLooksHtml");var PR=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function AR(e){return PR.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(AR,"isMetadataDiscoveryRequest");function xR(e,t,r){return e!=="GET"||!AR(t)?!1:r>=400&&r<500||r===502}n(xR,"sdkRetriesDiscoveryCandidate");function UR(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",[Je]:e.response.status,[Sr]:r,[Ve]:e.request.url.toString(),[_r]:e.body}})}n(UR,"throwUpstreamHtmlError");function Tm(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(Tm,"readUpstreamOAuthErrorBody");function OR(e){let{error:t,errorDescription:r}=Tm(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(OR,"logUpstreamOAuthHttpError");function km(e){return async(t,r)=>{let o=CR(t),i=TR(t,r),s=W(),c=Date.now(),a=await Bp(t,r,{maxRedirects:rR,maxResponseBytes:tR,problemCode:"upstream_token_exchange_failed",timeoutMs:eR}),u=await a.clone().text();if(s?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,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||OR({log:s,upstreamServerId:e,method:i,request:o,response:a,body:u}),xR(i,o.url,a.status)||(!a.ok&&ER(a,u)&&UR({upstreamServerId:e,request:o,response:a,body:u}),!kR(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(km,"createUpstreamOAuthFetch");function Em(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(Em,"logUpstreamOAuthFlowStarted");function Pm(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(Pm,"logUpstreamOAuthFlowFailed");function Am(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Am,"readAuthorizationRequestScope");async function xm(e,t){e.applyChallengeScope(t.requestedScope),Em({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:km(t.upstreamServerId)},o=Am(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await Ms(e,r)}catch(r){Pm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=IR({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(xm,"runUpstreamOAuth");async function MR(e,t){e.applyChallengeScope(t.requestedScope),Em({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:km(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Am(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await Ms(e,r)}catch(i){throw Pm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(MR,"exchangeUpstreamAuthorizationCode");async function Cm(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"||!Pr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(Cm,"adoptPeerCredentialAtResolutionBoundary");async function Um(e,t){let r=await xm(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(Um,"requireUpstreamAuthorizationRedirect");async function Om(e){let t=he(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),i=W(),s=i?await Er({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:s,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 xm(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||!yR(a))throw a;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:a.code,connectionFingerprint:s,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 Cm({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 Qs({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 Qs({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 Cm({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 Qs({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(Om,"authorizeUpstreamOAuthSession");async function qR(e){let t=await gi(e.stateToken),r=await N().consumeUpstreamOAuthState({id:t.id,now:D(new Date)}),o=zR(r);return NR({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),jR(o),o}n(qR,"consumeStoredCallbackState");function zR(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(zR,"readConsumedCallbackState");function NR(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(NR,"assertStoredCallbackStateMatches");function jR(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[C]:"oauth_state_expired"}})}n(jR,"assertStoredCallbackStateFresh");async function Qs(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),um(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),yi(t)}n(Qs,"buildOAuthConnectRequiredResponse");async function Mm(e){let t=await qR({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Go(t),[o]=await N().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={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&&(i.connection=o);let s=new wt(i),c=await MR(s,{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=s.readUsablePeerAdoption();if(a!==void 0&&await s.adoptConnectionForDirectResolution(a,"cas_loss"),!s.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(Mm,"finishUpstreamOAuthCallback");import{importPKCS8 as DR,SignJWT as $R}from"jose";var zm=1e4,Nm=64*1024,jm=2,LR=300,Me=l.string().min(1),HR=l.object({access_token:Me,issued_token_type:l.literal(Qi),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:Me.optional()}).passthrough(),BR=l.object({id_token:Me,token_type:Me.optional(),expires_in:l.number().int().positive().optional(),refresh_token:Me.optional(),scope:Me.optional()}).passthrough(),FR=l.object({access_token:Me,token_type:Me,expires_in:l.number().int().positive().optional(),scope:Me.optional(),resource:Me.optional(),refresh_token:Me.optional()}).passthrough();function qm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(qm,"formEncodeClientCredential");function GR(e){return e.replaceAll("\\n",`
25
+ import{$ as lr,$a as jc,$b as Nd,$c as Tu,$f as Se,$g as J,A as Ga,Aa as pc,Ab as ld,Ac as Qd,Af as lt,Ag as al,Ba as mc,Bb as pd,Bc as eu,Bf as _g,Bg as ne,C as Mo,Ca as hc,Cb as md,Cc as tu,Cf as wg,Cg as cl,Da as fc,Db as hd,Dc as ru,Df as Rg,Dg as dl,Ea as gc,Eb as fd,Ec as nu,Ef as bg,Eg as os,Fa as yc,Fb as gd,Fc as ou,Ff as vg,Fg as ul,Ga as Sc,Gb as yd,Gc as iu,Gf as Ig,Gg as ll,Ha as _c,Hb as Sd,Hc as su,Hf as Cg,Hg as is,Ia as wc,Ib as _d,Ic as au,If as Tg,Ig as pl,Ja as Rc,Jb as wd,Jc as cu,Jf as kg,Jg as $t,Ka as bc,Kb as Rd,Kc as du,Kf as Eg,Kg as ml,La as vc,Lb as bd,Lc as uu,Lf as Gu,Lg as Fn,Ma as Ic,Mb as vd,Mc as lu,Mf as Ju,Mg as hl,Na as Cc,Nb as Id,Nc as pu,Nf as Vu,Ng as Wo,Oa as Li,Ob as Cd,Oc as mu,Of as Fo,Og as Gn,P as Ja,Pa as Tc,Pb as Td,Pc as hu,Pf as Ln,Pg as fl,Qa as kc,Qb as kd,Qc as fu,Qf as Ku,Qg as gl,Ra as Ec,Rb as Ed,Rc as gu,Rf as vr,Rg as yl,Sa as Pc,Sb as Pd,Sc as yu,Sf as Wu,Sg as Sl,Ta as Ac,Tb as Ad,Tc as Su,Tf as Yi,Tg as _l,Ua as xc,Ub as xd,Uc as _u,Uf as Zu,Ug as wl,Va as Uc,Vb as Ud,Vc as wu,Vf as Hn,Vg as Rl,W as qo,Wa as Oc,Wb as Od,Wc as Ru,Wf as Go,Wg as bl,X as Ni,Xa as Mc,Xb as Hi,Xc as bu,Xf as Yu,Xg as Zo,Y as dr,Ya as qc,Yb as Md,Yc as vu,Yf as Xu,Yg as vl,Z as Nn,Za as zc,Zb as qd,Zc as Iu,Zf as Qu,Zg as Il,_ as ur,_a as Nc,_b as zd,_c as Cu,_f as el,_g as N,aa as jn,ab as Dc,ac as jd,ad as ku,af as ju,ag as de,ah as me,ba as pr,bb as $c,bc as Dd,bd as Eu,bf as ve,bg as tl,bh as Ye,ca as Va,cb as Lc,cc as $d,cd as Pu,cf as Du,cg as rl,ch as X,da as Ka,db as Hc,dc as Ld,dd as Au,df as $u,dg as D,dh as Yo,ea as Wa,eb as Bc,ec as Hd,ed as xu,ef as Y,eg as We,eh as Pg,fa as Za,fb as Fc,fc as Bd,fd as Uu,ff as Lu,fg as Ir,fh as Ag,ga as Ya,gb as Gc,gc as Fd,gd as mr,gf as gr,gg as pe,ha as Xa,hb as Jc,hc as Gd,hd as hr,hf as Hu,hg as te,ia as Qa,ib as Vc,ic as Jd,id as Ou,if as yr,ig as nl,ja as ec,jb as Kc,jc as Vd,jd as fr,jf as C,jg as W,ka as tc,kb as Wc,kc as Kd,kd as ut,kf as Sr,kg as ol,l as De,la as rc,lb as Zc,lc as Wd,ld as Zi,lf as _r,lg as pt,ma as nc,mb as Yc,mc as Bi,md as $o,mf as Je,mg as Xi,na as oc,nb as Xc,nc as zo,nd as Mu,nf as Ve,ng as Jo,oa as ic,ob as Qc,oc as No,od as $n,of as Lo,og as Qi,pa as sc,pb as ed,pc as Fi,pd as Dt,pf as wr,pg as Vo,qa as ac,qb as td,qc as Gi,qd as qu,qf as Rr,qg as Bn,ra as cc,rb as rd,rc as Ji,rd as zu,rf as br,rg as Cr,s as Nt,sa as jt,sb as nd,sc as Zd,sf as Ho,sg as il,t as Ba,ta as ji,tb as od,tc as Vi,tf as Bu,tg as Ze,ua as Di,ub as id,uc as Ki,uf as Oe,ug as es,v as H,va as Dn,vb as sd,vc as Yd,vf as Fu,vg as ts,wa as $i,wb as ad,wc as Xd,wf as Ke,wg as sl,xa as dc,xb as cd,xc as Wi,xd as Nu,xf as x,xg as Ko,ya as uc,yb as dd,yc as jo,yf as Bo,yg as rs,za as lc,zb as ud,zc as Do,zf as le,zg as ns}from"../chunk-7O65Y44U.js";import"../chunk-B5DKYXCI.js";import{a as Cl}from"../chunk-6SNZ4DOC.js";import{a as Fa}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as l,b as Mi,c as qn,d as $a,e as d,f as La,g as Ha,h as b,i as A,j as Uo,l as M,m as _,n as m,o as z,p as E,q as qi,r as zn,s as T,t as j,u as g,v as q,w as zi,x as Oo}from"../chunk-GCOWKKQW.js";import{$ as xo,X as ye,Y as v,Z as K,_ as Da}from"../chunk-HWNKBEMX.js";import{a as n}from"../chunk-TYV53J3B.js";var xg=Object.create,Xo=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,Og=Object.getOwnPropertyNames,Mg=Object.getPrototypeOf,qg=Object.prototype.hasOwnProperty,Tl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),kl=n((e,t)=>{let r={};for(var o in e)Xo(r,o,{get:e[o],enumerable:!0});return t&&Xo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),zg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Og(t),s=0,c=i.length,a;s<c;s++)a=i[s],!qg.call(e,a)&&a!==r&&Xo(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=Ug(t,a))||o.enumerable});return e},"__copyProps"),El=n((e,t,r)=>(r=e!=null?xg(Mg(e)):{},zg(t||!e||!e.__esModule?Xo(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Ng=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Pl(e){return typeof e=="string"&&Ng.has(e.replace(/#$/,""))}n(Pl,"declares2019Dialect");var ls=Symbol.for("mcp.sdk.errorBrands");function Lt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let i=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof i=="string"&&r.add(i),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,ls,{value:r,enumerable:!1,configurable:!0})}n(Lt,"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,ls)){let r=t[ls];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})({}),ht=class Dl 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",Lt(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 Dl(t.error,t.error_description??t.error,t.error_uri)}},ie=(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",Lt(this,new.target)}},Wg=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 $l(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n($l,"resourceUrlFromServerUrl");function ni({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 i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(s)}n(ni,"checkResourceAllowed");var Zg="2026-07-28";function Ll(e){return e>=Zg}n(Ll,"isModernProtocolVersion");function Hl(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(Hl,"appendTextFallbackForNonObject");var Bl=["task","inputRequests","requestState"];function Yg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Bl.some(t=>t in e)?e:{...e,content:[]}}n(Yg,"normalizeContentlessToolResult");function Xg(){let e=zi(()=>E([d(),b(),A(),Uo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),c=z({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=m({_meta:c.optional()}),u=a.extend({task:i.optional()}),p=m({method:d(),params:a.loose().optional()}),h=m({_meta:c.optional()}),f=m({method:d(),params:h.loose().optional()}),y=z({_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()}),L=m({name:d(),title:d().optional()}),F=L.extend({...L.shape,...O.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ee=zn(m({applyDefaults:A().optional()}),t),G=Oo(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,zn(m({form:ee.optional(),url:t.optional()}),t.optional())),V=z({list:t.optional(),cancel:t.optional(),requests:z({sampling:z({createMessage:t.optional()}).optional(),elicitation:z({create:t.optional()}).optional()}).optional()}),Be=z({list:t.optional(),cancel:t.optional(),requests:z({tools:z({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()}),ze=a.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),$=p.extend({method:g("initialize"),params:ze}),Ae=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:Be.optional(),extensions:T(d(),t).optional()}),Lr=y.extend({protocolVersion:d(),capabilities:Ae,serverInfo:F,instructions:d().optional()}),Jt=f.extend({method:g("notifications/initialized"),params:h.optional()}),ot=p.extend({method:g("ping"),params:a.optional()}),It=m({progress:b(),total:q(b()),message:q(d())}),Ne=m({...h.shape,...It.shape,progressToken:r}),it=f.extend({method:g("notifications/progress"),params:Ne}),Vt=a.extend({cursor:o.optional()}),Fe=p.extend({params:Vt.optional()}),Ge=y.extend({nextCursor:o.optional()}),Kt=m({uri:d(),mimeType:q(d()),_meta:T(d(),M()).optional()}),Wt=Kt.extend({text:d()}),Ct=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zt=Kt.extend({blob:Ct}),je=j(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:qn.datetime({offset:!0}).optional()}),Tt=m({...L.shape,...O.shape,uri:d(),description:q(d()),mimeType:q(d()),size:q(b()),annotations:xe.optional(),_meta:q(z({}))}),Hr=m({...L.shape,...O.shape,uriTemplate:d(),description:q(d()),mimeType:q(d()),annotations:xe.optional(),_meta:q(z({}))}),Br=Fe.extend({method:g("resources/list")}),Fr=Ge.extend({resources:_(Tt)}),st=Fe.extend({method:g("resources/templates/list")}),Yt=Ge.extend({resourceTemplates:_(Hr)}),kt=a.extend({uri:d()}),Gr=kt,Jr=p.extend({method:g("resources/read"),params:Gr}),Vr=y.extend({contents:_(E([Wt,Zt]))}),Kr=f.extend({method:g("notifications/resources/list_changed"),params:h.optional()}),Wr=kt,Zr=p.extend({method:g("resources/subscribe"),params:Wr}),Yr=kt,Xr=p.extend({method:g("resources/unsubscribe"),params:Yr}),Qr=h.extend({uri:d()}),en=f.extend({method:g("notifications/resources/updated"),params:Qr}),tn=m({name:d(),description:q(d()),required:q(A())}),rn=m({...L.shape,...O.shape,description:q(d()),arguments:q(_(tn)),_meta:q(z({}))}),nn=Fe.extend({method:g("prompts/list")}),on=Ge.extend({prompts:_(rn)}),sn=a.extend({name:d(),arguments:T(d(),d()).optional()}),an=p.extend({method:g("prompts/get"),params:sn}),Et=m({type:g("text"),text:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),Pt=m({type:g("image"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),At=m({type:g("audio"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),M()).optional()}),cn=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),at=m({type:g("resource"),resource:E([Wt,Zt]),annotations:xe.optional(),_meta:T(d(),M()).optional()}),dn=Tt.extend({type:g("resource_link")}),Ee=E([Et,Pt,At,dn,at]),Xt=m({role:je,content:Ee}),Qt=y.extend({description:d().optional(),messages:_(Xt)}),xt=f.extend({method:g("notifications/prompts/list_changed"),params:h.optional()}),un=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),er=m({taskSupport:j(["required","optional","forbidden"]).optional()}),Ut=m({...L.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:un.optional(),execution:er.optional(),_meta:T(d(),M()).optional()}),tr=Fe.extend({method:g("tools/list")}),rr=Ge.extend({tools:_(Ut)}),nr=y.extend({content:_(Ee),structuredContent:T(d(),M()).optional(),isError:A().optional()}),ae=u.extend({name:d(),arguments:T(d(),M()).optional()}),ln=p.extend({method:g("tools/call"),params:ae}),ho=f.extend({method:g("notifications/tools/list_changed"),params:h.optional()}),or=j(["debug","info","notice","warning","error","critical","alert","emergency"]),pn=a.extend({level:or}),mn=p.extend({method:g("logging/setLevel"),params:pn}),hn=h.extend({level:or,logger:d().optional(),data:M()}),fn=f.extend({method:g("notifications/message"),params:hn}),gn=m({name:d().optional()}),yn=m({hints:_(gn).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Sn=m({mode:j(["auto","required","none"]).optional()}),fo=m({type:g("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(Ee),structuredContent:m({}).loose().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),_n=qi("type",[Et,Pt,At]),ct=qi("type",[Et,Pt,At,cn,fo]),wn=m({role:je,content:E([ct,_(ct)]),_meta:T(d(),M()).optional()}),Rn=u.extend({messages:_(wn),modelPreferences:yn.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:Sn.optional()}),bn=p.extend({method:g("sampling/createMessage"),params:Rn}),vn=y.extend({model:d(),stopReason:q(j(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:_n}),In=y.extend({model:d(),stopReason:q(j(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:E([ct,_(ct)])}),Cn=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),Tn=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()}),kn=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()}),Pn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),An=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),xn=E([En,Pn]),Ot=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()}),Mt=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()}),go=E([Ot,Mt]),yo=E([An,xn,go]),Re=E([yo,Cn,Tn,kn]),be=u.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),Re),required:_(d()).optional()}).catchall(M())}),Un=u.extend({mode:g("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=E([be,Un]),So=p.extend({method:g("elicitation/create"),params:Ue}),_o=h.extend({elicitationId:d()}),wo=f.extend({method:g("notifications/elicitation/complete"),params:_o}),Ro=y.extend({action:j(["accept","decline","cancel"]),content:Oo(ce=>ce===null?void 0:ce,T(d(),E([d(),b(),A(),_(d())])).optional())}),bo=m({type:g("ref/resource"),uri:d()}),vo=m({type:g("ref/prompt"),name:d()}),Io=a.extend({ref:E([vo,bo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),On=p.extend({method:g("completion/complete"),params:Io}),Co=y.extend({completion:z({values:_(d()).max(100),total:q(b().int()),hasMore:q(A())})}),To=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),ir=p.extend({method:g("roots/list"),params:a.optional()}),Mn=y.extend({roots:_(To)}),ko=f.extend({method:g("notifications/roots/list_changed"),params:h.optional()}),Eo=z({ttl:b().optional(),pollInterval:b().optional()}),Po=j(["working","input_required","completed","failed","cancelled"]),dt=m({taskId:d(),status:Po,ttl:E([b(),Uo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:q(b()),statusMessage:q(d())}),fe=y.extend({task:dt}),Ao=h.merge(dt),qt=f.extend({method:g("notifications/tasks/status"),params:Ao}),sr=p.extend({method:g("tasks/get"),params:a.extend({taskId:d()})}),ar=y.merge(dt),cr=p.extend({method:g("tasks/result"),params:a.extend({taskId:d()})}),Oi=y.loose(),ge=Fe.extend({method:g("tasks/list")}),Z=Ge.extend({tasks:_(dt)}),zt=p.extend({method:g("tasks/cancel"),params:a.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,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:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Be,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:ze,InitializeRequestSchema:$,ServerCapabilitiesSchema:Ae,InitializeResultSchema:Lr,InitializedNotificationSchema:Jt,PingRequestSchema:ot,ProgressSchema:It,ProgressNotificationParamsSchema:Ne,ProgressNotificationSchema:it,PaginatedRequestParamsSchema:Vt,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ge,ResourceContentsSchema:Kt,TextResourceContentsSchema:Wt,BlobResourceContentsSchema:Zt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:Tt,ResourceTemplateSchema:Hr,ListResourcesRequestSchema:Br,ListResourcesResultSchema:Fr,ListResourceTemplatesRequestSchema:st,ListResourceTemplatesResultSchema:Yt,ResourceRequestParamsSchema:kt,ReadResourceRequestParamsSchema:Gr,ReadResourceRequestSchema:Jr,ReadResourceResultSchema:Vr,ResourceListChangedNotificationSchema:Kr,SubscribeRequestParamsSchema:Wr,SubscribeRequestSchema:Zr,UnsubscribeRequestParamsSchema:Yr,UnsubscribeRequestSchema:Xr,ResourceUpdatedNotificationParamsSchema:Qr,ResourceUpdatedNotificationSchema:en,PromptArgumentSchema:tn,PromptSchema:rn,ListPromptsRequestSchema:nn,ListPromptsResultSchema:on,GetPromptRequestParamsSchema:sn,GetPromptRequestSchema:an,TextContentSchema:Et,ImageContentSchema:Pt,AudioContentSchema:At,ToolUseContentSchema:cn,EmbeddedResourceSchema:at,ResourceLinkSchema:dn,ContentBlockSchema:Ee,PromptMessageSchema:Xt,GetPromptResultSchema:Qt,PromptListChangedNotificationSchema:xt,ToolAnnotationsSchema:un,ToolExecutionSchema:er,ToolSchema:Ut,ListToolsRequestSchema:tr,ListToolsResultSchema:rr,CallToolResultSchema:nr,CallToolRequestParamsSchema:ae,CallToolRequestSchema:ln,ToolListChangedNotificationSchema:ho,LoggingLevelSchema:or,SetLevelRequestParamsSchema:pn,SetLevelRequestSchema:mn,LoggingMessageNotificationParamsSchema:hn,LoggingMessageNotificationSchema:fn,ModelHintSchema:gn,ModelPreferencesSchema:yn,ToolChoiceSchema:Sn,ToolResultContentSchema:fo,SamplingContentSchema:_n,SamplingMessageContentBlockSchema:ct,SamplingMessageSchema:wn,CreateMessageRequestParamsSchema:Rn,CreateMessageRequestSchema:bn,CreateMessageResultSchema:vn,CreateMessageResultWithToolsSchema:In,BooleanSchemaSchema:Cn,StringSchemaSchema:Tn,NumberSchemaSchema:kn,UntitledSingleSelectEnumSchemaSchema:En,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:An,SingleSelectEnumSchemaSchema:xn,UntitledMultiSelectEnumSchemaSchema:Ot,TitledMultiSelectEnumSchemaSchema:Mt,MultiSelectEnumSchemaSchema:go,EnumSchemaSchema:yo,PrimitiveSchemaDefinitionSchema:Re,ElicitRequestFormParamsSchema:be,ElicitRequestURLParamsSchema:Un,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:So,ElicitationCompleteNotificationParamsSchema:_o,ElicitationCompleteNotificationSchema:wo,ElicitResultSchema:Ro,ResourceTemplateReferenceSchema:bo,PromptReferenceSchema:vo,CompleteRequestParamsSchema:Io,CompleteRequestSchema:On,CompleteResultSchema:Co,RootSchema:To,ListRootsRequestSchema:ir,ListRootsResultSchema:Mn,RootsListChangedNotificationSchema:ko,TaskCreationParamsSchema:Eo,TaskStatusSchema:Po,TaskSchema:dt,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:Ao,TaskStatusNotificationSchema:qt,GetTaskRequestSchema:sr,GetTaskResultSchema:ar,GetTaskPayloadRequestSchema:cr,GetTaskPayloadResultSchema:Oi,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:zt,CancelTaskResultSchema:y.merge(dt),ClientRequestSchema:E([ot,$,On,mn,an,nn,Br,st,Jr,Zr,Xr,ln,tr,sr,cr,ge,zt]),ClientNotificationSchema:E([I,it,Jt,ko,qt]),ClientResultSchema:E([k,vn,In,Ro,Mn,ar,Z,fe]),ServerRequestSchema:E([ot,bn,So,ir,sr,cr,ge,zt]),ServerNotificationSchema:E([I,it,fn,en,Kr,ho,xt,qt,wo]),ServerResultSchema:E([k,Lr,Co,Qt,on,Fr,Yt,Vr,nr,rr,ar,Z,fe]),CallToolResultWireSchema:M().superRefine((ce,Sg)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let ja of Bl)if(ja in ce){Sg.addIssue({code:"custom",message:`content is required when the body carries '${ja}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Yg).pipe(nr)}}n(Xg,"build$1");var Qg;function ys(){return Qg??=Xg()}n(ys,"buildSchemas2025");function Fl(e){return e.type!=="object"}n(Fl,"isNonObjectJsonSchemaRoot");var ey=new Set(["const","enum","default","examples"]),ty=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Al(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(Al,"establishesNewBase");function ry(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Al(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Pl(e.$schema)&&e.$recursiveAnchor!==!0,o=n((i,s)=>{if(Array.isArray(i))return i.map(u=>o(u,!1));if(i===null||typeof i!="object"||!s&&Al(i.$id))return i;let c={},a=!1;for(let[u,p]of Object.entries(i))s?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:ey.has(u)?c[u]=p:ty.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(ry,"wrapOutputSchemaForLegacy");var Gl={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},Jl={"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},ny={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},Qo;function oi(){if(Qo)return Qo;let e=ys();return Qo={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}},Qo}n(oi,"registryMaps");function oy(){oi()}n(oy,"warmRegistryMaps2025");function Vl(e){return Object.prototype.hasOwnProperty.call(Gl,e)}n(Vl,"hasRequestMethod2025");function Kl(e){return Object.prototype.hasOwnProperty.call(Jl,e)}n(Kl,"hasNotificationMethod2025");function iy(e){return Object.prototype.hasOwnProperty.call(ny,e)}n(iy,"hasResultMethod");function sy(e){return iy(e)?oi().resultSchemas[e]:void 0}n(sy,"getResultSchema");function ay(e){return Vl(e)?oi().requestSchemas[e]:void 0}n(ay,"getRequestSchema");function cy(e){return Kl(e)?oi().notificationSchemas[e]:void 0}n(cy,"getNotificationSchema");var ET=Object.keys(Gl),PT=Object.keys(Jl);function ps(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ps,"isPlainObject$4");function ei(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(ei,"triState$1");var xl={ok:!1,reason:"not-in-era"};function Ul(e){return ps(e)&&ps(e.outputSchema)&&Fl(e.outputSchema)}n(Ul,"toolNeedsLegacyWrap");var Ss={era:"2025-11-25",hasRequestMethod:Vl,hasNotificationMethod:Kl,validateRequest:n((e,t)=>ei(ay(e),t),"validateRequest"),validateResult:n((e,t)=>ei(sy(e),t),"validateResult"),validateNotification:n((e,t)=>ei(cy(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>xl,"validateInputRequest"),validateInputResponse:n(()=>xl,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=ys();return ei(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Hl(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Fl(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(ps(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=>Ul(o))?t:{...t,tools:r.map(o=>Ul(o)?{...o,outputSchema:ry(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function dy(){let e=zi(()=>E([d(),b(),A(),Uo(),T(d(),e),_(e)])),t=T(d(),e),r=E([d(),b().int()]),o=d(),i=E([d(),b().int()]),s=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=z({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()}),L=zn(m({applyDefaults:A().optional()}),t),F=Oo(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,zn(m({form:L.optional(),url:t.optional()}),t.optional())),ee=z({list:t.optional(),cancel:t.optional(),requests:z({sampling:z({createMessage:t.optional()}).optional(),elicitation:z({create:t.optional()}).optional()}).optional()}),G=z({list:t.optional(),cancel:t.optional(),requests:z({tools:z({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()}),Be=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:q(b()),message:q(d())}),ze=m({...S.shape,...oe.shape,progressToken:r}),$=k.extend({method:g("notifications/progress"),params:ze}),Ae=S.extend({level:c,logger:d().optional(),data:M()}),Lr=k.extend({method:g("notifications/message"),params:Ae}),Jt=m({uri:d(),mimeType:q(d()),_meta:T(d(),M()).optional()}),ot=Jt.extend({text:d()}),It=Jt.extend({blob:a}),Ne=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:qn.datetime({offset:!0}).optional()}),it=m({...U.shape,...I.shape,uri:d(),description:q(d()),mimeType:q(d()),size:q(b()),annotations:Ne.optional(),_meta:q(z({}))}),Vt=m({...U.shape,...I.shape,uriTemplate:d(),description:q(d()),mimeType:q(d()),annotations:Ne.optional(),_meta:q(z({}))}),Fe=k.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ge=S.extend({uri:d()}),Kt=k.extend({method:g("notifications/resources/updated"),params:Ge}),Wt=m({name:d(),description:q(d()),required:q(A())}),Ct=m({...U.shape,...I.shape,description:q(d()),arguments:q(_(Wt)),_meta:q(z({}))}),Zt=k.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),je=m({type:g("text"),text:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),xe=m({type:g("image"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Tt=m({type:g("audio"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Hr=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),M()),_meta:T(d(),M()).optional()}),Br=m({type:g("resource"),resource:E([ot,It]),annotations:Ne.optional(),_meta:T(d(),M()).optional()}),Fr=it.extend({type:g("resource_link")}),st=E([je,xe,Tt,Fr,Br]),Yt=m({role:s,content:st}),kt=m({title:d().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),Gr=k.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),Jr=m({name:d().optional()}),Vr=m({hints:_(Jr).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Kr=m({mode:j(["auto","required","none"]).optional()}),Wr=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:A().optional()}),Zr=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()}),Yr=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Xr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Qr=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),en=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),tn=E([Xr,Qr]),rn=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()}),nn=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()}),on=E([rn,nn]),sn=E([en,tn,on]),an=E([sn,Wr,Zr,Yr]),Et=y.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),an),required:_(d()).optional()}).catchall(M())}),Pt=m({type:g("ref/resource"),uri:d()}),At=m({type:g("ref/prompt"),name:d()}),cn=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),M()).optional()}),at=V.shape,dn=m({experimental:at.experimental,sampling:at.sampling,elicitation:at.elicitation,roots:at.roots,extensions:at.extensions}),Ee=Be.shape,Xt=m({experimental:Ee.experimental,logging:Ee.logging,completions:Ee.completions,prompts:Ee.prompts,resources:Ee.resources,tools:Ee.tools,extensions:Ee.extensions}),Qt=z({progressToken:r.optional(),[dr]:d(),[Nn]:O.optional(),[lr]:dn,[jn]:c.optional()}),xt=m({...U.shape,...I.shape,description:d().optional(),inputSchema:z({$schema:d().optional(),type:g("object")}),outputSchema:z({$schema:d().optional()}).optional(),annotations:kt.optional(),_meta:T(d(),M()).optional()}),un=m({type:g("tool_result"),toolUseId:d(),content:_(st),structuredContent:M().optional(),isError:A().optional(),_meta:T(d(),M()).optional()}),er=E([je,xe,Tt,Hr,un]),Ut=m({role:s,content:E([er,_(er)]),_meta:T(d(),M()).optional()}),tr=d(),rr=z({[ur]:O.optional().catch(void 0)}),nr=rr.optional();function ae(Z){return z({_meta:nr,resultType:tr.default("complete"),...Z})}n(ae,"wireResult");let ln=ae({}),ho=ae({nextCursor:o.optional()}),or=ae({content:_(st),structuredContent:M().optional(),isError:A().optional()}),pn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(xt),nextCursor:o.optional()}),mn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),hn=ae({description:d().optional(),messages:_(Yt)}),fn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(it),nextCursor:o.optional()}),gn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Vt),nextCursor:o.optional()}),yn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([ot,It]))}),Sn=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:A().optional()}).loose()}),fo=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"])}),_n=ae({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Xt,instructions:d().optional()}),ct=m({messages:_(Ut),modelPreferences:Vr.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(xt).optional(),toolChoice:Kr.optional()}),wn=m({method:g("sampling/createMessage"),params:ct}),Rn=m({method:g("roots/list"),params:m({_meta:T(d(),M()).optional()}).optional()}),bn=m({...Ut.shape,model:d(),stopReason:d().optional()}),vn=m({roots:_(cn)}),In=m({action:j(["accept","decline","cancel"]),content:T(d(),E([d(),b(),A(),_(d())])).optional()}),Cn=m({mode:g("url"),message:d(),url:d().url()}),Tn=E([Et,Cn]),kn=m({method:g("elicitation/create"),params:Tn}),En=E([wn,Rn,kn]),Pn=E([bn,vn,In]),An=T(d(),En),xn=T(d(),Pn),Ot=ae({inputRequests:An.optional(),requestState:d().optional()}),Mt={inputResponses:xn.optional(),requestState:d().optional()},go=m({_meta:Qt,...Mt}),yo=z({progressToken:r.optional()});function Re(Z,zt){return m({method:g(Z),params:m({_meta:Qt,...zt})})}n(Re,"wireRequest");function be(Z,zt){return m({method:g(Z),params:m({_meta:yo.optional(),...zt}).optional()})}n(be,"dispatchRequest");let Un={name:d(),arguments:T(d(),M()).optional(),...Mt},Ue={cursor:o.optional()},So=Re("tools/call",Un),_o=Re("tools/list",Ue),wo=Re("prompts/list",Ue),Ro=Re("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Mt}),bo=Re("resources/list",Ue),vo=Re("resources/templates/list",Ue),Io=Re("resources/read",{uri:d(),...Mt}),On={ref:E([At,Pt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},Co=Re("completion/complete",On),To=Re("server/discover",{}),ir=m({toolsListChanged:A().optional(),promptsListChanged:A().optional(),resourcesListChanged:A().optional(),resourceSubscriptions:_(d()).optional()}),Mn={notifications:ir},ko=Re("subscriptions/listen",Mn),Eo=rr.extend({"io.modelcontextprotocol/subscriptionId":i}),Po=z({_meta:Eo,resultType:tr.default("complete")}),dt={"tools/call":be("tools/call",Un),"tools/list":be("tools/list",Ue),"prompts/get":be("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":be("prompts/list",Ue),"resources/list":be("resources/list",Ue),"resources/templates/list":be("resources/templates/list",Ue),"resources/read":be("resources/read",{uri:d()}),"completion/complete":be("completion/complete",On),"server/discover":be("server/discover",{}),"subscriptions/listen":be("subscriptions/listen",Mn)};function fe(Z){return z({_meta:nr,...Z})}n(fe,"liftedResult");let Ao={"tools/call":fe({content:_(st),structuredContent:M().optional(),isError:A().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(xt),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Yt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),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:_(Vt),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(E([ot,It]))}),"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:Xt,instructions:d().optional()}),"subscriptions/listen":fe({})},qt=z({"io.modelcontextprotocol/subscriptionId":i.optional()}),sr=m({method:g("notifications/subscriptions/acknowledged"),params:m({_meta:qt.optional(),notifications:ir})}),ar=m({_meta:qt.optional(),requestId:i,reason:d().optional()}),cr=m({method:g("notifications/cancelled"),params:ar}),Oi={"notifications/cancelled":cr,"notifications/progress":$,"notifications/message":Lr,"notifications/resources/updated":Kt,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":Gr,"notifications/prompts/list_changed":Zt,"notifications/subscriptions/acknowledged":sr},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:i,RoleSchema:s,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:Be,ProgressSchema:oe,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:$,LoggingMessageNotificationParamsSchema:Ae,LoggingMessageNotificationSchema:Lr,ResourceContentsSchema:Jt,TextResourceContentsSchema:ot,BlobResourceContentsSchema:It,AnnotationsSchema:Ne,ResourceSchema:it,ResourceTemplateSchema:Vt,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:Kt,PromptArgumentSchema:Wt,PromptSchema:Ct,PromptListChangedNotificationSchema:Zt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:Tt,ToolUseContentSchema:Hr,EmbeddedResourceSchema:Br,ResourceLinkSchema:Fr,ContentBlockSchema:st,PromptMessageSchema:Yt,ToolAnnotationsSchema:kt,ToolListChangedNotificationSchema:Gr,ModelHintSchema:Jr,ModelPreferencesSchema:Vr,ToolChoiceSchema:Kr,BooleanSchemaSchema:Wr,StringSchemaSchema:Zr,NumberSchemaSchema:Yr,UntitledSingleSelectEnumSchemaSchema:Xr,TitledSingleSelectEnumSchemaSchema:Qr,LegacyTitledEnumSchemaSchema:en,SingleSelectEnumSchemaSchema:tn,UntitledMultiSelectEnumSchemaSchema:rn,TitledMultiSelectEnumSchemaSchema:nn,MultiSelectEnumSchemaSchema:on,EnumSchemaSchema:sn,PrimitiveSchemaDefinitionSchema:an,ElicitRequestFormParamsSchema:Et,ResourceTemplateReferenceSchema:Pt,PromptReferenceSchema:At,RootSchema:cn,ClientCapabilities2026Schema:dn,ServerCapabilities2026Schema:Xt,RequestMetaEnvelopeSchema:Qt,ToolSchema:xt,ToolResultContentSchema:un,SamplingMessageContentBlockSchema:er,SamplingMessageSchema:Ut,ResultTypeSchema:tr,ResultMetaSchema:rr,ResultSchema:ln,PaginatedResultSchema:ho,CallToolResultSchema:or,ListToolsResultSchema:pn,ListPromptsResultSchema:mn,GetPromptResultSchema:hn,ListResourcesResultSchema:fn,ListResourceTemplatesResultSchema:gn,ReadResourceResultSchema:yn,CompleteResultSchema:Sn,CacheableResultSchema:fo,DiscoverResultSchema:_n,CreateMessageRequestParamsSchema:ct,CreateMessageRequestSchema:wn,ListRootsRequestSchema:Rn,CreateMessageResultSchema:bn,ListRootsResultSchema:vn,ElicitResultSchema:In,ElicitRequestURLParamsSchema:Cn,ElicitRequestParamsSchema:Tn,ElicitRequestSchema:kn,InputRequestSchema:En,InputResponseSchema:Pn,InputRequestsSchema:An,InputResponsesSchema:xn,InputRequiredResultSchema:Ot,InputResponseRequestParamsSchema:go,CallToolRequestSchema:So,ListToolsRequestSchema:_o,ListPromptsRequestSchema:wo,GetPromptRequestSchema:Ro,ListResourcesRequestSchema:bo,ListResourceTemplatesRequestSchema:vo,ReadResourceRequestSchema:Io,CompleteRequestSchema:Co,DiscoverRequestSchema:To,SubscriptionFilterSchema:ir,SubscriptionsListenRequestSchema:ko,SubscriptionsListenResultMetaSchema:Eo,SubscriptionsListenResultSchema:Po,dispatchRequestSchemas:dt,dispatchResultSchemas:Ao,NotificationMetaSchema:qt,SubscriptionsAcknowledgedNotificationSchema:sr,CancelledNotificationParamsSchema:ar,CancelledNotificationSchema:cr,notificationSchemas2026:Oi,JSONRPCResultResponseSchema:ge(ln),CallToolResultResponseSchema:ge(E([or,Ot])),ListToolsResultResponseSchema:ge(pn),ListPromptsResultResponseSchema:ge(mn),GetPromptResultResponseSchema:ge(E([hn,Ot])),ListResourcesResultResponseSchema:ge(fn),ListResourceTemplatesResultResponseSchema:ge(gn),ReadResourceResultResponseSchema:ge(E([yn,Ot])),CompleteResultResponseSchema:ge(Sn),DiscoverResultResponseSchema:ge(_n)}}n(dy,"build");var uy;function mt(){return uy??=dy()}n(mt,"buildSchemas2026");var ly=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function py(e){return ly.includes(e)}n(py,"isCacheableResultMethod");var _s=Symbol("modelcontextprotocol.resultCacheHintFallback");function my(e){return e[_s]}n(my,"cacheHintFallbackOf");function Wl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(Wl,"isValidCacheTtlMs");function Zl(e){return e==="public"||e==="private"}n(Zl,"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})({}),se=class Yl 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",Lt(this,new.target)}static fromError(t,r,o){if(t===P.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new ii(i.elicitations,r)}if(t===P.UnsupportedProtocolVersion&&o){let i=o;if(Array.isArray(i.supported)&&typeof i.requested=="string")return new Ql({supported:i.supported,requested:i.requested},r)}if(t===P.InvalidParams||t===P.ResourceNotFound){let i=o;if(typeof i?.uri=="string"&&(t===P.ResourceNotFound||Object.keys(i).length===1))return new Xl(i.uri,r)}if(t===P.MissingRequiredClientCapability&&o){let i=o;if(i.requiredCapabilities!==null&&typeof i.requiredCapabilities=="object"&&!Array.isArray(i.requiredCapabilities))return new ep({requiredCapabilities:i.requiredCapabilities},r)}return new Yl(t,r,o)}},Xl=class extends se{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}},ii=class extends se{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??[]}},Ql=class extends se{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}},ep=class extends se{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}},hy=0,fy="private",gy=["tools/call","prompts/get","resources/read"];function yy(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||gy.includes(e))return t;throw new se(P.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(yy,"stampResultType");function Sy(e,t){let r=my(t);if(t.resultType!=="complete"||!py(e))return r===void 0?t:vy(t);let o=t,i=Wl(o.ttlMs)?o.ttlMs:Ry(r),s=Zl(o.cacheScope)?o.cacheScope:by(r),c={...o,ttlMs:i,cacheScope:s};return delete c[_s],c}n(Sy,"fillCacheFields");function _y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(_y,"isPlainObject$3");function wy(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ur]:t}}:!_y(r)||r[ur]!==void 0?e:{...e,_meta:{...r,[ur]:t}}}n(wy,"stampServerInfoMeta");function Ry(e){return e!==void 0&&Wl(e.ttlMs)?e.ttlMs:hy}n(Ry,"resolveTtlMs");function by(e){return e!==void 0&&Zl(e.cacheScope)?e.cacheScope:fy}n(by,"resolveCacheScope");function vy(e){let t={...e};return delete t[_s],t}n(vy,"stripCacheHintFallback");var Iy=["elicitation/create","sampling/createMessage","roots/list"],ti;function ws(){if(ti)return ti;let e=mt();return ti={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:z({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ti}n(ws,"inputSchemaMaps");function Cy(){ws()}n(Cy,"warmInputSchemaMaps2026");function tp(e){return Iy.includes(e)}n(tp,"isInputRequestMethod2026");function ss(e){return tp(e)?ws().request[e]:void 0}n(ss,"getInputRequestSchema2026");function Ty(e){return tp(e)?ws().response[e]:void 0}n(Ty,"getInputResponseSchema2026");var Rs={"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},rp={"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 np(e){return Object.prototype.hasOwnProperty.call(Rs,e)}n(np,"hasRequestMethod2026");function op(e){return Object.prototype.hasOwnProperty.call(rp,e)}n(op,"hasNotificationMethod2026");function ky(e){return Object.prototype.hasOwnProperty.call(Rs,e)}n(ky,"hasResultMethod2026");function Ey(e){return np(e)?mt().dispatchRequestSchemas[e]:void 0}n(Ey,"getRequestSchema2026");function Py(e){return ky(e)?mt().dispatchResultSchemas[e]:void 0}n(Py,"getResultSchema2026");function Ay(e){return op(e)?mt().notificationSchemas2026[e]:void 0}n(Ay,"getNotificationSchema2026");var AT=Object.keys(Rs),xT=Object.keys(rp);function Kn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Kn,"isPlainObject$2");function Jn(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(Jn,"triState");var xy={ok:!1,reason:"not-in-era"},Uy=[dr,lr];function Oy(e,t){let r=t,o=!1,i=n(()=>(o||(r={...r},o=!0),r),"copy"),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Kn(a)&&"execution"in a)&&(i().tools=s.map(a=>{if(!Kn(a)||!("execution"in a))return a;let u={...a};return delete u.execution,u}));let c=t.capabilities;if(Kn(c)&&"tasks"in c){let a={...c};delete a.tasks,i().capabilities=a}return r}n(Oy,"enforceDeletedFields");var bs={era:"2026-07-28",hasRequestMethod:np,hasNotificationMethod:op,hasInputRequestMethod:n(e=>ss(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>Jn(Ey(e),t),"validateRequest"),validateResult:n((e,t)=>Jn(Py(e),t),"validateResult"),validateNotification:n((e,t)=>Jn(Ay(e),t),"validateNotification"),validateInputRequest:n((e,t)=>Jn(ss(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>Jn(Ty(e),t),"validateInputResponse"),samplingResultVariant:n(()=>xy,"samplingResultVariant"),outboundEnvelope(e){return{[dr]:e.protocolVersion,[Nn]:e.clientInfo,[lr]:e.clientCapabilities,...e.logLevel!==void 0&&{[jn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Uy)o in e||t.push({key:o,problem:"missing"});let r=mt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let i=o.path.map(String),s=i.length>0?i.join("."):"_meta";i.length===1&&t.some(c=>c.key===s&&c.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>Hl(e),"projectCallToolResult"),inputRequestSchema:ss,decodeResult(e,t){if(!Kn(t))return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new re(ie.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(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let c=t.inputRequests,a=Kn(c)?c:{},u=t.requestState;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new re(ie.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(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=ip(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let c=i.safeParse(t);if(!c.success)return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: ${c.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return wy(Sy(e,yy(e,Oy(e,t))),r)},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=mt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},ri;function ip(){if(ri)return ri;let e=mt();return ri={"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},ri}n(ip,"getWireResultSchemas");function My(){ip()}n(My,"warmWireResultSchemas2026");var vs="2026-07-28";function Zn(e){return e!==void 0&&Ll(e)?bs:Ss}n(Zn,"codecForVersion");function Ol(e){return e.revision!==void 0?Zn(e.revision).era:e.era==="modern"?bs.era:Ss.era}n(Ol,"classifiedWireEra");function as(e){return sp.some(t=>t.hasRequestMethod(e))}n(as,"isSpecRequestMethod");function cs(e){return sp.some(t=>t.hasNotificationMethod(e))}n(cs,"isSpecNotificationMethod");var sp=[Ss,bs],qy=kl({AnnotationsSchema:n(()=>Nc,"AnnotationsSchema"),AudioContentSchema:n(()=>gd,"AudioContentSchema"),BaseMetadataSchema:n(()=>fc,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>tc,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>qc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Bi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>xd,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Ud,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Pd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>Cu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>Tu,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>lc,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>pc,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>_c,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>Eu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>ku,"ClientRequestSchema"),ClientResultSchema:n(()=>Pu,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>yc,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>Ad,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>su,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>au,"CompleteRequestSchema"),CompleteResultSchema:n(()=>cu,"CompleteResultSchema"),ContentBlockSchema:n(()=>wd,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Jd,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Vd,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Kd,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>Wd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>gu,"CreateTaskResultSchema"),CursorSchema:n(()=>Ya,"CursorSchema"),DiscoverRequestSchema:n(()=>Cc,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Li,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>jo,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Qd,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>eu,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Do,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>nu,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>tu,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>ru,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Sd,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>uc,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Xd,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>pd,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>md,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>bd,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>Ru,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>bu,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>_u,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>wu,"GetTaskResultSchema"),IconSchema:n(()=>mc,"IconSchema"),IconsSchema:n(()=>hc,"IconsSchema"),ImageContentSchema:n(()=>fd,"ImageContentSchema"),ImplementationSchema:n(()=>gc,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>wc,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>Rc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>vc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>Ic,"InitializedNotificationSchema"),JSONArraySchema:n(()=>Wa,"JSONArraySchema"),JSONObjectSchema:n(()=>Ka,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Dn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>$i,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>ji,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>jt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>dc,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Di,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Va,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Ji,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>Hi,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>ud,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>ld,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>Hc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>Bc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>$c,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Lc,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>uu,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>lu,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>vu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>Iu,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>kd,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>Ed,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>Md,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Nd,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>jd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Dd,"ModelHintSchema"),ModelPreferencesSchema:n(()=>$d,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Yd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>ic,"NotificationSchema"),NotificationsParamsSchema:n(()=>oc,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>No,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>Ac,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>xc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Uc,"PaginatedResultSchema"),PingRequestSchema:n(()=>Tc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>Wi,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>Ec,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Pc,"ProgressNotificationSchema"),ProgressSchema:n(()=>kc,"ProgressSchema"),ProgressTokenSchema:n(()=>Za,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>cd,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>vd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>Rd,"PromptMessageSchema"),PromptReferenceSchema:n(()=>iu,"PromptReferenceSchema"),PromptSchema:n(()=>dd,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Gc,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Jc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Vc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Qa,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>cc,"RequestIdSchema"),RequestMetaSchema:n(()=>ec,"RequestMetaSchema"),RequestSchema:n(()=>nc,"RequestSchema"),ResourceContentsSchema:n(()=>Oc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>_d,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Kc,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Fc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>jc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>ou,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Dc,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>sd,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>ad,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>sc,"ResultMetaObjectSchema"),ResultSchema:n(()=>ac,"ResultSchema"),RoleSchema:n(()=>zc,"RoleSchema"),RootSchema:n(()=>du,"RootSchema"),RootsListChangedNotificationSchema:n(()=>pu,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>Bd,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Fd,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Gd,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>bc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>xu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>Au,"ServerRequestSchema"),ServerResultSchema:n(()=>Uu,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Sc,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>qd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>zd,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Zd,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>zo,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>Wc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Zc,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Qc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>rd,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>nd,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>ed,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>td,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>od,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>id,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>rc,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>mu,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>Xa,"TaskMetadataSchema"),TaskSchema:n(()=>fu,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>yu,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Su,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>hu,"TaskStatusSchema"),TextContentSchema:n(()=>hd,"TextContentSchema"),TextResourceContentsSchema:n(()=>Mc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Ki,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Gi,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>Id,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Ld,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>Cd,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>Od,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>Hd,"ToolResultContentSchema"),ToolSchema:n(()=>Td,"ToolSchema"),ToolUseContentSchema:n(()=>yd,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Yc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Xc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Vi,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Fi,"UntitledSingleSelectEnumSchemaSchema")});var ap=n(e=>jt.safeParse(e).success,"isJSONRPCRequest"),cp=n(e=>ji.safeParse(e).success,"isJSONRPCNotification"),ms=n(e=>Di.safeParse(e).success,"isJSONRPCResultResponse"),dp=n(e=>Dn.safeParse(e).success,"isJSONRPCErrorResponse");var Wn=-32020,UT=[{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:[Wn,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:[Wn],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:[Wn],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."}],OT={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Wn]:400};function Is(e,t){return $a(e,t)}n(Is,"parseSchema");function Vn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Vn,"shapeKeys");function hs(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(hs,"isStandardSchema");var Ml=!1,fs="draft-2020-12";function zy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:fs});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().");Ml||(Ml=!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=Mi(e,{target:fs,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:up(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(zy,"standardSchemaToJsonSchema");function up(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"||up(o)))}return!1}n(up,"isProvablyObjectShapedRoot");function Ny(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Ny,"formatIssue");async function ds(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Ny(o)).join(", ")}:{success:!0,data:r.value}}n(ds,"validateStandardSchema");function jy(e){let t=Mi(e,{target:fs,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(jy,"zodEmittedPattern");var Dy=/\\\.\\d\{(\d+)\}/;function $y(e){let t=Dy.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(i=>r.map(s=>qn.datetime({local:o,offset:i,precision:s}))))}n($y,"datetimeReferenceSchemas");function Ly(e,t){let r;switch(e){case"email":r=[La()];break;case"uri":r=[Ha()];break;case"date":r=[qn.date()];break;case"date-time":r=$y(t);break}return new Set(r.map(o=>jy(o)).filter(o=>o!==void 0))}n(Ly,"referencePatternsForFormat");function Hy(e,t,r){return r!=="zod"?!0:Ly(e,t).has(t)}n(Hy,"isLibraryFormatPattern");function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Yn,"isJsonObject");function By(e){try{return zy(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new se(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(By,"convertStandardElicitationSchema");var Fy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Cs(e){return Fy.has(e)||e.startsWith("x-")}n(Cs,"isAnnotationOnlyJsonSchemaKeyword");var Gy=new Set(["$schema",...Object.keys(jo.shape.requestedSchema.shape)]),ql={string:Vn([zo,Fi,Gi,Ji]),number:Vn([No]),integer:Vn([No]),boolean:Vn([Bi]),array:Vn([Vi,Ki])},Jy=new Set(zo.shape.format.unwrap().options);function Vy(e,t,r,o){if(!Yn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(ql,e.type)?ql[e.type]:void 0;if(i===void 0)return e;let s={};for(let[c,a]of Object.entries(e))i.has(c)||Cs(c)?s[c]=a:c==="pattern"&&e.type==="string"&&typeof e.format=="string"?Jy.has(e.format)?(typeof a!="string"||!Hy(e.format,a,r))&&o.push(`${t}.${c}`):s[c]=a:o.push(`${t}.${c}`);return s}n(Vy,"walkProperty");function Ky(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Yn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([c,a])=>[c,Vy(a,`properties.${c}`,t,o)])):Gy.has(i)?r[i]=s:Cs(i)||o.push(i);if(o.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(Ky,"walkRequestedSchema");function Wy(e,t){if(!Yn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Is(Wi,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(Wy,"describeUnsupportedProperties");function gs(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>gs(o,t[i],`${r}[${i}]`)):!Yn(e)||!Yn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?gs(i,t[o],s):Cs(o)?[]:[s]})}n(gs,"findDroppedConstraintPaths");function Zy(e){if(!hs(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Ky(By(e.requestedSchema),t),o=Is(jo.shape.requestedSchema,r);if(!o.success)throw new se(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Wy(r,o.error.message)}`);let i=gs(r,o.data);if(i.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(", ")}`);let s=(o.data.required??[]).filter(c=>!Object.prototype.hasOwnProperty.call(o.data.properties,c));if(s.length>0)throw new se(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Zy,"normalizeElicitInputParams");function Yy(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(Yy,"buildInputRequired");var MT=Object.assign(Yy,{elicit(e){try{return{method:"elicitation/create",params:Zy(e)}}catch(t){throw t instanceof se?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 Xy=["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"],Qy={IdJagTokenExchangeResponseSchema:Zi,OAuthClientInformationFullSchema:Dt,OAuthClientInformationSchema:$n,OAuthClientMetadataSchema:Mu,OAuthClientRegistrationErrorSchema:qu,OAuthErrorResponseSchema:$o,OAuthMetadataSchema:hr,OAuthProtectedResourceMetadataSchema:mr,OAuthTokenRevocationRequestSchema:zu,OAuthTokensSchema:ut,OpenIdProviderDiscoveryMetadataSchema:fr,OpenIdProviderMetadataSchema:Ou},lp={},pp={};function mp(e,t){let r=e.slice(0,-6);lp[r]=t,pp[r]=o=>t.safeParse(o).success}n(mp,"register");for(let e of Xy)mp(e,qy[e]);for(let[e,t]of Object.entries(Qy))mp(e,t);var eS=Object.freeze(lp),tS=Object.freeze(pp);function rS(e){switch(e){case"initialize":case"notifications/initialized":return Zn(void 0);case"server/discover":return Zn(vs);default:return}}n(rS,"bootstrapOutboundCodec");var hp=6e4,nS=[dr,Nn,lr,jn],oS=["inputResponses","requestState"];function zl(e,t){let r=e.params;if(!us(r))return{message:e,lifted:{}};let o=r._meta,i=us(o)?nS.filter(u=>u in o):[],s=t==="request"?oS.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let c={},a={...r};if(i.length>0&&us(o)){let u={},p={...o};for(let h of i)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 s)u==="inputResponses"&&(c.inputResponses=a[u]),u==="requestState"&&(c.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:c}}n(zl,"liftWireOnlyMaterial");function Nl(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 i=e.validateResult(t,o);return i.ok?{value:i.value}:{issues:[{message:i.reason==="invalid"?i.message:`not-in-era: ${t}`}]}}}}}n(Nl,"codecResultValidator");function fp(e){return()=>e}n(fp,"requestStateAccessor");var iS=fp(void 0),sS,aS=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{sS=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ni,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(ie.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,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,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(ie.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=i=>{r?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),ms(i)||dp(i)?this._onresponse(i):ap(i)?this._onrequest(i,s):cp(i)?this._onnotification(i,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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(ie.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}=zl(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let c=Ol(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(cs(r.method)&&!o.hasNotificationMethod(r.method))return;let i=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;i===void 0&&s===void 0||Promise.resolve().then(()=>i===void 0?s(r):i(r,o)).catch(c=>this._onerror(new Error(`Uncaught error in notification handler: ${c}`)))}_onrequest(e,t){let{message:r,lifted:o}=zl(e,"request"),i=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 s=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}}};s?.send(O).catch(L=>this._onerror(new Error(`Failed to send an error response: ${L}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=Ol(t.classification);if(w!==i.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${i.era}`));let I=t.classification.revision??w;c(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${I}`,{supported:this._supportedProtocolVersions,requested:I});return}}if(as(r.method)&&!i.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=i.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:cS(o.inputResponses),S={sessionId:s?.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?iS:fp(o.requestState),signal:f.signal,send:n(((w,I,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),hs(I))return h(w,I,U);let L=Nl(O,w.method);if(L===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,L,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=i.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 s?.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:i.encodeErrorCode(I),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await s?.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),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}i(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),ms(e)?r(e):r(se.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),hs(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=Nl(o,e.method);if(i===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,i,t)}_negotiatedWireCodec(){return Zn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=rS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(as(t)&&!e.hasRequestMethod(t))throw new re(ie.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:i,resumptionToken:s,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(ie.RequestTimeout,String(G))}let k=e.era===vs&&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,L=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:i,resumptionToken:s,onresumptiontoken:c}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),y(G instanceof re?G:new re(ie.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(dS(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((ze,$)=>this._requestWithSchemaViaCodec(e,ze===void 0?{method:t.method}:{method:t.method,params:ze},r,$),"retry")};return f(this._resolveNonCompleteResult(V,oe))}let Be=V.result;ds(r,Be).then(oe=>{oe.success?f(oe.data):y(new re(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},y)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??hp,ee=n(()=>L(new re(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,ee,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,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(ie.NotConnected,"Not connected");if(cs(t.method)&&!e.hasNotificationMethod(t.method))throw new re(ie.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(i=>this._onerror(i))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!as(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let c=this._negotiatedWireCodec(),a=c.validateRequest(e,i);if(!a.ok&&a.reason==="not-in-era"&&(a=c.validateInputRequest(e,i)),!a.ok)throw a.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let c=await ds(t.params,{...i.params});if(!c.success)throw new se(P.InvalidParams,`Invalid params for ${e}: ${c.error}`);return r(c.data,s)},"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(!cs(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,i)=>{let s=i.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let i=await ds(t.params,{...o.params});if(!i.success)throw new se(P.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await r(i.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(us,"isPlainObject$1");function jl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(jl,"isPlainObject");function cS(e){let t={},r=[];if(!jl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!jl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(cS,"partitionInputResponses");function dS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(dS,"manualInputRequiredValue");var uS=Tl((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=i;function i(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?s(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(i,"parse");function s(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(s,"getcontenttype");function c(a){this.parameters=Object.create(null),this.type=a}n(c,"ContentType")})),qT=El(uS(),1);var lS=10*1024*1024;function Ts(){ys(),mt(),oy(),Cy(),My()}n(Ts,"preloadSchemas");var VT=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 pS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,mS=[0,31,28,31,30,31,30,31,31,30,31,30,31],hS=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,fS=/^(?=.{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,gS=/^(?:[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,yS=/^(?:(?:[^\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,SS=/^(?:(?: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,_S=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,RS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,bS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,vS=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(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),IS=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,CS=/^((([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,TS=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 $e(e){return e.test.bind(e)}n($e,"bind");var KT={date:gp,time:yp.bind(void 0,!1),"date-time":PS,duration:TS,uri:US,"uri-reference":$e(gS),"uri-template":$e(yS),url:$e(SS),email:vS,hostname:$e(fS),ipv4:$e(IS),ipv6:$e(CS),regex:MS,uuid:$e(_S),"json-pointer":$e(wS),"json-pointer-uri-fragment":$e(RS),"relative-json-pointer":$e(bS)};function kS(e){return e%4===0&&(e%100!==0||e%400===0)}n(kS,"isLeapYear");function gp(e){let t=e.match(pS);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&kS(r)?29:mS[o])}n(gp,"date");function yp(e,t){let r=t.match(hS);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],c=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||c)}n(yp,"time");var ES=/t|\s/i;function PS(e){let t=e.split(ES);return t.length==2&&gp(t[0])&&yp(!0,t[1])}n(PS,"date_time");var AS=/\/|:/,xS=/^(?:[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 US(e){return AS.test(e)&&xS.test(e)}n(US,"uri");var OS=/[^\\]\\Z/;function MS(e){if(OS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(MS,"regex");Ts();var Sp=!1;var ks;ks=globalThis.crypto;async function zS(e){return(await ks).getRandomValues(new Uint8Array(e))}n(zS,"getRandomValues");async function NS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await zS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(NS,"random");async function jS(e){return await NS(e)}n(jS,"generateVerifier");async function DS(e){let t=await(await ks).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(DS,"generateChallenge");async function Es(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await jS(e),r=await DS(t);return{code_verifier:t,code_challenge:r}}n(Es,"pkceChallenge");var Qn=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,Lt(this,new.target)}},Xn=class extends Qn{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}},Os=class extends Qn{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}},ai=class extends Qn{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}},Ps=class extends Qn{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}},qk=class extends Qn{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 _p(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):bp(e.issuer,t)?e:void 0}n(_p,"discardIfIssuerMismatch");function bp(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(bp,"issuersMatch");var zk=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",Lt(this,new.target)}};function vp(e){return e?.authorization_response_iss_parameter_supported===!0}n(vp,"isIssParameterSupported");function Ip({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Xn("authorization_response",t,void 0);return}if(e!==t)throw new Xn("authorization_response",t,e)}}n(Ip,"validateAuthorizationResponseIssuer");function $S(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n($S,"isClientAuthMethod");var As="code",xs="S256";function LS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&$S(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(LS,"selectClientAuthMethod");function HS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":BS(i,s,r);return;case"client_secret_post":FS(i,s,o);return;case"none":GS(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(HS,"applyClientAuthentication");function BS(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(BS,"applyBasicAuth");function FS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(FS,"applyPostAuth");function GS(e,t){t.set("client_id",e)}n(GS,"applyPublicAuth");function Cp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Cp,"isLoopbackHost");function JS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Cp(t.hostname))throw new ai(t.href);return t}n(JS,"assertSecureTokenEndpoint");function VS(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Cp(r.hostname))return"native"}return"web"}n(VS,"deriveApplicationType");function KS(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??VS(t.redirect_uris)}}n(KS,"resolveClientMetadata");async function wp(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=$o.parse(JSON.parse(r));return ht.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ht(ue.ServerError,i)}}n(wp,"parseErrorResponse");async function Ms(e,t){try{return await Us(e,t)}catch(r){if(r instanceof ht){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Us(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await Us(e,t)}throw r}}n(Ms,"auth");function WS(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:i}=e,s=t||r?.scopes_supported?.join(" ")||i.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&i.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}n(WS,"determineScope");async function Us(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:c,skipIssuerMetadataValidation:a,forceReauthorization:u}){let p=KS(e),h=await e.discoveryState?.(),f,y,S,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(y=h.authorizationServerUrl,f=h.resourceMetadata,S=h.authorizationServerMetadata??await Pp(y,{fetchFn:c,skipIssuerValidation:a}),!f)try{f=await kp(t,{resourceMetadataUrl:w},c)}catch($){if($ instanceof TypeError)throw $}(S!==h.authorizationServerMetadata||f!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S})}else{let $=await t_(t,{resourceMetadataUrl:w,fetchFn:c,skipIssuerMetadataValidation:a});y=$.authorizationServerUrl,S=$.authorizationServerMetadata,f=$.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 $=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if($===void 0){if(e.saveDiscoveryState!==void 0)throw new Ps("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(!bp($,I))throw new Ps($,I)}k&&await e.saveDiscoveryState?.(k);let O=await ZS(t,e,f);O&&await e.saveResourceUrl?.(String(O));let L=WS({requestedScope:i,resourceMetadata:f,authServerMetadata:S,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),ee=_p(F,I,{canPersistStamp:e.saveClientInformation!==void 0});if(ee===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new Ps(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 $=S?.client_id_metadata_document_supported===!0,Ae=e.clientMetadataUrl;if(Ae&&!qs(Ae))throw new ht(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ae}`);if($&&Ae)ee={client_id:Ae,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 s_(y,{metadata:S,clientMetadata:p,scope:L,fetchFn:c}),issuer:I},await e.saveClientInformation(ee,U)}}let G=!e.redirectUrl;if(r!==void 0||G){r!==void 0&&Ip({iss:o,expectedIssuer:S?.issuer,issParameterSupported:vp(S)});let $=await i_(e,y,{metadata:S,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:c});return await e.saveTokens({...$,issuer:I},U),"AUTHORIZED"}let V=_p(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 $=await o_(y,{metadata:S,clientInformation:ee,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:c});return await e.saveTokens({...$,issuer:I},U),"AUTHORIZED"}catch($){if($ instanceof ai||!(!($ instanceof ht)||$.code===ue.ServerError))throw $}let Be=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:ze}=await r_(y,{metadata:S,clientInformation:ee,state:Be,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(ze),await e.redirectToAuthorization(oe),"REDIRECT"}n(Us,"authInternal");function qs(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(qs,"isHttpsUrl");async function ZS(e,t,r){let o=$l(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ni({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(ZS,"selectResourceURL");function Tp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=si(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let c=si(e,"scope")||void 0,a=si(e,"error")||void 0,u=si(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:c,error:a,errorDescription:u}}n(Tp,"extractWWWAuthenticateParams");function si(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=r.match(o);if(i){let s=i[1]||i[2];if(s)return s}return null}n(si,"extractFieldFromWwwAuth");async function kp(e,t,r=fetch){let o=await QS(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 mr.parse(await o.json())}n(kp,"discoverOAuthProtectedResourceMetadata");async function Ep(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!Sp)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(Ep,"fetchWithCorsRetry");function YS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(YS,"buildWellKnownPath");async function Rp(e,t,r=fetch){return await Ep(e,{"MCP-Protocol-Version":t},r)}n(Rp,"tryMetadataDiscovery");function XS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(XS,"shouldAttemptFallback");async function QS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??qo,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=YS(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let a=await Rp(c,s,r);return!o?.metadataUrl&&XS(a,i.pathname)&&(a=await Rp(new URL(`/.well-known/${t}`,i),s,r)),a}n(QS,"discoverMetadataWithFallback");function e_(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 i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(e_,"buildDiscoveryUrls");async function Pp(e,{fetchFn:t=fetch,protocolVersion:r=qo,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=e_(e);for(let{url:c,type:a}of s){let u=await Ep(c,i,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"?hr.parse(await u.json()):fr.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 Xn("metadata",h,p.issuer)}return p}}n(Pp,"discoverAuthorizationServerMetadata");async function t_(e,t){let r,o;try{r=await kp(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let i=await Pp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(t_,"discoverOAuthServerInfo");async function r_(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:c}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(As))throw new Error(`Incompatible auth server: does not support response type ${As}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(xs))throw new Error(`Incompatible auth server: does not support code challenge method ${xs}`)}else a=new URL("/authorize",e);let u=await Es(),p=u.code_verifier,h=u.code_challenge;return a.searchParams.set("response_type",As),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",xs),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),i&&a.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),c&&a.searchParams.set("resource",c.href),{authorizationUrl:a,codeVerifier:p}}n(r_,"startAuthorization");function n_(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(n_,"prepareAuthorizationCodeRequest");async function Ap(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:c}){let a=JS(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",s.href),i?await i(u,r,a,t):o&&HS(LS(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 wp(p);let h=await p.json();try{return ut.parse(h)}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await wp(JSON.stringify(h)):f}}n(Ap,"executeTokenRequest");async function o_(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:c}){return{refresh_token:o,...await Ap(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:c})}}n(o_,"refreshAuthorization");async function i_(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:c,fetchFn:a}={}){i!==void 0&&Ip({iss:s,expectedIssuer:r?.issuer,issParameterSupported:vp(r)});let u=c??e.clientMetadata.scope,p;if(e.prepareTokenRequest&&(p=await e.prepareTokenRequest(u)),!p){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");p=n_(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return Ap(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(i_,"fetchToken");async function s_(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let c={...r,...o===void 0?{}:{scope:o}},a=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Os({status:a.status,body:await a.text(),submittedMetadata:c});return Dt.parse(await a.json())}n(s_,"registerClient");var Nk=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,Lt(this,new.target)}};function a_(e){let t=jt.safeParse(e);return t.success?t.data.id:void 0}n(a_,"parseJsonRpcRequestId");function xp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return a_(t)}catch{return}}n(xp,"readJsonRpcRequestIdFromBody");function ci(e){return Dn.parse({jsonrpc:pr,...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(ci,"jsonRpcErrorResponse");function Up(e){return new ii([Do.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Up,"urlElicitationRequiredError");var ui=l.record(l.string(),l.unknown()),c_=l.record(l.string(),l.unknown()),gt=l.array(l.string().min(1)).min(1).optional(),d_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:c_.optional(),_meta:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),u_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),l_=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:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),p_=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:ui.optional(),roles:gt,groups:gt,public:l.boolean().optional()}).strict(),m_=l.array(l.union([l.string(),d_])),h_=l.array(l.union([l.string(),u_])),f_=l.array(l.union([l.string(),l_])),g_=l.array(l.union([l.string(),p_])),y_=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),S_=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:y_.optional()}).strict(),__=l.object({tools:m_.optional(),prompts:h_.optional(),resources:f_.optional(),resourceTemplates:g_.optional(),accessControl:S_.optional()}).strict(),ft=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function w_(e,t){return Du(__,e,`MCP capability filter policy "${t}"`)}n(w_,"parseMcpCapabilityFilterOptions");function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(_e,"isRecord");function eo(e){return typeof e.method=="string"?e.method:void 0}n(eo,"messageMethod");function Op(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Op,"correlationKey");function Mp(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Mp,"asStringArray");function qp(e,t){if(!_e(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>_e(o)?o[i]: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(qp,"readClaimValues");function js(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:Mp(e.roles),groups:Mp(e.groups),public:e.public===!0}}n(js,"normalizeEntry");function R_(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(s=>t.has(s))||i.some(s=>r.has(s))}n(R_,"isCallerAllowed");function di(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let c=js(s,t);c!==void 0&&R_(c,r,o)&&i.push(c.key)}return i}n(di,"allowedKeys");var jp=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(qp(e.user?.data,o)),c=new Set(qp(e.user?.data,i));return{tools:di(r.tools,"name",s,c),prompts:di(r.prompts,"name",s,c),resources:di(r.resources,"uri",s,c),resourceTemplates:di(r.resourceTemplates,"uriTemplate",s,c)}},"claimsCapabilityResolver");function b_(e,t){let r=[];for(let o of ft){let i=e[o.option];if(i!==void 0)for(let s of i){let c=js(s,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(b_,"assertNoConflictingMarkup");function v_(e,t){let r=[];for(let o of ft){let i=e[o.option];if(i!==void 0)for(let s of i){let c=js(s,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(v_,"assertNoMarkup");function I_(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 i=o;return async(s,c,a)=>{let u=await i(s,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(I_,"buildCustomResolver");function C_(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 I_(r,t)}if(o==="rolesAndGroups")return b_(e,t),jp;v_(e,t)}n(C_,"buildCapabilityResolver");function T_(e){let t={};for(let r of ft){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let c=x_(s,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(T_,"buildProjectionMaps");function zs(e){return e===void 0?void 0:ft.find(t=>t.listMethod===e)}n(zs,"findListRule");function k_(e){return e===void 0?void 0:ft.find(t=>t.directMethods.includes(e))}n(k_,"findDirectRule");function E_(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(E_,"directCapabilityAccess");function P_(e){let t=k_(eo(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(P_,"rawDirectCapabilityAccess");function A_(e){return Response.json(ci({...e==null?{}:{id:e},error:{code:P.MethodNotFound,message:"Method not found"}}))}n(A_,"methodNotFoundResponse");function x_(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(x_,"buildProjection");function zp(e){let t=e.base[e.property],r=e.overlay[e.property];return _e(r)?_e(t)?{...t,...r}:r:t}n(zp,"mergeRecordProperty");function U_(e,t){let r={...e,...t.overlay},o=zp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=zp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(U_,"applyProjection");function Np(e,t,r,o){if(!_e(e))return e;let i=e.result;if(!_e(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(c=>_e(c)&&typeof c[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.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?[]:[U_(c,u)]})}}}n(Np,"filterAndProjectItems");function O_(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let p of t.messages){let h=zs(eo(p)),f=h===void 0?void 0:Op(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=Op(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:Np(p,f,y,i?.[f.option])})}if(t.shape!=="single"||!_e(r)||"error"in r)return r;let s=t.messages[0],c=zs(s===void 0?void 0:eo(s)),a=c===void 0?void 0:o[c.option];return c===void 0||a===void 0?r:Np(r,c,a,i?.[c.option])}n(O_,"filterResponseBody");function M_(e){return e.headers.get("content-type")?.includes("json")??!1}n(M_,"isJsonResponse");var Ns=class extends Mo{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=w_(t,r);super(o,r),this.#r=r,this.#e=T_(o),this.#t=C_(o,r)}async handler(t,r){let o=await Cl(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let c of o.messages){let a=c.type==="request"?E_(c):P_(c);if(a===void 0)continue;let u=this.#e[a.option];if(u===void 0)continue;let p=i?.[a.option];if(!u.has(a.target)||p!==void 0&&!p.has(a.target))return A_(c.type==="request"?c.id:c.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async c=>{if(!M_(c))return c;let a;try{a=await c.clone().json()}catch{return c}let u=O_({envelope:o,responseBody:a,projectionMaps:s,allowedSets:i});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=eo(r);return o===void 0?!1:ft.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#o(t){return t.messages.some(r=>{let o=zs(eo(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#i(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=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 ft)this.#e[u.option]!==void 0&&(a[u.option]=new Set);return a}let s={};for(let c of ft){let a=this.#e[c.option];if(a===void 0)continue;let u=i[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);s[c.option]=p}return s}};var Ds="zuplo.com",q_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),z_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Dp(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Dp,"s2FaviconHref");function N_(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(N_,"strictFaviconHref");var li=Dp(Ds);function $s(e){let t=e.toLowerCase();return t===Ds||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Dp(Ds):N_(e)}n($s,"resolveIconHref");function j_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(j_,"hostnameFromHost");function D_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(D_,"isLocalOrAddressHost");function $_(e){let t=j_(e).toLowerCase().replace(/\.$/,"");if(D_(t)||z_.some(s=>t===s.slice(1)||t.endsWith(s)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=q_.has(o)?3:2;return r.slice(-i).join(".")}n($_,"inferFaviconDomain");function Ls(e){return{src:$s($_(e)),mimeType:"image/png",sizes:["128x128"]}}n(Ls,"resolveMcpFaviconIcon");function pi(e){try{return Ls(new URL(e).host)}catch{return}}n(pi,"resolveMcpFaviconIconFromUrl");function yt(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(yt,"getUpstreamServerConfig");function mi(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(mi,"getUpstreamAuthConfig");function Tr(e,t){let r=mi({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(Tr,"requireUpstreamOAuthConfig");function $p(e,t){let r=mi({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($p,"requireUpstreamIdJagConfig");function Lp(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(Lp,"mergeAbortSignals");async function L_(e){try{await e.cancel()}catch{}}n(L_,"cancelReader");async function hi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,s=await r.read();for(;!s.done;){let u=s.value;if(i+=u.byteLength,i>t.maxBytes)throw await L_(r),t.createLimitError();o.push(u),s=await r.read()}let c=new Uint8Array(i),a=0;for(let u of o)c.set(u,a),a+=u.byteLength;return c}n(hi,"readBoundedByteStream");var H_=2,B_=1024*1024,F_=1e4,G_=new Set([301,302,303,307,308]),J_=["authorization","proxy-authorization","cookie","cookie2"];function Hs(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Hs,"readRequestUrl");function kr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(kr,"readRequestMethod");function V_(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}})}n(V_,"assertContentLengthWithinLimit");async function K_(e,t,r){return V_(e,t,r),hi(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[C]:r}}),"createLimitError")})}n(K_,"readBoundedResponseBody");function W_(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(W_,"responseFromBufferedBody");function Z_(e,t){if(!G_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Z_,"resolveRedirectUrl");function Hp(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(Hp,"validateOutboundUrl");function Y_(e,t){throw e instanceof v&&Ho(e.extensionMembers?.[C])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[C]:t}},{cause:e})}n(Y_,"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,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&pe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(to,"logOutboundFailure");async function X_(e,t,r,o,i,s,c){let a=kr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";to(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:a,host:te(s),error:u,extra:{abortReason:c()}}),Y_(u,i)}}n(X_,"fetchWithNormalizedError");function Q_(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(Q_,"assertRedirectAllowed");function ew(e,t){let r=new Headers(e);for(let o of J_)r.delete(o);for(let o of t)r.delete(o);return r}n(ew,"stripCrossOriginHeaders");function tw(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=ew(e.headers,i)),s}n(tw,"buildRedirectInit");function rw(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(rw,"buildInitialRequestInit");function nw(e){let t=kr(e.currentInput,e.currentInit);Q_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Hp(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:tw(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(nw,"followRedirect");async function Bs(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??H_,s=r.maxResponseBytes??B_,c=r.timeoutMs??F_,a=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,f=Lp(h,t.signal),y=!1,S=setTimeout(()=>{y=!0,h.abort()},c),k=e,w=rw(e,t,h.signal),I;try{I=Hp(Hs(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw to(p,{event:"outbound_url_blocked",problemCode:o,method:kr(e,t),host:te(Hs(e)),error:O}),clearTimeout(S),f?.(),O}let U=0;try{for(;;){let O=await X_(p,a,k,w,o,I,()=>y?`timeout_after_${c}ms`:void 0),L=Z_(O,I);if(L!==void 0)try{let F=nw({currentInput:k,currentInit:w,currentUrl:I,redirectUrl:L,redirects:U,maxRedirects:i,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 to(p,{event:"outbound_redirect_blocked",problemCode:o,method:kr(k,w),host:te(I),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:te(L)}}),F}try{return W_(O,await K_(O,s,o))}catch(F){throw to(p,{event:"outbound_response_size_exceeded",problemCode:o,method:kr(k,w),host:te(I),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(S),f?.()}}n(Bs,"runSafeOutboundExchange");async function ro(e,t,r){let o=await Bs(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw to(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:kr(e,t),host:te(Hs(e)),error:i,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:i})}}n(ro,"runSafeOutboundJsonExchange");function Bp(e,t={},r={}){return Bs(e,t,{...r,validateUrl:Fn})}n(Bp,"fetchConfiguredOutbound");function Fp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Fn})}n(Fp,"fetchConfiguredOutboundJson");function fi(e,t={},r={}){return ro(e,t,{...r,validateUrl:hl})}n(fi,"fetchIdentityProviderJson");function Gp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Wo})}n(Gp,"fetchCimdClientMetadataJson");function Jp(e,t={},r={}){return ro(e,t,{...r,validateUrl:Gn})}n(Jp,"fetchCimdClientJwksJson");import{errors as Xp,jwtVerify as Qp,SignJWT as em}from"jose";var we="zuplo-mcp-gateway",Ce=we,Te="HS256";import{base64url as ow}from"jose";var iw=new TextEncoder,sw="MCP gateway could not initialize secure key material.",aw=32,Vp=new Map,Kp=new Map,cw;function dw(){return cw??Da.instance.authPrivateKey}n(dw,"readAuthPrivateKey");function Wp(e){return new ye(sw,e===void 0?void 0:{cause:e})}n(Wp,"createGeneratedKeyMaterialError");function Zp(e,t){let r=ow.decode(t);if(r.byteLength!==aw)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Zp,"decodeJwkKeyField");function uw(e){let t=dw();if(!t)throw Wp();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=Zp("d",r.d);Zp("x",r.x);let i=iw.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),s=new Uint8Array(i.byteLength+o.byteLength);return s.set(i),s.set(o,i.byteLength),s}catch(r){throw Wp(r)}}n(uw,"decodeGeneratedKeyMaterial");function lw(e){let t=Vp.get(e);return t||(t=uw(e),Vp.set(e,t)),t}n(lw,"getMasterKeyMaterial");async function Le(e){let t=Kp.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(lw(e.keyMaterialPurpose));return Kp.set(e.purpose,r),r}n(Le,"readCachedDerivedKey");var pw="SHA-256",mw=32,hw="zuplo-mcp-gateway:",fw=new TextEncoder,Yp=new WeakMap;async function St(e,t){let r=Yp.get(e);r||(r=new Map,Yp.set(e,r));let o=r.get(t);if(o)return o;let i=await gw(e,t);return r.set(t,i),i}n(St,"deriveGatewaySigningKey");async function gw(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=fw.encode(`${hw}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:pw,salt:new Uint8Array,info:me(i)},o,mw*8);return new Uint8Array(s)}n(gw,"hkdfExpand");var tm=900,yw=900,Sw=Zu.extend({id:_l}),_w=Sw.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),rm=Yi.extend({id:wl,purpose:l.literal("browser_connect")}),ww=Yi.extend({purpose:l.literal("browser_connect")}),Rw=rm.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),nm=tm*1e3;async function om(){return Le({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>St(e,"oauth-state"),"derive")})}n(om,"getOAuthStateKey");async function im(){return Le({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>St(e,"browser-connect"),"derive")})}n(im,"getBrowserConnectKey");async function sm(e){let t=Math.floor(Date.now()/1e3)+tm;return new em(e).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await om())}n(sm,"signOAuthState");async function gi(e){try{let{payload:t}=await Qp(e,await om(),{algorithms:[Te],issuer:we,audience:Ce});return _w.parse(t)}catch(t){throw t instanceof Xp.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(gi,"verifyOAuthState");async function am(e){let t=Math.floor(Date.now()/1e3)+yw,r=ww.parse(e),o=rm.parse({...r,id:Il()});return new em(o).setProtectedHeader({alg:Te,typ:"JWT"}).setIssuer(we).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await im())}n(am,"signBrowserConnectTicket");async function cm(e){try{let{payload:t}=await Qp(e,await im(),{algorithms:[Te],issuer:we,audience:Ce});return Rw.parse(t)}catch(t){throw t instanceof Xp.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(cm,"verifyBrowserConnectTicket");async function dm(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(dm,"consumeBrowserConnectTicket");function bw(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(bw,"buildConnectRequiredMessage");async function vw(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 am({...Hn(e),purpose:"browser_connect"})),r.toString()}n(vw,"buildGatewayBrowserTicketUrl");function Iw(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Iw,"buildGatewayConnectPath");async function Fs(e){return vw({...e,path:Iw(e.upstreamServerId),redirect:!0})}n(Fs,"buildGatewayConnectUrl");async function yi(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 Fs(t),message:bw(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(yi,"buildRedirectConnectRequiredResponse");function um(e){return Cw({...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(um,"buildAdminConnectRequiredResponse");function Cw(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(Cw,"buildAdminSetupRequiredResponse");var lm=12;async function pm(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(pm,"sha256Hex");async function Ht(e){if(e)return(await pm(e)).slice(0,lm)}n(Ht,"fingerprintSecret");async function Er(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await pm(t)).slice(0,lm)}n(Er,"fingerprintConnectionIdentity");var Tw=6e4;function Pr(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(Pr,"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()+Tw)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var mm=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function kw(e,t){return e&&e.length>0?e.join(t):void 0}n(kw,"joinOAuthScopes");function Ew(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of mm)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Ew,"sanitizeAuthorizationServerMetadata");function hm(e){let t=Ew(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(hm,"sanitizeOAuthDiscoveryState");function fm(e){let t=new URL(e);for(let r of mm){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(fm,"dedupeSingletonAuthorizationRequestParams");function Si(e){let t=new URL(e);return ve(t)&&ju(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Si,"normalizeLoopbackOAuthRedirectUri");function gm(e){return kw(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(gm,"readProtectedResourceMetadataScope");function Pw(e){return`Zuplo MCP Gateway - ${e}`}n(Pw,"buildGatewayOAuthClientName");function Aw(e,t){return e&&e.length>0?e.join(t):void 0}n(Aw,"joinOAuthScopeList");function xw(e){if(e.clientRegistration.mode!=="auto")return Aw(e.scopes,e.scopeDelimiter)}n(xw,"readPublicClientMetadataScope");function Gs(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Gs,"buildOAuthClientMetadataDocumentUrl");function Js(e){let t=yt(e.upstreamServerId);return{client_name:Pw(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(Js,"buildGatewayOAuthClientMetadata");function ym(e,t,r){let o=Tr(t,r),i=xw(o);return{client_id:Gs({origin:e,upstreamServerId:t}),...Js({origin:e,upstreamServerId:t,redirectUri:Si(new URL(o.redirectPath,e)).toString(),scope:i})}}n(ym,"buildOAuthClientMetadataDocument");import{base64url as _t}from"jose";var Uw="SHA-256",Ar="AES-GCM",Ow=12,Ks="zuplo-secret",Ws=1,Sm="generated:auth_private_key:token-encryption",Mw=l.object({version:l.literal(Ws),keyId:l.literal(Sm),algorithm:l.literal(Ar),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Vs(){return Le({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Uw,me(e));return crypto.subtle.importKey("raw",t,{name:Ar},!1,["encrypt","decrypt"])},"derive")})}n(Vs,"getEncryptionKey");function _m(e){return me(new TextEncoder().encode(`${Ks}:v${e.version}:${e.keyId}`))}n(_m,"getAssociatedData");function qw(e){return`${Ks}:v${e.version}:${_t.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(qw,"encodeEnvelope");function zw(e){let t=`${Ks}:v${Ws}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(_t.decode(r));return Mw.parse(JSON.parse(o))}n(zw,"decodeEnvelope");async function Xe(e){let t=await Vs(),r=crypto.getRandomValues(new Uint8Array(Ow)),o={version:Ws,keyId:Sm},i=await crypto.subtle.encrypt({name:Ar,iv:r,additionalData:_m(o)},t,new TextEncoder().encode(e));return qw({...o,algorithm:Ar,iv:_t.encode(r),ciphertext:_t.encode(new Uint8Array(i))})}n(Xe,"encryptSecret");async function Qe(e){let t=zw(e);if(t){let c=await Vs(),a=await crypto.subtle.decrypt({name:Ar,iv:me(_t.decode(t.iv)),additionalData:_m(t)},c,me(_t.decode(t.ciphertext)));return new TextDecoder().decode(a)}let[r,o]=e.split(".");if(!r||!o)throw new ye("Encrypted payload is malformed");let i=await Vs(),s=await crypto.subtle.decrypt({name:Ar,iv:me(_t.decode(r))},i,me(_t.decode(o)));return new TextDecoder().decode(s)}n(Qe,"decryptSecret");var wm={issuer:l.string().min(1).optional()},Nw=l.union([Dt.extend(wm),$n.extend(wm)]),Rm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:mr.optional(),authorizationServerMetadata:l.union([hr,fr]).optional()}).passthrough(),jw="Bearer",Dw="__zuplo_refresh_only_upstream_access_token__";function Zs(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Zs,"splitScopes");function Ys(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ys,"scopesCover");function $w(e){return yr.parse(e)}n($w,"parsePkceCodeVerifier");function Lw(e){if(typeof e.expires_in=="number")return D(new Date(Date.now()+e.expires_in*1e3))}n(Lw,"readTokenExpiry");async function bm(e){if(e!==void 0)return Xe(JSON.stringify(e))}n(bm,"encryptJson");async function vm(e,t){if(!e)return;let r=await Qe(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(vm,"decryptJson");function Hw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Hw,"clientInformationAllowsRedirectUri");function Bw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Bw,"clientInformationMatchesCurrentClientMetadataUrl");function Fw(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Fw,"isUrlBasedClientInformation");function Gw(e,t){return t===void 0?e:{...e,scope:t}}n(Gw,"applyOAuthClientMetadataScope");function Jw(e,t){return gm({state:e,delimiter:t})}n(Jw,"readResourceMetadataScope");function Vw(e,t){return e&&e.length>0?e.join(t):void 0}n(Vw,"joinOAuthScopeList");function Kw(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 Dt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Kw,"buildManualOAuthClientInformation");function Ww(e,t){let r=Gs({origin:new URL(t).origin,upstreamServerId:e});return qs(r)?r:void 0}n(Ww,"buildClientMetadataUrl");function Zw(e){for(let t of e)if(t!==void 0)return t}n(Zw,"firstDefined");function Yw(e){let t=Tr(e.target.upstreamServerId,e.target.authProfileId),r=Vw(t.scopes,t.scopeDelimiter),o=Js({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:Kw({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Ww(e.target.upstreamServerId,e.redirectUri);return i===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:i}}n(Yw,"buildInitialOAuthClientSetup");function Xw(e,t){if(t===void 0)return Zw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Xw,"readEncryptedClientInformation");function Qw(e){return e.pendingState?.encryptedDiscoveryState}n(Qw,"readEncryptedDiscoveryState");function Xs(e,t){return t===void 0?e:{...e,issuer:t}}n(Xs,"applyIssuerStamp");var wt=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=Yw({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=Xw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Qw(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=Zs(this.configuredScope??r??this.readEffectiveScope());return Ys(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 Er({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Ht(await Qe(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await N().conditionalUpsertUpstreamConnection(t,r)}catch(o){let i=W();if(i){let s=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});i.error(s,"Upstream OAuth conditional storage write failed")}throw o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Gw(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return sm({id:t.id,...Hn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?Xs(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"),!Fw({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await bm(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ni({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=hm(Rm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await bm(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=Jw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Zs(this.configuredScope).filter(s=>!o.includes(s));i.length>0&&W()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,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 Xs(r,t?.issuer)}async saveTokens(t){let r=ut.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await Xe(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:ut.parse({...r,refresh_token:await Qe(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:i?.id??Zo(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Xe(r.access_token),encryptedRefreshToken:c,scopes:Zs(r.scope??this.readEffectiveScope()),expiresAt:Lw(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},u=i?{expectedUpdatedAt:i.updatedAt}:{expectAbsent:!0},p=await this.conditionalUpsertCredential(a,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ys(p.connection.scopes,a.scopes)||!Pr(i,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:i?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:i?.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,Pr(i,p.connection)&&he(p.connection)==="usable"&&Ys(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:i?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:i?.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:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Ht(r.refresh_token),reusedSnapshotRefreshToken:s,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=fm(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:$w(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",i=t==="all"||t==="discovery",s=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(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(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:vl(),...Hn({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()+nm)),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 vm(this.encryptedClientInformation,Nw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!Hw(r,this.redirectUriValue)||!Bw({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=Xs($n.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 vm(this.encryptedDiscoveryState,Rm)}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 Qe(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Qe(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Ht(o):void 0,i?.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 s=ut.parse({access_token:r??Dw,token_type:jw,refresh_token:o,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=s,s}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let o=r.status,i=r.updatedAt,s={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&&(s.status="reconsent_required",s.encryptedAccessToken=void 0,s.encryptedRefreshToken=void 0,s.scopes=[],s.expiresAt=void 0),s.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let c=await this.conditionalUpsertCredential(s,{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,Pr(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:i,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 eR=3e4,tR=256*1024,rR=2,nR="does not support dynamic client registration",oR=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],iR=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],sR=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],aR="Protected resource ",cR=" does not match expected ",dR=["HTTP 403 Forbidden","Access Denied","permission to access"],uR=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function lR(e){return e instanceof Error&&e.message.includes(nR)}n(lR,"isDynamicClientRegistrationUnsupported");function pR(e){return e instanceof Error&&oR.some(t=>e.message.includes(t))}n(pR,"isProtectedResourceMetadataUnavailable");function mR(e){return e instanceof Error&&iR.some(t=>e.message.includes(t))}n(mR,"isAuthorizationServerMetadataUnavailable");function hR(e){return e instanceof Error&&sR.some(t=>e.message.includes(t))}n(hR,"isAuthorizationServerIncompatible");function fR(e){return e instanceof Error&&e.message.includes(aR)&&e.message.includes(cR)}n(fR,"isProtectedResourceMismatch");function gR(e){return e instanceof Error&&dR.some(t=>e.message.includes(t))}n(gR,"isUpstreamProviderAccessDenied");function yR(e){return e instanceof ht&&uR.has(e.code)}n(yR,"isStoredConnectionReconsentError");function et(e){let t=e.diagnostics??{};return new v({message:e.message,extensionMembers:{[C]:e.code,[Lo]:e.upstreamServerId,[wr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[Ve]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[Je]:t.httpStatus},...t.providerError===void 0?{}:{[Rr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[br]:t.providerErrorDescription}}},{cause:e.cause})}n(et,"buildUpstreamSetupProblem");function SR(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(SR,"describeIssuerMetadataMismatch");var _R=128,wR=256;function Im(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Im,"truncateProviderDetail");function RR(e){let{error:t,errorDescription:r}=Tm(e.body),o=Im(t,_R),i=Im(r,wR);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...i===void 0?{}:{providerErrorDescription:i}}}n(RR,"readRegistrationRejectionDiagnostics");function bR(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(bR,"describeRegistrationRejection");function vR(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(vR,"readDiscoveryEndpointUrl");function IR(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(lR(e.error))return et({...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 Os){let r=RR(e.error);return et({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${bR(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 Xn&&e.error.kind==="metadata")return et({...t,code:"upstream_oauth_issuer_mismatch",message:SR(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ai)return et({...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(hR(e.error))return et({...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(mR(e.error)){let r=vR(e.error.message);return et({...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(fR(e.error))return et({...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(pR(e.error))return et({...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(gR(e.error))return et({...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(IR,"mapUpstreamOAuthSetupError");function CR(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(CR,"readOAuthFetchRequest");function TR(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(TR,"readOAuthFetchMethod");function kR(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(kR,"responseLooksJson");function ER(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(ER,"responseLooksHtml");var PR=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function AR(e){return PR.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(AR,"isMetadataDiscoveryRequest");function xR(e,t,r){return e!=="GET"||!AR(t)?!1:r>=400&&r<500||r===502}n(xR,"sdkRetriesDiscoveryCandidate");function UR(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",[Je]:e.response.status,[Sr]:r,[Ve]:e.request.url.toString(),[_r]:e.body}})}n(UR,"throwUpstreamHtmlError");function Tm(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(Tm,"readUpstreamOAuthErrorBody");function OR(e){let{error:t,errorDescription:r}=Tm(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(OR,"logUpstreamOAuthHttpError");function km(e){return async(t,r)=>{let o=CR(t),i=TR(t,r),s=W(),c=Date.now(),a=await Bp(t,r,{maxRedirects:rR,maxResponseBytes:tR,problemCode:"upstream_token_exchange_failed",timeoutMs:eR}),u=await a.clone().text();if(s?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,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||OR({log:s,upstreamServerId:e,method:i,request:o,response:a,body:u}),xR(i,o.url,a.status)||(!a.ok&&ER(a,u)&&UR({upstreamServerId:e,request:o,response:a,body:u}),!kR(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(km,"createUpstreamOAuthFetch");function Em(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(Em,"logUpstreamOAuthFlowStarted");function Pm(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(Pm,"logUpstreamOAuthFlowFailed");function Am(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Am,"readAuthorizationRequestScope");async function xm(e,t){e.applyChallengeScope(t.requestedScope),Em({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:km(t.upstreamServerId)},o=Am(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await Ms(e,r)}catch(r){Pm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=IR({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(xm,"runUpstreamOAuth");async function MR(e,t){e.applyChallengeScope(t.requestedScope),Em({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:km(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Am(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await Ms(e,r)}catch(i){throw Pm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(MR,"exchangeUpstreamAuthorizationCode");async function Cm(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"||!Pr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(Cm,"adoptPeerCredentialAtResolutionBoundary");async function Um(e,t){let r=await xm(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(Um,"requireUpstreamAuthorizationRedirect");async function Om(e){let t=he(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),i=W(),s=i?await Er({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:s,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 xm(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||!yR(a))throw a;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:a.code,connectionFingerprint:s,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 Cm({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 Qs({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 Qs({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 Cm({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 Qs({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(Om,"authorizeUpstreamOAuthSession");async function qR(e){let t=await gi(e.stateToken),r=await N().consumeUpstreamOAuthState({id:t.id,now:D(new Date)}),o=zR(r);return NR({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),jR(o),o}n(qR,"consumeStoredCallbackState");function zR(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(zR,"readConsumedCallbackState");function NR(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(NR,"assertStoredCallbackStateMatches");function jR(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[C]:"oauth_state_expired"}})}n(jR,"assertStoredCallbackStateFresh");async function Qs(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),um(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),yi(t)}n(Qs,"buildOAuthConnectRequiredResponse");async function Mm(e){let t=await qR({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Go(t),[o]=await N().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={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&&(i.connection=o);let s=new wt(i),c=await MR(s,{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=s.readUsablePeerAdoption();if(a!==void 0&&await s.adoptConnectionForDirectResolution(a,"cas_loss"),!s.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(Mm,"finishUpstreamOAuthCallback");import{importPKCS8 as DR,SignJWT as $R}from"jose";var zm=1e4,Nm=64*1024,jm=2,LR=300,Me=l.string().min(1),HR=l.object({access_token:Me,issued_token_type:l.literal(Qi),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:Me.optional()}).passthrough(),BR=l.object({id_token:Me,token_type:Me.optional(),expires_in:l.number().int().positive().optional(),refresh_token:Me.optional(),scope:Me.optional()}).passthrough(),FR=l.object({access_token:Me,token_type:Me,expires_in:l.number().int().positive().optional(),scope:Me.optional(),resource:Me.optional(),refresh_token:Me.optional()}).passthrough();function qm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(qm,"formEncodeClientCredential");function GR(e){return e.replaceAll("\\n",`
26
26
  `)}n(GR,"normalizePem");async function JR(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??LR,o=await DR(GR(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new $R({jti:crypto.randomUUID()}).setProtectedHeader(i).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(JR,"createPrivateKeyJwtClientAssertion");async function VR(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=qm(e.clientAuth.clientId),r=qm(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",Vo),e.form.set("client_assertion",await JR({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(VR,"appendClientAuthentication");async function ea(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await VR({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(ea,"buildFormRequest");function Dm(e){return(t,r)=>fi(t,r,{context:e,maxRedirects:jm,maxResponseBytes:Nm,problemCode:"upstream_token_exchange_failed",timeoutMs:zm})}n(Dm,"defaultIdpFetchJson");function KR(e){return(t,r)=>Fp(t,r,{context:e,maxRedirects:jm,maxResponseBytes:Nm,problemCode:"upstream_token_exchange_failed",timeoutMs:zm})}n(KR,"defaultResourceAsFetchJson");function _i(e){let t={[C]:e.code,[Ve]:e.tokenUrl};return e.response!==void 0&&(t[Je]=e.response.status),new v({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(_i,"runtimeError");function ta(e){if(!e.response.ok)throw _i({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(ta,"assertTokenEndpointSucceeded");function WR(e){let t=BR.safeParse(e.json);if(!t.success)throw _i({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(WR,"parseIdpRefreshTokenResponse");function ZR(e){let t=HR.safeParse(e.json);if(!t.success)throw _i({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(ZR,"parseIdJagTokenExchangeResponse");function YR(e){let t=FR.safeParse(e.json);if(!t.success)throw _i({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(YR,"parseAccessTokenResponse");async function $m(e){let t=new URLSearchParams({grant_type:Jo,requested_token_type:Qi,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??Dm(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await ea({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return ta({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),ZR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n($m,"requestIdJag");async function Lm(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Dm(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await ea({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return ta({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),WR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Lm,"refreshIdpSubjectToken");async function Hm(e){let t=new URLSearchParams({grant_type:pt,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??KR(e.context),{response:o,json:i}=await r(e.resourceAs.tokenUrl,await ea({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return ta({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),YR({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Hm,"exchangeIdJagForAccessToken");function XR(e){return he(e)==="usable"}n(XR,"hasUsableAccessToken");function QR(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(QR,"assertBearerToken");function Bm(e,t){if(t===Cr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Bm,"hasExpiredSubjectToken");async function eb(e){let t=await Qe(e.encryptedSubjectToken);if(e.subjectTokenType!==Cr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Lm({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:Bn};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 Xe(r.refreshToken),idpSubjectTokenType:Cr,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 Ht(t),newSubjectRefreshTokenFingerprint:await Ht(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:Bn}}n(eb,"resolveIdJagSubjectToken");async function Fm(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,i=!o&&r==="usable",s=W(),c=s?await Er({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(s?.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:!i,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},i?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&XR(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Qe(t.encryptedAccessToken)}};let a=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||a===void 0||u===void 0||Bm(t,u))return s?.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&&Bm(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=yt(e.upstreamServerId),h=$p(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 eb({connection:t,connectionFingerprint:c,encryptedSubjectToken:a,subjectTokenType:u,idp:{tokenUrl:h.idp.tokenUrl},clientAuth:h.idp.clientAuth,context:e.context}),k=await $m({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 Hm({resourceAs:{tokenUrl:h.resourceAs.tokenUrl},assertion:k.assertion,resource:f,scope:w,clientAuth:h.resourceAs.clientAuth,context:e.context});if(QR(I),t!==void 0){let O=(I.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],L=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 Xe(I.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:O,expiresAt:L,metadata:S.connection.metadata});s?.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:L},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:I.accessToken}}}n(Fm,"authorizeUpstreamIdJagRequest");var wi=new Map;function tb(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(tb,"normalizeRefreshFlightScope");function rb(e){return Si(new URL(e.callbackPath,Y(e.requestUrl,e.requestHeaders))).toString()}n(rb,"buildGatewayOAuthRedirectUri");async function ra(e){let t=yt(e.upstreamServerId),r=Tr(e.upstreamServerId,e.authProfileId),o=rb({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await N().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,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(ra,"prepareUpstreamOAuthRequest");async function Gm(e){let t=await ra(e),r=new wt({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Um(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Gm,"startUpstreamConnect");async function Jm(e){let t=await ra(e),r=new wt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>Om({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 i=Rl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),s=JSON.stringify([i,tb(r.configuredAuthorizationScope??e.requestedScope)]),c=wi.get(s);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 ra(f),r=new wt({...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(()=>{wi.get(s)===u&&wi.delete(s)}),wi.set(s,u),a}n(Jm,"authorizeUpstreamRequest");async function xr(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Jm({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 Fm({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(xr,"resolveUpstreamCredentialForRoute");async function Vm(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 Gm({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(Vm,"startUpstreamConnectForRequest");async function Km(e){let r=(await gi(e.callbackRequest.state)).authProfileId;if(mi({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 Mm({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:yt(e.callbackRequest.upstreamServerId)})}n(Km,"finishUpstreamCallbackForRequest");function nb(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(nb,"buildRouteAuthBaseFromConnection");function Wm(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Yu(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Wm,"buildRouteAuthBaseFromPolicyOptions");function Ri(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 nb({connection:o.connection,operationId:t})}n(Ri,"resolveRouteAuthBase");function na(e,t){switch(e){case"user":return vr(t);case"shared":return Wu()}}n(na,"buildOwnerForSubject");function Ur(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:na("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:na("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:na("user",t),initiatedBySubjectId:t}}}n(Ur,"resolveRouteAuthForSubject");var ob=P.InvalidRequest;function ib(e,t){return{credentialType:e.type,forceRefresh:t}}n(ib,"buildCredentialResolvedAttributes");function sb(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(sb,"connectRequiredReasonCode");function Zm(e){J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:ib(e.credential,e.forceRefresh===!0)})}n(Zm,"emitCredentialResolvedAnalyticsEvent");function Ym(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(J(e.context,{eventType:H.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:H.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:sb(e.payload.state),reasonClass:"auth",attributes:t})}n(Ym,"emitCredentialMissingAnalyticsEvents");function ab(e){let t=e.route.raw();return Fo.parse(t?.operationId)}n(ab,"readOperationId");async function cb(e,t,r,o){let i=await xr({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return Ym({context:o,payload:i.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:i.payload};let s=i.credential;if(Zm({context:o,credential:s,routeBinding:t}),s.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${s.token}`]]};let c=await s.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(cb,"buildCredentialHeaders");var db=new Set(["authorization","cookie","cookie2"]);function ub(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(ub,"readJsonRequestMethod");function lb(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(lb,"isJsonResponse");function oa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(oa,"isRecord");function pb(e){return Array.isArray(e)&&e.length>0}n(pb,"hasIconList");function mb(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=pi(Gu(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(mb,"readFallbackServerIcons");function hb(e){if(!oa(e.body))return e.body;let t=e.body.result;if(!oa(t))return e.body;let r=t.serverInfo;return!oa(r)||pb(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(hb,"addMissingServerIcons");function fb(e,t){let r=Xm(e);for(let o of db)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Fa(e,{headers:r})}n(fb,"applyUpstreamHeaders");function Xm(e){let t=new Headers(e.headers);return Ja(t),t}n(Xm,"buildProxyHeaders");async function gb(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(gb,"readRetryBody");function Qm(e,t){let r=t.authUrl===void 0?void 0:Up({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(ci({id:xp(e),error:{code:r?.code??ob,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Qm,"connectRequiredJsonRpcResponse");async function yb(e){let{scope:t}=Tp(e.upstreamResponse),r=await xr({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return Ym({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),i=r.credential;if(Zm({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0}),i.type==="bearer_token")return o.set("authorization",`Bearer ${i.token}`),{kind:"headers",headers:o};let s=await i.provider.tokens();return s?(o.set("authorization",`${s.token_type??"Bearer"} ${s.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(yb,"applyRefreshedCredentialHeaders");function Sb(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await yb({request:e.request,context:e.context,headers:Xm(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Qm(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=Ju({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return xo.fetch(i.url,i.init)})}n(Sb,"installUpstreamAuthRetryHook");function _b(e){if(ub(e.requestBody)!=="initialize")return;let t=mb({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!lb(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=hb({body:o,icons:t});if(i===o)return r;let s=new Headers(r.headers);return s.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:s})})}n(_b,"installInitializeIconHook");async function ia(e,t,r){let o=ab(t),i=await gb(e),s=Wm({connection:r,operationId:o}),c=$t(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),nl(t,c);let a=Ur(s,c.subjectId),u=await cb(e,a,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Qm(i,u.payload);if(u instanceof Response)return u;let p=fb(e,u.headers);return Sb({request:p,context:t,requestBody:i,routeAuth:a}),_b({context:t,requestBody:i,connection:r}),p}n(ia,"mcpTokenExchangePolicy");var sa=class extends Mo{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=Xu(t,r);super(o,r),this.#e=o}async handler(t,r){return ia(t,r,this.#e)}};var eh=Symbol("Html");function wb(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(wb,"escapeHtml");function Rb(e){return e===null||typeof e!="object"?!1:e[eh]===!0}n(Rb,"isHtml");function th(e){return e==null||e===!1?"":Array.isArray(e)?e.map(th).join(""):Rb(e)?e.value:wb(String(e))}n(th,"renderValue");function tt(e){return{[eh]:!0,value:e}}n(tt,"trustedHtml");var Pe=tt("");function B(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=th(t[o]),r+=e[o+1]??"";return tt(r)}n(B,"html");function Or(e){return e.value}n(Or,"renderHtml");function rh(e){return B`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(rh,"renderBrowserErrorPage");var Mr=tt('*,: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}@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}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function qr(e){return B`<!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
27
  ${e.styles}
28
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(qr,"renderShell");var bb="text/html; charset=utf-8";function zr(e){try{return new URL(e).host}catch{return""}}n(zr,"safeHostFromUrl");function He(e){let t=Ib(e.kind??"authorization_failed"),r=vb(e);return new Response(Or(qr({title:e.title??t.title,iconHref:"",styles:Mr,headerIcon:Pe,heading:e.title??t.title,subhead:"",body:rh({detail:e.detail,guidance:B`<p class="card__description">${t.guidance}</p>`,technicalDetails:Pb({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:kb(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":bb,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(He,"browserErrorPageResponse");function vb(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Cb(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??Tb(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(vb,"buildBrowserErrorDiagnostic");function Ib(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"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",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(Ib,"readBrowserErrorPagePresentation");function Cb(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(Cb,"readBrowserErrorStage");function Tb(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(Tb,"readBrowserErrorSuggestedFix");function kb(e){return e===void 0?Pe:B`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(kb,"renderAction");function Eb(e){let t=[["Error code",e.code],["Stage",e.stage],["Request ID",e.requestId],["Time",e.timestamp],["Gateway route",e.routePath],["Operation ID",e.operationId],["Upstream",e.upstreamServerId],["Auth profile",e.authProfileId],["Upstream URL",e.upstreamUrl],["Metadata URL",e.metadataUrl],["HTTP status",e.httpStatus],["Content type",e.contentType],["Provider error",e.providerError],["Provider error description",e.providerErrorDescription],["Suggested fix",e.suggestedFix],["Underlying error",e.underlyingError]].filter(r=>r[1]!==void 0).map(([r,o])=>`${r}: ${o}`).join(`