@zuplo/cli 7.2.0 → 7.2.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.
- package/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.js +3 -1
- package/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs +3 -1
- package/node_modules/@posthog/core/dist/utils/index.d.ts +0 -1
- package/node_modules/@posthog/core/dist/utils/index.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/utils/index.js +0 -14
- package/node_modules/@posthog/core/dist/utils/index.mjs +1 -2
- package/node_modules/@posthog/core/package.json +1 -1
- package/node_modules/@posthog/core/src/error-tracking/coercers/object-coercer.ts +5 -1
- package/node_modules/@posthog/core/src/error-tracking/error-properties-builder.coerce.spec.ts +36 -0
- package/node_modules/@posthog/core/src/utils/index.ts +0 -4
- package/node_modules/@zuplo/core/customer.cli.minified.js +143 -143
- package/node_modules/@zuplo/core/index.minified.js +144 -144
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-TPXAFGLU.js +409 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-FP5XLKCX.js.map → chunk-TPXAFGLU.js.map} +1 -1
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +54 -59
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/package.json +6 -6
- package/node_modules/@zuplo/runtime/out/esm/chunk-FP5XLKCX.js +0 -409
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-FP5XLKCX.js.LEGAL.txt → chunk-TPXAFGLU.js.LEGAL.txt} +0 -0
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$ as Ea,$a as Cc,$b as vd,$c as pu,$e as hr,$f as ji,A as Ro,Aa as Xa,Ab as Yc,Ac as $d,Af as ku,Ag as jo,Ba as Qa,Bb as Xc,Bc as Dd,Bf as Uo,Bg as Nn,Ca as ec,Cb as Qc,Cc as Ld,Cf as qn,Cg as Wu,Da as tc,Db as ed,Dc as Hd,Df as Au,Dg as Zu,Ea as rc,Eb as td,Ec as Bd,Ef as yr,Eg as Yu,Fa as nc,Fb as rd,Fc as Fd,Ff as Pu,Fg as Xu,Ga as oc,Gb as nd,Gc as Jd,Gf as Mi,Gg as Qu,Ha as ic,Hb as od,Hc as Gd,Hf as Eu,Hg as el,Ia as Ti,Ib as id,Ic as Vd,If as zn,Ig as tl,Ja as sc,Jb as sd,Jc as Kd,Jf as Oo,Jg as rl,Ka as ac,Kb as ad,Kc as Wd,Kf as xu,Kg as No,La as cc,Lb as cd,Lc as Zd,Lf as Uu,Lg as nl,Ma as dc,Mb as dd,Mc as Yd,Mf as Ou,Mg as ol,Na as uc,Nb as ud,Nc as Xd,Nf as qu,Ng as j,Oa as lc,Ob as ld,Oc as Qd,Of as Ae,Og as G,Pa as pc,Pb as pd,Pc as eu,Pf as de,Pg as me,Q as Co,Qa as mc,Qb as md,Qc as tu,Qf as zu,Qg as Ke,R as bi,Ra as hc,Rb as ki,Rc as ru,Rf as Mu,Rg as Y,S as sr,Sa as fc,Sb as hd,Sc as nu,Sf as $,Sg as $o,T as En,Ta as gc,Tb as fd,Tc as ou,Te as Su,Tf as Ge,Tg as Qf,U as ar,Ua as yc,Ub as gd,Uc as iu,Ue as Re,Uf as Sr,Ug as eg,V as cr,Va as Sc,Vb as yd,Vc as su,Ve as _u,Vf as pe,W as xn,Wa as _c,Wb as Sd,Wc as au,We as wu,Wf as ee,X as dr,Xa as wc,Xb as _d,Xc as cu,Xe as re,Xf as ju,Y as ka,Ya as Rc,Yb as wd,Yc as du,Ye as Ru,Yf as W,Z as Aa,Za as bc,Zb as Rd,Zc as uu,Ze as mr,Zf as Nu,_ as Pa,_a as vc,_b as bd,_c as lu,_e as bu,_f as ut,aa as xa,ab as Ic,ac as Cd,ad as ur,af as I,ag as qo,ba as Ua,bb as Tc,bc as Id,bd as lr,bf as fr,bg as Ni,ca as Oa,cb as kc,cc as Td,cd as mu,cf as gr,cg as zo,da as qa,db as Ac,dc as kd,dd as pr,df as at,dg as Mn,ea as za,eb as Pc,ec as Ad,ed as st,ef as ct,eg as _r,fa as Ma,fb as Ec,fc as Pd,fd as zi,ff as Eo,fg as $u,ga as ja,gb as xc,gc as Ai,gd as Po,gf as vu,gg as Ve,ha as Na,hb as Uc,hc as Io,hd as hu,hf as Oe,hg as $i,ia as $a,ib as Oc,ic as To,id as On,if as Cu,ig as Di,ja as Da,jb as qc,jc as Pi,jd as jt,jf as Je,jg as Du,k as Fe,ka as La,kb as zc,kc as Ei,kd as fu,kf as x,kg as Mo,la as Ha,lb as Mc,lc as xi,ld as gu,lf as xo,lg as Li,ma as Mt,mb as jc,mc as Ed,mf as le,mg as Hi,na as vi,nb as Nc,nc as Ui,nf as dt,ng as Lu,oa as Ci,ob as $c,oc as Oi,of as Bf,og as ne,pa as Un,pb as Dc,pc as xd,pf as Ff,pg as Hu,qa as Ii,qb as Lc,qc as Ud,qf as Jf,qg as Bu,r as zt,ra as Ba,rb as Hc,rc as qi,rd as yu,rf as Gf,rg as Bi,s as Ra,sa as Fa,sb as Bc,sc as ko,sf as Vf,sg as Fu,ta as Ja,tb as Fc,tc as Ao,tf as Kf,tg as Ju,ua as Ga,ub as Jc,uc as Od,uf as Wf,ug as Fi,va as Va,vb as Gc,vc as qd,vf as Zf,vg as Gu,wa as Ka,wb as Vc,wc as zd,wf as Yf,wg as Nt,xa as Wa,xb as Kc,xc as Md,xf as Xf,xg as Vu,y as va,ya as Za,yb as Wc,yc as jd,yf as Iu,yg as jn,za as Ya,zb as Zc,zc as Nd,zf as Tu,zg as Ku}from"../chunk-FP5XLKCX.js";import"../chunk-B3D32RUX.js";import{a as H}from"../chunk-4VE55TG3.js";import{a as il}from"../chunk-6SNZ4DOC.js";import{a as ba}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as f,B as z,C as Ri,D as vo,G as l,h as _i,i as An,j as Ca,k as d,l as Ia,m as Ta,n as b,o as E,p as bo,r as q,s as _,t as m,u as M,v as A,w as wi,x as Pn,y as T,z as N}from"../chunk-4CDML74A.js";import"../chunk-UKQQD2JN.js";import{W as ke,X as v,Y as K,Z as wa,_ as wo}from"../chunk-4POCC75H.js";import{a as n}from"../chunk-TYV53J3B.js";var tg=Object.create,Do=Object.defineProperty,rg=Object.getOwnPropertyDescriptor,ng=Object.getOwnPropertyNames,og=Object.getPrototypeOf,ig=Object.prototype.hasOwnProperty,sl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),al=n((e,t)=>{let r={};for(var o in e)Do(r,o,{get:e[o],enumerable:!0});return t&&Do(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),sg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=ng(t),s=0,a=i.length,c;s<a;s++)c=i[s],!ig.call(e,c)&&c!==r&&Do(e,c,{get:(u=>t[u]).bind(null,c),enumerable:!(o=rg(t,c))||o.enumerable});return e},"__copyProps"),cl=n((e,t,r)=>(r=e!=null?tg(og(e)):{},sg(t||!e||!e.__esModule?Do(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var ag=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function dl(e){return typeof e=="string"&&ag.has(e.replace(/#$/,""))}n(dl,"declares2019Dialect");var Zi=Symbol.for("mcp.sdk.errorBrands");function $t(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,Zi,{value:r,enumerable:!1,configurable:!0})}n($t,"stampErrorBrands");function be(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Zi)){let r=t[Zi];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(be,"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})({}),pt=class _l extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return be(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 be(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",$t(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 _l(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})({}),te=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",$t(this,new.target)}},_g=class extends te{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 wl(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(wl,"resourceUrlFromServerUrl");function Rl({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(Rl,"checkResourceAllowed");var wg="2026-07-28";function bl(e){return e>=wg}n(bl,"isModernProtocolVersion");function vl(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(vl,"appendTextFallbackForNonObject");var Cl=["task","inputRequests","requestState"];function Rg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Cl.some(t=>t in e)?e:{...e,content:[]}}n(Rg,"normalizeContentlessToolResult");function bg(){let e=Ri(()=>A([d(),b(),E(),bo(),T(d(),e),_(e)])),t=T(d(),e),r=A([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),a=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),c=m({_meta:a.optional()}),u=c.extend({task:i.optional()}),p=m({method:d(),params:c.loose().optional()}),h=m({_meta:a.optional()}),g=m({method:d(),params:h.loose().optional()}),S=M({_meta:a.optional()}),y=A([d(),b().int()]),k=S.strict(),w=h.extend({requestId:y.optional(),reason:d().optional()}),C=g.extend({method:f("notifications/cancelled"),params:w}),U=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:N(["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()}),Q=Pn(m({applyDefaults:E().optional()}),t),J=vo(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,Pn(m({form:Q.optional(),url:t.optional()}),t.optional())),V=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),Le=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),oe=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:V.optional(),extensions:T(d(),t).optional()}),ze=c.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),D=p.extend({method:f("initialize"),params:ze}),Ee=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:Le.optional(),extensions:T(d(),t).optional()}),qr=S.extend({protocolVersion:d(),capabilities:Ee,serverInfo:F,instructions:d().optional()}),Bt=g.extend({method:f("notifications/initialized"),params:h.optional()}),et=p.extend({method:f("ping"),params:c.optional()}),bt=m({progress:b(),total:z(b()),message:z(d())}),Me=m({...h.shape,...bt.shape,progressToken:r}),tt=g.extend({method:f("notifications/progress"),params:Me}),Ft=c.extend({cursor:o.optional()}),He=p.extend({params:Ft.optional()}),Be=S.extend({nextCursor:o.optional()}),Jt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),Gt=Jt.extend({text:d()}),vt=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vt=Jt.extend({blob:vt}),je=N(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:An.datetime({offset:!0}).optional()}),Ct=m({...L.shape,...O.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:xe.optional(),_meta:z(M({}))}),zr=m({...L.shape,...O.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:xe.optional(),_meta:z(M({}))}),Mr=He.extend({method:f("resources/list")}),jr=Be.extend({resources:_(Ct)}),rt=He.extend({method:f("resources/templates/list")}),Kt=Be.extend({resourceTemplates:_(zr)}),It=c.extend({uri:d()}),Nr=It,$r=p.extend({method:f("resources/read"),params:Nr}),Dr=S.extend({contents:_(A([Gt,Vt]))}),Lr=g.extend({method:f("notifications/resources/list_changed"),params:h.optional()}),Hr=It,Br=p.extend({method:f("resources/subscribe"),params:Hr}),Fr=It,Jr=p.extend({method:f("resources/unsubscribe"),params:Fr}),Gr=h.extend({uri:d()}),Vr=g.extend({method:f("notifications/resources/updated"),params:Gr}),Kr=m({name:d(),description:z(d()),required:z(E())}),Wr=m({...L.shape,...O.shape,description:z(d()),arguments:z(_(Kr)),_meta:z(M({}))}),Zr=He.extend({method:f("prompts/list")}),Yr=Be.extend({prompts:_(Wr)}),Xr=c.extend({name:d(),arguments:T(d(),d()).optional()}),Qr=p.extend({method:f("prompts/get"),params:Xr}),Tt=m({type:f("text"),text:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),kt=m({type:f("image"),data:vt,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),At=m({type:f("audio"),data:vt,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),en=m({type:f("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),nt=m({type:f("resource"),resource:A([Gt,Vt]),annotations:xe.optional(),_meta:T(d(),q()).optional()}),tn=Ct.extend({type:f("resource_link")}),Te=A([Tt,kt,At,tn,nt]),Wt=m({role:je,content:Te}),Zt=S.extend({description:d().optional(),messages:_(Wt)}),Pt=g.extend({method:f("notifications/prompts/list_changed"),params:h.optional()}),rn=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yt=m({taskSupport:N(["required","optional","forbidden"]).optional()}),Et=m({...L.shape,...O.shape,description:d().optional(),inputSchema:m({type:f("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()),outputSchema:m({type:f("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()).optional(),annotations:rn.optional(),execution:Yt.optional(),_meta:T(d(),q()).optional()}),Xt=He.extend({method:f("tools/list")}),Qt=Be.extend({tools:_(Et)}),er=S.extend({content:_(Te),structuredContent:T(d(),q()).optional(),isError:E().optional()}),ae=u.extend({name:d(),arguments:T(d(),q()).optional()}),nn=p.extend({method:f("tools/call"),params:ae}),ro=g.extend({method:f("notifications/tools/list_changed"),params:h.optional()}),tr=N(["debug","info","notice","warning","error","critical","alert","emergency"]),on=c.extend({level:tr}),sn=p.extend({method:f("logging/setLevel"),params:on}),an=h.extend({level:tr,logger:d().optional(),data:q()}),cn=g.extend({method:f("notifications/message"),params:an}),dn=m({name:d().optional()}),un=m({hints:_(dn).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),ln=m({mode:N(["auto","required","none"]).optional()}),no=m({type:f("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(Te),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),pn=wi("type",[Tt,kt,At]),ot=wi("type",[Tt,kt,At,en,no]),mn=m({role:je,content:A([ot,_(ot)]),_meta:T(d(),q()).optional()}),hn=u.extend({messages:_(mn),modelPreferences:un.optional(),systemPrompt:d().optional(),includeContext:N(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Et).optional(),toolChoice:ln.optional()}),fn=p.extend({method:f("sampling/createMessage"),params:hn}),gn=S.extend({model:d(),stopReason:z(N(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:pn}),yn=S.extend({model:d(),stopReason:z(N(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:A([ot,_(ot)])}),Sn=m({type:f("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),_n=m({type:f("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:N(["email","uri","date","date-time"]).optional(),default:d().optional()}),wn=m({type:N(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Rn=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),bn=m({type:f("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),vn=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Cn=A([Rn,bn]),xt=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:f("string"),enum:_(d())}),default:_(d()).optional()}),Ut=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),oo=A([xt,Ut]),io=A([vn,Cn,oo]),_e=A([io,Sn,_n,wn]),we=u.extend({mode:f("form").optional(),message:d(),requestedSchema:m({type:f("object"),properties:T(d(),_e),required:_(d()).optional()}).catchall(q())}),In=u.extend({mode:f("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=A([we,In]),so=p.extend({method:f("elicitation/create"),params:Ue}),ao=h.extend({elicitationId:d()}),co=g.extend({method:f("notifications/elicitation/complete"),params:ao}),uo=S.extend({action:N(["accept","decline","cancel"]),content:vo(ce=>ce===null?void 0:ce,T(d(),A([d(),b(),E(),_(d())])).optional())}),lo=m({type:f("ref/resource"),uri:d()}),po=m({type:f("ref/prompt"),name:d()}),mo=c.extend({ref:A([po,lo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),Tn=p.extend({method:f("completion/complete"),params:mo}),ho=S.extend({completion:M({values:_(d()).max(100),total:z(b().int()),hasMore:z(E())})}),fo=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),rr=p.extend({method:f("roots/list"),params:c.optional()}),kn=S.extend({roots:_(fo)}),go=g.extend({method:f("notifications/roots/list_changed"),params:h.optional()}),yo=M({ttl:b().optional(),pollInterval:b().optional()}),So=N(["working","input_required","completed","failed","cancelled"]),it=m({taskId:d(),status:So,ttl:A([b(),bo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:z(b()),statusMessage:z(d())}),fe=S.extend({task:it}),_o=h.merge(it),Ot=g.extend({method:f("notifications/tasks/status"),params:_o}),nr=p.extend({method:f("tasks/get"),params:c.extend({taskId:d()})}),or=S.merge(it),ir=p.extend({method:f("tasks/result"),params:c.extend({taskId:d()})}),Si=S.loose(),ge=He.extend({method:f("tasks/list")}),Z=Be.extend({tasks:_(it)}),qt=p.extend({method:f("tasks/cancel"),params:c.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:u,RequestSchema:p,NotificationsParamsSchema:h,NotificationSchema:g,ResultSchema:S,RequestIdSchema:y,EmptyResultSchema:k,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:C,IconSchema:U,IconsSchema:O,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Le,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:ze,InitializeRequestSchema:D,ServerCapabilitiesSchema:Ee,InitializeResultSchema:qr,InitializedNotificationSchema:Bt,PingRequestSchema:et,ProgressSchema:bt,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:tt,PaginatedRequestParamsSchema:Ft,PaginatedRequestSchema:He,PaginatedResultSchema:Be,ResourceContentsSchema:Jt,TextResourceContentsSchema:Gt,BlobResourceContentsSchema:Vt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:Ct,ResourceTemplateSchema:zr,ListResourcesRequestSchema:Mr,ListResourcesResultSchema:jr,ListResourceTemplatesRequestSchema:rt,ListResourceTemplatesResultSchema:Kt,ResourceRequestParamsSchema:It,ReadResourceRequestParamsSchema:Nr,ReadResourceRequestSchema:$r,ReadResourceResultSchema:Dr,ResourceListChangedNotificationSchema:Lr,SubscribeRequestParamsSchema:Hr,SubscribeRequestSchema:Br,UnsubscribeRequestParamsSchema:Fr,UnsubscribeRequestSchema:Jr,ResourceUpdatedNotificationParamsSchema:Gr,ResourceUpdatedNotificationSchema:Vr,PromptArgumentSchema:Kr,PromptSchema:Wr,ListPromptsRequestSchema:Zr,ListPromptsResultSchema:Yr,GetPromptRequestParamsSchema:Xr,GetPromptRequestSchema:Qr,TextContentSchema:Tt,ImageContentSchema:kt,AudioContentSchema:At,ToolUseContentSchema:en,EmbeddedResourceSchema:nt,ResourceLinkSchema:tn,ContentBlockSchema:Te,PromptMessageSchema:Wt,GetPromptResultSchema:Zt,PromptListChangedNotificationSchema:Pt,ToolAnnotationsSchema:rn,ToolExecutionSchema:Yt,ToolSchema:Et,ListToolsRequestSchema:Xt,ListToolsResultSchema:Qt,CallToolResultSchema:er,CallToolRequestParamsSchema:ae,CallToolRequestSchema:nn,ToolListChangedNotificationSchema:ro,LoggingLevelSchema:tr,SetLevelRequestParamsSchema:on,SetLevelRequestSchema:sn,LoggingMessageNotificationParamsSchema:an,LoggingMessageNotificationSchema:cn,ModelHintSchema:dn,ModelPreferencesSchema:un,ToolChoiceSchema:ln,ToolResultContentSchema:no,SamplingContentSchema:pn,SamplingMessageContentBlockSchema:ot,SamplingMessageSchema:mn,CreateMessageRequestParamsSchema:hn,CreateMessageRequestSchema:fn,CreateMessageResultSchema:gn,CreateMessageResultWithToolsSchema:yn,BooleanSchemaSchema:Sn,StringSchemaSchema:_n,NumberSchemaSchema:wn,UntitledSingleSelectEnumSchemaSchema:Rn,TitledSingleSelectEnumSchemaSchema:bn,LegacyTitledEnumSchemaSchema:vn,SingleSelectEnumSchemaSchema:Cn,UntitledMultiSelectEnumSchemaSchema:xt,TitledMultiSelectEnumSchemaSchema:Ut,MultiSelectEnumSchemaSchema:oo,EnumSchemaSchema:io,PrimitiveSchemaDefinitionSchema:_e,ElicitRequestFormParamsSchema:we,ElicitRequestURLParamsSchema:In,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:so,ElicitationCompleteNotificationParamsSchema:ao,ElicitationCompleteNotificationSchema:co,ElicitResultSchema:uo,ResourceTemplateReferenceSchema:lo,PromptReferenceSchema:po,CompleteRequestParamsSchema:mo,CompleteRequestSchema:Tn,CompleteResultSchema:ho,RootSchema:fo,ListRootsRequestSchema:rr,ListRootsResultSchema:kn,RootsListChangedNotificationSchema:go,TaskCreationParamsSchema:yo,TaskStatusSchema:So,TaskSchema:it,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:_o,TaskStatusNotificationSchema:Ot,GetTaskRequestSchema:nr,GetTaskResultSchema:or,GetTaskPayloadRequestSchema:ir,GetTaskPayloadResultSchema:Si,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:qt,CancelTaskResultSchema:S.merge(it),ClientRequestSchema:A([et,D,Tn,sn,Qr,Zr,Mr,rt,$r,Br,Jr,nn,Xt,nr,ir,ge,qt]),ClientNotificationSchema:A([C,tt,Bt,go,Ot]),ClientResultSchema:A([k,gn,yn,uo,kn,or,Z,fe]),ServerRequestSchema:A([et,fn,so,rr,nr,ir,ge,qt]),ServerNotificationSchema:A([C,tt,cn,Vr,Lr,ro,Pt,Ot,co]),ServerResultSchema:A([k,qr,ho,Zt,Yr,jr,Kt,Dr,er,Qt,or,Z,fe]),CallToolResultWireSchema:q().superRefine((ce,Hf)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let _a of Cl)if(_a in ce){Hf.addIssue({code:"custom",message:`content is required when the body carries '${_a}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Rg).pipe(er)}}n(bg,"build$1");var vg;function rs(){return vg??=bg()}n(rs,"buildSchemas2025");function Il(e){return e.type!=="object"}n(Il,"isNonObjectJsonSchemaRoot");var Cg=new Set(["const","enum","default","examples"]),Ig=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ul(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(ul,"establishesNewBase");function Tg(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ul(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=dl(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&&ul(i.$id))return i;let a={},c=!1;for(let[u,p]of Object.entries(i))s?a[u]=o(p,!1):(u==="$ref"||u==="$dynamicRef")&&typeof p=="string"?a[u]=p==="#"?"#/properties/result":p.startsWith("#/")?`#/properties/result${p.slice(1)}`:p:u==="$recursiveRef"&&p==="#"&&r?c=!0:Cg.has(u)?a[u]=p:Ig.has(u)?a[u]=o(p,!0):a[u]=o(p,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(Tg,"wrapOutputSchemaForLegacy");var Tl={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},kl={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},kg={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},Lo;function Jo(){if(Lo)return Lo;let e=rs();return Lo={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}},Lo}n(Jo,"registryMaps");function Ag(){Jo()}n(Ag,"warmRegistryMaps2025");function Al(e){return Object.prototype.hasOwnProperty.call(Tl,e)}n(Al,"hasRequestMethod2025");function Pl(e){return Object.prototype.hasOwnProperty.call(kl,e)}n(Pl,"hasNotificationMethod2025");function Pg(e){return Object.prototype.hasOwnProperty.call(kg,e)}n(Pg,"hasResultMethod");function Eg(e){return Pg(e)?Jo().resultSchemas[e]:void 0}n(Eg,"getResultSchema");function xg(e){return Al(e)?Jo().requestSchemas[e]:void 0}n(xg,"getRequestSchema");function Ug(e){return Pl(e)?Jo().notificationSchemas[e]:void 0}n(Ug,"getNotificationSchema");var II=Object.keys(Tl),TI=Object.keys(kl);function Yi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Yi,"isPlainObject$4");function Ho(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(Ho,"triState$1");var ll={ok:!1,reason:"not-in-era"};function pl(e){return Yi(e)&&Yi(e.outputSchema)&&Il(e.outputSchema)}n(pl,"toolNeedsLegacyWrap");var ns={era:"2025-11-25",hasRequestMethod:Al,hasNotificationMethod:Pl,validateRequest:n((e,t)=>Ho(xg(e),t),"validateRequest"),validateResult:n((e,t)=>Ho(Eg(e),t),"validateResult"),validateNotification:n((e,t)=>Ho(Ug(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>ll,"validateInputRequest"),validateInputResponse:n(()=>ll,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=rs();return Ho(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=vl(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Il(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(Yi(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=>pl(o))?t:{...t,tools:r.map(o=>pl(o)?{...o,outputSchema:Tg(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function Og(){let e=Ri(()=>A([d(),b(),E(),bo(),T(d(),e),_(e)])),t=T(d(),e),r=A([d(),b().int()]),o=d(),i=A([d(),b().int()]),s=N(["user","assistant"]),a=N(["debug","info","notice","warning","error","critical","alert","emergency"]),c=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=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":p.optional()}),g=m({_meta:h.optional()}),S=g.extend({task:u.optional()}),y=m({_meta:h.optional()}),k=m({method:d(),params:y.loose().optional()}),w=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:N(["light","dark"]).optional()}),C=m({icons:_(w).optional()}),U=m({name:d(),title:d().optional()}),O=U.extend({...U.shape,...C.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),L=Pn(m({applyDefaults:E().optional()}),t),F=vo(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,Pn(m({form:L.optional(),url:t.optional()}),t.optional())),Q=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),J=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({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:E().optional()}).optional(),tasks:Q.optional(),extensions:T(d(),t).optional()}),Le=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:J.optional(),extensions:T(d(),t).optional()}),oe=m({progress:b(),total:z(b()),message:z(d())}),ze=m({...y.shape,...oe.shape,progressToken:r}),D=k.extend({method:f("notifications/progress"),params:ze}),Ee=y.extend({level:a,logger:d().optional(),data:q()}),qr=k.extend({method:f("notifications/message"),params:Ee}),Bt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),et=Bt.extend({text:d()}),bt=Bt.extend({blob:c}),Me=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:An.datetime({offset:!0}).optional()}),tt=m({...U.shape,...C.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:Me.optional(),_meta:z(M({}))}),Ft=m({...U.shape,...C.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:Me.optional(),_meta:z(M({}))}),He=k.extend({method:f("notifications/resources/list_changed"),params:y.optional()}),Be=y.extend({uri:d()}),Jt=k.extend({method:f("notifications/resources/updated"),params:Be}),Gt=m({name:d(),description:z(d()),required:z(E())}),vt=m({...U.shape,...C.shape,description:z(d()),arguments:z(_(Gt)),_meta:z(M({}))}),Vt=k.extend({method:f("notifications/prompts/list_changed"),params:y.optional()}),je=m({type:f("text"),text:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),xe=m({type:f("image"),data:c,mimeType:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),Ct=m({type:f("audio"),data:c,mimeType:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),zr=m({type:f("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),Mr=m({type:f("resource"),resource:A([et,bt]),annotations:Me.optional(),_meta:T(d(),q()).optional()}),jr=tt.extend({type:f("resource_link")}),rt=A([je,xe,Ct,jr,Mr]),Kt=m({role:s,content:rt}),It=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Nr=k.extend({method:f("notifications/tools/list_changed"),params:y.optional()}),$r=m({name:d().optional()}),Dr=m({hints:_($r).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Lr=m({mode:N(["auto","required","none"]).optional()}),Hr=m({type:f("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Br=m({type:f("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:N(["email","uri","date","date-time"]).optional(),default:d().optional()}),Fr=m({type:N(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Jr=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Gr=m({type:f("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),Vr=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Kr=A([Jr,Gr]),Wr=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:f("string"),enum:_(d())}),default:_(d()).optional()}),Zr=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),Yr=A([Wr,Zr]),Xr=A([Vr,Kr,Yr]),Qr=A([Xr,Hr,Br,Fr]),Tt=S.extend({mode:f("form").optional(),message:d(),requestedSchema:m({type:f("object"),properties:T(d(),Qr),required:_(d()).optional()}).catchall(q())}),kt=m({type:f("ref/resource"),uri:d()}),At=m({type:f("ref/prompt"),name:d()}),en=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),nt=V.shape,tn=m({experimental:nt.experimental,sampling:nt.sampling,elicitation:nt.elicitation,roots:nt.roots,extensions:nt.extensions}),Te=Le.shape,Wt=m({experimental:Te.experimental,logging:Te.logging,completions:Te.completions,prompts:Te.prompts,resources:Te.resources,tools:Te.tools,extensions:Te.extensions}),Zt=M({progressToken:r.optional(),[sr]:d(),[En]:O.optional(),[cr]:tn,[xn]:a.optional()}),Pt=m({...U.shape,...C.shape,description:d().optional(),inputSchema:M({$schema:d().optional(),type:f("object")}),outputSchema:M({$schema:d().optional()}).optional(),annotations:It.optional(),_meta:T(d(),q()).optional()}),rn=m({type:f("tool_result"),toolUseId:d(),content:_(rt),structuredContent:q().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),Yt=A([je,xe,Ct,zr,rn]),Et=m({role:s,content:A([Yt,_(Yt)]),_meta:T(d(),q()).optional()}),Xt=d(),Qt=M({[ar]:O.optional().catch(void 0)}),er=Qt.optional();function ae(Z){return M({_meta:er,resultType:Xt.default("complete"),...Z})}n(ae,"wireResult");let nn=ae({}),ro=ae({nextCursor:o.optional()}),tr=ae({content:_(rt),structuredContent:q().optional(),isError:E().optional()}),on=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),tools:_(Pt),nextCursor:o.optional()}),sn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),prompts:_(vt),nextCursor:o.optional()}),an=ae({description:d().optional(),messages:_(Kt)}),cn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resources:_(tt),nextCursor:o.optional()}),dn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resourceTemplates:_(Ft),nextCursor:o.optional()}),un=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),contents:_(A([et,bt]))}),ln=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),no=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"])}),pn=ae({ttlMs:b().int().min(0).catch(0),cacheScope:N(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Wt,instructions:d().optional()}),ot=m({messages:_(Et),modelPreferences:Dr.optional(),systemPrompt:d().optional(),includeContext:N(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Pt).optional(),toolChoice:Lr.optional()}),mn=m({method:f("sampling/createMessage"),params:ot}),hn=m({method:f("roots/list"),params:m({_meta:T(d(),q()).optional()}).optional()}),fn=m({...Et.shape,model:d(),stopReason:d().optional()}),gn=m({roots:_(en)}),yn=m({action:N(["accept","decline","cancel"]),content:T(d(),A([d(),b(),E(),_(d())])).optional()}),Sn=m({mode:f("url"),message:d(),url:d().url()}),_n=A([Tt,Sn]),wn=m({method:f("elicitation/create"),params:_n}),Rn=A([mn,hn,wn]),bn=A([fn,gn,yn]),vn=T(d(),Rn),Cn=T(d(),bn),xt=ae({inputRequests:vn.optional(),requestState:d().optional()}),Ut={inputResponses:Cn.optional(),requestState:d().optional()},oo=m({_meta:Zt,...Ut}),io=M({progressToken:r.optional()});function _e(Z,qt){return m({method:f(Z),params:m({_meta:Zt,...qt})})}n(_e,"wireRequest");function we(Z,qt){return m({method:f(Z),params:m({_meta:io.optional(),...qt}).optional()})}n(we,"dispatchRequest");let In={name:d(),arguments:T(d(),q()).optional(),...Ut},Ue={cursor:o.optional()},so=_e("tools/call",In),ao=_e("tools/list",Ue),co=_e("prompts/list",Ue),uo=_e("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Ut}),lo=_e("resources/list",Ue),po=_e("resources/templates/list",Ue),mo=_e("resources/read",{uri:d(),...Ut}),Tn={ref:A([At,kt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},ho=_e("completion/complete",Tn),fo=_e("server/discover",{}),rr=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:_(d()).optional()}),kn={notifications:rr},go=_e("subscriptions/listen",kn),yo=Qt.extend({"io.modelcontextprotocol/subscriptionId":i}),So=M({_meta:yo,resultType:Xt.default("complete")}),it={"tools/call":we("tools/call",In),"tools/list":we("tools/list",Ue),"prompts/get":we("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":we("prompts/list",Ue),"resources/list":we("resources/list",Ue),"resources/templates/list":we("resources/templates/list",Ue),"resources/read":we("resources/read",{uri:d()}),"completion/complete":we("completion/complete",Tn),"server/discover":we("server/discover",{}),"subscriptions/listen":we("subscriptions/listen",kn)};function fe(Z){return M({_meta:er,...Z})}n(fe,"liftedResult");let _o={"tools/call":fe({content:_(rt),structuredContent:q().optional(),isError:E().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),tools:_(Pt),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Kt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),prompts:_(vt),nextCursor:o.optional()}),"resources/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resources:_(tt),nextCursor:o.optional()}),"resources/templates/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resourceTemplates:_(Ft),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),contents:_(A([et,bt]))}),"completion/complete":fe({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":fe({ttlMs:b().int().min(0).catch(0),cacheScope:N(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Wt,instructions:d().optional()}),"subscriptions/listen":fe({})},Ot=M({"io.modelcontextprotocol/subscriptionId":i.optional()}),nr=m({method:f("notifications/subscriptions/acknowledged"),params:m({_meta:Ot.optional(),notifications:rr})}),or=m({_meta:Ot.optional(),requestId:i,reason:d().optional()}),ir=m({method:f("notifications/cancelled"),params:or}),Si={"notifications/cancelled":ir,"notifications/progress":D,"notifications/message":qr,"notifications/resources/updated":Jt,"notifications/resources/list_changed":He,"notifications/tools/list_changed":Nr,"notifications/prompts/list_changed":Vt,"notifications/subscriptions/acknowledged":nr},ge=n(Z=>m({jsonrpc:f("2.0"),id:A([d(),b().int()]),result:Z}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:i,RoleSchema:s,LoggingLevelSchema:a,TaskMetadataSchema:u,RelatedTaskMetadataSchema:p,RequestMetaSchema:h,BaseRequestParamsSchema:g,TaskAugmentedRequestParamsSchema:S,NotificationsParamsSchema:y,NotificationSchema:k,IconSchema:w,IconsSchema:C,BaseMetadataSchema:U,ImplementationSchema:O,ClientTasksCapabilitySchema:Q,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:V,ServerCapabilitiesSchema:Le,ProgressSchema:oe,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:Ee,LoggingMessageNotificationSchema:qr,ResourceContentsSchema:Bt,TextResourceContentsSchema:et,BlobResourceContentsSchema:bt,AnnotationsSchema:Me,ResourceSchema:tt,ResourceTemplateSchema:Ft,ResourceListChangedNotificationSchema:He,ResourceUpdatedNotificationParamsSchema:Be,ResourceUpdatedNotificationSchema:Jt,PromptArgumentSchema:Gt,PromptSchema:vt,PromptListChangedNotificationSchema:Vt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:Ct,ToolUseContentSchema:zr,EmbeddedResourceSchema:Mr,ResourceLinkSchema:jr,ContentBlockSchema:rt,PromptMessageSchema:Kt,ToolAnnotationsSchema:It,ToolListChangedNotificationSchema:Nr,ModelHintSchema:$r,ModelPreferencesSchema:Dr,ToolChoiceSchema:Lr,BooleanSchemaSchema:Hr,StringSchemaSchema:Br,NumberSchemaSchema:Fr,UntitledSingleSelectEnumSchemaSchema:Jr,TitledSingleSelectEnumSchemaSchema:Gr,LegacyTitledEnumSchemaSchema:Vr,SingleSelectEnumSchemaSchema:Kr,UntitledMultiSelectEnumSchemaSchema:Wr,TitledMultiSelectEnumSchemaSchema:Zr,MultiSelectEnumSchemaSchema:Yr,EnumSchemaSchema:Xr,PrimitiveSchemaDefinitionSchema:Qr,ElicitRequestFormParamsSchema:Tt,ResourceTemplateReferenceSchema:kt,PromptReferenceSchema:At,RootSchema:en,ClientCapabilities2026Schema:tn,ServerCapabilities2026Schema:Wt,RequestMetaEnvelopeSchema:Zt,ToolSchema:Pt,ToolResultContentSchema:rn,SamplingMessageContentBlockSchema:Yt,SamplingMessageSchema:Et,ResultTypeSchema:Xt,ResultMetaSchema:Qt,ResultSchema:nn,PaginatedResultSchema:ro,CallToolResultSchema:tr,ListToolsResultSchema:on,ListPromptsResultSchema:sn,GetPromptResultSchema:an,ListResourcesResultSchema:cn,ListResourceTemplatesResultSchema:dn,ReadResourceResultSchema:un,CompleteResultSchema:ln,CacheableResultSchema:no,DiscoverResultSchema:pn,CreateMessageRequestParamsSchema:ot,CreateMessageRequestSchema:mn,ListRootsRequestSchema:hn,CreateMessageResultSchema:fn,ListRootsResultSchema:gn,ElicitResultSchema:yn,ElicitRequestURLParamsSchema:Sn,ElicitRequestParamsSchema:_n,ElicitRequestSchema:wn,InputRequestSchema:Rn,InputResponseSchema:bn,InputRequestsSchema:vn,InputResponsesSchema:Cn,InputRequiredResultSchema:xt,InputResponseRequestParamsSchema:oo,CallToolRequestSchema:so,ListToolsRequestSchema:ao,ListPromptsRequestSchema:co,GetPromptRequestSchema:uo,ListResourcesRequestSchema:lo,ListResourceTemplatesRequestSchema:po,ReadResourceRequestSchema:mo,CompleteRequestSchema:ho,DiscoverRequestSchema:fo,SubscriptionFilterSchema:rr,SubscriptionsListenRequestSchema:go,SubscriptionsListenResultMetaSchema:yo,SubscriptionsListenResultSchema:So,dispatchRequestSchemas:it,dispatchResultSchemas:_o,NotificationMetaSchema:Ot,SubscriptionsAcknowledgedNotificationSchema:nr,CancelledNotificationParamsSchema:or,CancelledNotificationSchema:ir,notificationSchemas2026:Si,JSONRPCResultResponseSchema:ge(nn),CallToolResultResponseSchema:ge(A([tr,xt])),ListToolsResultResponseSchema:ge(on),ListPromptsResultResponseSchema:ge(sn),GetPromptResultResponseSchema:ge(A([an,xt])),ListResourcesResultResponseSchema:ge(cn),ListResourceTemplatesResultResponseSchema:ge(dn),ReadResourceResultResponseSchema:ge(A([un,xt])),CompleteResultResponseSchema:ge(ln),DiscoverResultResponseSchema:ge(pn)}}n(Og,"build");var qg;function lt(){return qg??=Og()}n(lt,"buildSchemas2026");var zg=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Mg(e){return zg.includes(e)}n(Mg,"isCacheableResultMethod");var os=Symbol("modelcontextprotocol.resultCacheHintFallback");function jg(e){return e[os]}n(jg,"cacheHintFallbackOf");function El(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(El,"isValidCacheTtlMs");function xl(e){return e==="public"||e==="private"}n(xl,"isValidCacheScope");var P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),se=class Ul extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return be(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 be(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",$t(this,new.target)}static fromError(t,r,o){if(t===P.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new Go(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 Ol(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 zl({requiredCapabilities:i.requiredCapabilities},r)}return new Ul(t,r,o)}},Ol=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}},Go=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}},zl=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}},Ng=0,$g="private",Dg=["tools/call","prompts/get","resources/read"];function Lg(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Dg.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(Lg,"stampResultType");function Hg(e,t){let r=jg(t);if(t.resultType!=="complete"||!Mg(e))return r===void 0?t:Vg(t);let o=t,i=El(o.ttlMs)?o.ttlMs:Jg(r),s=xl(o.cacheScope)?o.cacheScope:Gg(r),a={...o,ttlMs:i,cacheScope:s};return delete a[os],a}n(Hg,"fillCacheFields");function Bg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Bg,"isPlainObject$3");function Fg(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ar]:t}}:!Bg(r)||r[ar]!==void 0?e:{...e,_meta:{...r,[ar]:t}}}n(Fg,"stampServerInfoMeta");function Jg(e){return e!==void 0&&El(e.ttlMs)?e.ttlMs:Ng}n(Jg,"resolveTtlMs");function Gg(e){return e!==void 0&&xl(e.cacheScope)?e.cacheScope:$g}n(Gg,"resolveCacheScope");function Vg(e){let t={...e};return delete t[os],t}n(Vg,"stripCacheHintFallback");var Kg=["elicitation/create","sampling/createMessage","roots/list"],Bo;function is(){if(Bo)return Bo;let e=lt();return Bo={request:{"elicitation/create":m({method:f("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:f("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:f("roots/list"),params:M({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Bo}n(is,"inputSchemaMaps");function Wg(){is()}n(Wg,"warmInputSchemaMaps2026");function Ml(e){return Kg.includes(e)}n(Ml,"isInputRequestMethod2026");function Ji(e){return Ml(e)?is().request[e]:void 0}n(Ji,"getInputRequestSchema2026");function Zg(e){return Ml(e)?is().response[e]:void 0}n(Zg,"getInputResponseSchema2026");var ss={"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},jl={"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 Nl(e){return Object.prototype.hasOwnProperty.call(ss,e)}n(Nl,"hasRequestMethod2026");function $l(e){return Object.prototype.hasOwnProperty.call(jl,e)}n($l,"hasNotificationMethod2026");function Yg(e){return Object.prototype.hasOwnProperty.call(ss,e)}n(Yg,"hasResultMethod2026");function Xg(e){return Nl(e)?lt().dispatchRequestSchemas[e]:void 0}n(Xg,"getRequestSchema2026");function Qg(e){return Yg(e)?lt().dispatchResultSchemas[e]:void 0}n(Qg,"getResultSchema2026");function ey(e){return $l(e)?lt().notificationSchemas2026[e]:void 0}n(ey,"getNotificationSchema2026");var kI=Object.keys(ss),AI=Object.keys(jl);function Ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ln,"isPlainObject$2");function $n(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($n,"triState");var ty={ok:!1,reason:"not-in-era"},ry=[sr,cr];function ny(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(c=>Ln(c)&&"execution"in c)&&(i().tools=s.map(c=>{if(!Ln(c)||!("execution"in c))return c;let u={...c};return delete u.execution,u}));let a=t.capabilities;if(Ln(a)&&"tasks"in a){let c={...a};delete c.tasks,i().capabilities=c}return r}n(ny,"enforceDeletedFields");var as={era:"2026-07-28",hasRequestMethod:Nl,hasNotificationMethod:$l,hasInputRequestMethod:n(e=>Ji(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>$n(Xg(e),t),"validateRequest"),validateResult:n((e,t)=>$n(Qg(e),t),"validateResult"),validateNotification:n((e,t)=>$n(ey(e),t),"validateNotification"),validateInputRequest:n((e,t)=>$n(Ji(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>$n(Zg(e),t),"validateInputResponse"),samplingResultVariant:n(()=>ty,"samplingResultVariant"),outboundEnvelope(e){return{[sr]:e.protocolVersion,[En]:e.clientInfo,[cr]:e.clientCapabilities,...e.logLevel!==void 0&&{[xn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of ry)o in e||t.push({key:o,problem:"missing"});let r=lt().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(a=>a.key===s&&a.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>vl(e),"projectCallToolResult"),inputRequestSchema:Ji,decodeResult(e,t){if(!Ln(t))return{kind:"invalid",error:new te(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new te(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 te(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Ln(a)?a:{},u=t.requestState;return Object.keys(c).length===0&&typeof u!="string"?{kind:"invalid",error:new te(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:c,...typeof u=="string"&&{requestState:u}}}if(r!=="complete")return{kind:"invalid",error:new te(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Dl(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let a=i.safeParse(t);if(!a.success)return{kind:"invalid",error:new te(ie.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return Fg(Hg(e,Lg(e,ny(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=lt().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("; ")}`}},Fo;function Dl(){if(Fo)return Fo;let e=lt();return Fo={"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},Fo}n(Dl,"getWireResultSchemas");function oy(){Dl()}n(oy,"warmWireResultSchemas2026");var cs="2026-07-28";function Bn(e){return e!==void 0&&bl(e)?as:ns}n(Bn,"codecForVersion");function ml(e){return e.revision!==void 0?Bn(e.revision).era:e.era==="modern"?as.era:ns.era}n(ml,"classifiedWireEra");function Gi(e){return Ll.some(t=>t.hasRequestMethod(e))}n(Gi,"isSpecRequestMethod");function Vi(e){return Ll.some(t=>t.hasNotificationMethod(e))}n(Vi,"isSpecNotificationMethod");var Ll=[ns,as],iy=al({AnnotationsSchema:n(()=>yc,"AnnotationsSchema"),AudioContentSchema:n(()=>Zc,"AudioContentSchema"),BaseMetadataSchema:n(()=>Wa,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>za,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>fc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Ai,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>ld,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>pd,"CallToolRequestSchema"),CallToolResultSchema:n(()=>dd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>iu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>su,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Ja,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Ga,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Qa,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>cu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>au,"ClientRequestSchema"),ClientResultSchema:n(()=>du,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Ya,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>ud,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Dd,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>Ld,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Hd,"CompleteResultSchema"),ContentBlockSchema:n(()=>ed,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Td,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>kd,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Ad,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>Pd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Zd,"CreateTaskResultSchema"),CursorSchema:n(()=>xa,"CursorSchema"),DiscoverRequestSchema:n(()=>ic,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Ti,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>ko,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Od,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>qd,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Ao,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>jd,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>zd,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>Md,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Xc,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Fa,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Ud,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Gc,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Vc,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>rd,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>tu,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>ru,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Qd,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>eu,"GetTaskResultSchema"),IconSchema:n(()=>Va,"IconSchema"),IconsSchema:n(()=>Ka,"IconsSchema"),ImageContentSchema:n(()=>Wc,"ImageContentSchema"),ImplementationSchema:n(()=>Za,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>ec,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>tc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>nc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>oc,"InitializedNotificationSchema"),JSONArraySchema:n(()=>Pa,"JSONArraySchema"),JSONObjectSchema:n(()=>Aa,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Un,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>Ii,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>vi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Mt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Ba,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Ci,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>ka,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>xi,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>ki,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Fc,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Jc,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>bc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>vc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>wc,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Rc,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Fd,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Jd,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>nu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>ou,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>ad,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>cd,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>hd,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>yd,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>Sd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>_d,"ModelHintSchema"),ModelPreferencesSchema:n(()=>wd,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>xd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>$a,"NotificationSchema"),NotificationsParamsSchema:n(()=>Na,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>To,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>uc,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>lc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>pc,"PaginatedResultSchema"),PingRequestSchema:n(()=>sc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>qi,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>cc,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>dc,"ProgressNotificationSchema"),ProgressSchema:n(()=>ac,"ProgressSchema"),ProgressTokenSchema:n(()=>Ea,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Hc,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>nd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>td,"PromptMessageSchema"),PromptReferenceSchema:n(()=>$d,"PromptReferenceSchema"),PromptSchema:n(()=>Bc,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Ic,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Tc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>kc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Oa,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Ha,"RequestIdSchema"),RequestMetaSchema:n(()=>qa,"RequestMetaSchema"),RequestSchema:n(()=>ja,"RequestSchema"),ResourceContentsSchema:n(()=>mc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Qc,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Ac,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Cc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>Sc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Nd,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>_c,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Dc,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>Lc,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Da,"ResultMetaObjectSchema"),ResultSchema:n(()=>La,"ResultSchema"),RoleSchema:n(()=>gc,"RoleSchema"),RootSchema:n(()=>Bd,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Gd,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>vd,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Cd,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Id,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>rc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>lu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>uu,"ServerRequestSchema"),ServerResultSchema:n(()=>pu,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Xa,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>fd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>gd,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Ed,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Io,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>Pc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Ec,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Oc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>Mc,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>jc,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>qc,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>zc,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Nc,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>$c,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>Ma,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Vd,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>Ua,"TaskMetadataSchema"),TaskSchema:n(()=>Wd,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Yd,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Xd,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>Kd,"TaskStatusSchema"),TextContentSchema:n(()=>Kc,"TextContentSchema"),TextResourceContentsSchema:n(()=>hc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Oi,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Ei,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>od,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Rd,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>id,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>md,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>bd,"ToolResultContentSchema"),ToolSchema:n(()=>sd,"ToolSchema"),ToolUseContentSchema:n(()=>Yc,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>xc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Uc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ui,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Pi,"UntitledSingleSelectEnumSchemaSchema")});var Hl=n(e=>Mt.safeParse(e).success,"isJSONRPCRequest"),Bl=n(e=>vi.safeParse(e).success,"isJSONRPCNotification"),Xi=n(e=>Ci.safeParse(e).success,"isJSONRPCResultResponse"),Fl=n(e=>Un.safeParse(e).success,"isJSONRPCErrorResponse");var Hn=-32020,PI=[{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:[Hn,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:[Hn],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:[Hn],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."}],EI={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Hn]:400};function ds(e,t){return Ca(e,t)}n(ds,"parseSchema");function Dn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Dn,"shapeKeys");function Qi(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(Qi,"isStandardSchema");var hl=!1,es="draft-2020-12";function sy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:es});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().");hl||(hl=!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=_i(e,{target:es,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:Jl(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(sy,"standardSchemaToJsonSchema");function Jl(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"||Jl(o)))}return!1}n(Jl,"isProvablyObjectShapedRoot");function ay(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(ay,"formatIssue");async function Ki(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>ay(o)).join(", ")}:{success:!0,data:r.value}}n(Ki,"validateStandardSchema");function cy(e){let t=_i(e,{target:es,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(cy,"zodEmittedPattern");var dy=/\\\.\\d\{(\d+)\}/;function uy(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=>An.datetime({local:o,offset:i,precision:s}))))}n(uy,"datetimeReferenceSchemas");function ly(e,t){let r;switch(e){case"email":r=[Ia()];break;case"uri":r=[Ta()];break;case"date":r=[An.date()];break;case"date-time":r=uy(t);break}return new Set(r.map(o=>cy(o)).filter(o=>o!==void 0))}n(ly,"referencePatternsForFormat");function py(e,t,r){return r!=="zod"?!0:ly(e,t).has(t)}n(py,"isLibraryFormatPattern");function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Fn,"isJsonObject");function my(e){try{return sy(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(my,"convertStandardElicitationSchema");var hy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function us(e){return hy.has(e)||e.startsWith("x-")}n(us,"isAnnotationOnlyJsonSchemaKeyword");var fy=new Set(["$schema",...Object.keys(ko.shape.requestedSchema.shape)]),fl={string:Dn([Io,Pi,Ei,xi]),number:Dn([To]),integer:Dn([To]),boolean:Dn([Ai]),array:Dn([Ui,Oi])},gy=new Set(Io.shape.format.unwrap().options);function yy(e,t,r,o){if(!Fn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(fl,e.type)?fl[e.type]:void 0;if(i===void 0)return e;let s={};for(let[a,c]of Object.entries(e))i.has(a)||us(a)?s[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?gy.has(e.format)?(typeof c!="string"||!py(e.format,c,r))&&o.push(`${t}.${a}`):s[a]=c:o.push(`${t}.${a}`);return s}n(yy,"walkProperty");function Sy(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Fn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([a,c])=>[a,yy(c,`properties.${a}`,t,o)])):fy.has(i)?r[i]=s:us(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(Sy,"walkRequestedSchema");function _y(e,t){if(!Fn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!ds(qi,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(_y,"describeUnsupportedProperties");function ts(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>ts(o,t[i],`${r}[${i}]`)):!Fn(e)||!Fn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?ts(i,t[o],s):us(o)?[]:[s]})}n(ts,"findDroppedConstraintPaths");function wy(e){if(!Qi(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Sy(my(e.requestedSchema),t),o=ds(ko.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): ${_y(r,o.error.message)}`);let i=ts(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(a=>!Object.prototype.hasOwnProperty.call(o.data.properties,a));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(wy,"normalizeElicitInputParams");function Ry(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(Ry,"buildInputRequired");var xI=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(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 by=["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"],vy={IdJagTokenExchangeResponseSchema:zi,OAuthClientInformationFullSchema:jt,OAuthClientInformationSchema:On,OAuthClientMetadataSchema:hu,OAuthClientRegistrationErrorSchema:fu,OAuthErrorResponseSchema:Po,OAuthMetadataSchema:lr,OAuthProtectedResourceMetadataSchema:ur,OAuthTokenRevocationRequestSchema:gu,OAuthTokensSchema:st,OpenIdProviderDiscoveryMetadataSchema:pr,OpenIdProviderMetadataSchema:mu},Gl={},Vl={};function Kl(e,t){let r=e.slice(0,-6);Gl[r]=t,Vl[r]=o=>t.safeParse(o).success}n(Kl,"register");for(let e of by)Kl(e,iy[e]);for(let[e,t]of Object.entries(vy))Kl(e,t);var Cy=Object.freeze(Gl),Iy=Object.freeze(Vl);function Ty(e){switch(e){case"initialize":case"notifications/initialized":return Bn(void 0);case"server/discover":return Bn(cs);default:return}}n(Ty,"bootstrapOutboundCodec");var Wl=6e4,ky=[sr,En,cr,xn],Ay=["inputResponses","requestState"];function gl(e,t){let r=e.params;if(!Wi(r))return{message:e,lifted:{}};let o=r._meta,i=Wi(o)?ky.filter(u=>u in o):[],s=t==="request"?Ay.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let a={},c={...r};if(i.length>0&&Wi(o)){let u={},p={...o};for(let h of i)u[h]=o[h],delete p[h];a.envelope=u,Object.keys(p).length>0?c._meta=p:delete c._meta}for(let u of s)u==="inputResponses"&&(a.inputResponses=c[u]),u==="requestState"&&(a.requestState=c[u]),delete c[u];return{message:{...e,params:c},lifted:a}}n(gl,"liftWireOnlyMaterial");function yl(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(yl,"codecResultValidator");function Zl(e){return()=>e}n(Zl,"requestStateAccessor");var Py=Zl(void 0),Ey,xy=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{Ey=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??bi,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 te(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 te(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),Xi(i)||Fl(i)?this._onresponse(i):Hl(i)?this._onrequest(i,s):Bl(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 te(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}=gl(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=ml(t.classification);if(a!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${o.era}`));return}}if(Vi(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(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:o}=gl(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,a=n((w,C,U)=>{let O={jsonrpc:"2.0",id:r.id,error:{code:w,message:C,...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=ml(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 C=t.classification.revision??w;a(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${C}`,{supported:this._supportedProtocolVersions,requested:C});return}}if(Gi(r.method)&&!i.hasRequestMethod(r.method)){a(P.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(P.MethodNotFound,"Method not found");return}let u=i.checkInboundEnvelope(o);if(u!==void 0){a(P.InvalidParams,u);return}let p=n((w,C)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...C,relatedRequestId:r.id}),"sendNotification"),h=n((w,C,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,C,{...U,relatedRequestId:r.id}),"sendRequest"),g=new AbortController;this._requestHandlerAbortControllers.set(r.id,g);let S=o.inputResponses===void 0?void 0:Uy(o.inputResponses),y={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...S!==void 0&&{inputResponses:S.accepted},...S!==void 0&&S.droppedKeys.length>0&&{droppedInputResponseKeys:S.droppedKeys},requestState:o.requestState===void 0?Py:Zl(o.requestState),signal:g.signal,send:n(((w,C,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),Qi(C))return h(w,C,U);let L=yl(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,C)}),"send"),notify:p},http:t?.authInfo?{authInfo:t.authInfo}:void 0},k=this.buildContext(y,t);Promise.resolve().then(()=>c(r,k)).then(async w=>{if(g.signal.aborted)return;let C;try{C=i.encodeResult(r.method,w,this._outboundServerInfo())}catch(O){this._onerror(new Error(`Failed to encode result for ${r.method}: ${O}`)),a(P.InternalError,"Internal error");return}let U={result:C,jsonrpc:"2.0",id:r.id};await s?.send(U)},async w=>{if(g.signal.aborted)return;let C=Number.isSafeInteger(w.code)?w.code:P.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:i.encodeErrorCode(C),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)===g&&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),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);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),Xi(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),Qi(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=yl(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 Bn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ty(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Gi(t)&&!e.hasRequestMethod(t))throw new te(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:a,headers:c}=o??{},u=Date.now(),p,h;return new Promise((g,S)=>{let y=n(J=>{S(J)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){y(J);return}if(o?.signal?.aborted){let J=o.signal.reason;throw J instanceof te?J:new te(ie.RequestTimeout,String(J))}let k=e.era===cs&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;h=w;let C={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),C.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let U=this._envelopeOutbound(C),O=!1,L=n(J=>{O||(this._progressHandlers.delete(w),k===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(J)}}),{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),S(J instanceof te?J:new te(ie.RequestTimeout,String(J))))},"cancel");this._responseHandlers.set(w,J=>{if(o?.signal?.aborted)return;if(O=!0,J instanceof Error)return S(J);let V;try{V=e.decodeResult(t.method,J.result)}catch(oe){return S(oe instanceof Error?oe:new Error(String(oe)))}if(V.kind==="invalid")return S(V.error);if(V.kind==="input_required"){if(o?.allowInputRequired===!0)return g(Oy(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((ze,D)=>this._requestWithSchemaViaCodec(e,ze===void 0?{method:t.method}:{method:t.method,params:ze},r,D),"retry")};return g(this._resolveNonCompleteResult(V,oe))}let Le=V.result;Ki(r,Le).then(oe=>{oe.success?g(oe.data):S(new te(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},S)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??Wl,Q=n(()=>L(new te(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,Q,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a,headers:c,requestSignal:k?.signal}).catch(J=>{this._progressHandlers.delete(w),S(J)})}).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 te(ie.NotConnected,"Not connected");if(Vi(t.method)&&!e.hasNotificationMethod(t.method))throw new te(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(!Gi(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,i);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,i)),!c.ok)throw c.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let a=await Ki(t.params,{...i.params});if(!a.success)throw new se(P.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.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(!Vi(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 Ki(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 Wi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Wi,"isPlainObject$1");function Sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Sl,"isPlainObject");function Uy(e){let t={},r=[];if(!Sl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!Sl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(Uy,"partitionInputResponses");function Oy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(Oy,"manualInputRequiredValue");var qy=sl((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(c){if(!c)throw new TypeError("argument string is required");var u=typeof c=="object"?s(c):c;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 g=new a(h.toLowerCase());if(p!==-1){var S,y,k;for(t.lastIndex=p;y=t.exec(u);){if(y.index!==p)throw new TypeError("invalid parameter format");p+=y[0].length,S=y[1].toLowerCase(),k=y[2],k.charCodeAt(0)===34&&(k=k.slice(1,-1),k.indexOf("\\")!==-1&&(k=k.replace(r,"$1"))),g.parameters[S]=k}if(p!==u.length)throw new TypeError("invalid parameter format")}return g}n(i,"parse");function s(c){var u;if(typeof c.getHeader=="function"?u=c.getHeader("content-type"):typeof c.headers=="object"&&(u=c.headers&&c.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}n(s,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}n(a,"ContentType")})),UI=cl(qy(),1);var zy=10*1024*1024;function ls(){rs(),lt(),Ag(),Wg(),oy()}n(ls,"preloadSchemas");var FI=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 My=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ny=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,$y=/^(?=.{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,Dy=/^(?:[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,Ly=/^(?:(?:[^\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,Hy=/^(?:(?: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,By=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Fy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Jy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Gy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Vy=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"),Ky=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Wy=/^((([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,Zy=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 Ne(e){return e.test.bind(e)}n(Ne,"bind");var JI={date:Yl,time:Xl.bind(void 0,!1),"date-time":Qy,duration:Zy,uri:rS,"uri-reference":Ne(Dy),"uri-template":Ne(Ly),url:Ne(Hy),email:Vy,hostname:Ne($y),ipv4:Ne(Ky),ipv6:Ne(Wy),regex:oS,uuid:Ne(By),"json-pointer":Ne(Fy),"json-pointer-uri-fragment":Ne(Jy),"relative-json-pointer":Ne(Gy)};function Yy(e){return e%4===0&&(e%100!==0||e%400===0)}n(Yy,"isLeapYear");function Yl(e){let t=e.match(My);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&Yy(r)?29:jy[o])}n(Yl,"date");function Xl(e,t){let r=t.match(Ny);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||a)}n(Xl,"time");var Xy=/t|\s/i;function Qy(e){let t=e.split(Xy);return t.length==2&&Yl(t[0])&&Xl(!0,t[1])}n(Qy,"date_time");var eS=/\/|:/,tS=/^(?:[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 rS(e){return eS.test(e)&&tS.test(e)}n(rS,"uri");var nS=/[^\\]\\Z/;function oS(e){if(nS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(oS,"regex");ls();var Ql=!1;var ps;ps=globalThis.crypto;async function sS(e){return(await ps).getRandomValues(new Uint8Array(e))}n(sS,"getRandomValues");async function aS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await sS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(aS,"random");async function cS(e){return await aS(e)}n(cS,"generateVerifier");async function dS(e){let t=await(await ps).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 ms(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await cS(e),r=await dS(t);return{code_verifier:t,code_challenge:r}}n(ms,"pkceChallenge");var Jn=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e){super(e),this.name=new.target.name,$t(this,new.target)}},Ss=class extends Jn{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}},uS=class extends Jn{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}},np=class extends Jn{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}},hs=class extends Jn{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}},UT=class extends Jn{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 ep(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):op(e.issuer,t)?e:void 0}n(ep,"discardIfIssuerMismatch");function op(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(op,"issuersMatch");var OT=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",$t(this,new.target)}};function ip(e){return e?.authorization_response_iss_parameter_supported===!0}n(ip,"isIssParameterSupported");function sp({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Ss("authorization_response",t,void 0);return}if(e!==t)throw new Ss("authorization_response",t,e)}}n(sp,"validateAuthorizationResponseIssuer");function lS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(lS,"isClientAuthMethod");var fs="code",gs="S256";function pS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&lS(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(pS,"selectClientAuthMethod");function mS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":hS(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(mS,"applyClientAuthentication");function hS(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(hS,"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 ap(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(ap,"isLoopbackHost");function yS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!ap(t.hostname))throw new np(t.href);return t}n(yS,"assertSecureTokenEndpoint");function SS(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||ap(r.hostname))return"native"}return"web"}n(SS,"deriveApplicationType");function _S(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??SS(t.redirect_uris)}}n(_S,"resolveClientMetadata");async function tp(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Po.parse(JSON.parse(r));return pt.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pt(ue.ServerError,i)}}n(tp,"parseErrorResponse");async function _s(e,t){try{return await ys(e,t)}catch(r){if(r instanceof pt){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ys(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await ys(e,t)}throw r}}n(_s,"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 ys(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:u}){let p=_S(e),h=await e.discoveryState?.(),g,S,y,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(S=h.authorizationServerUrl,g=h.resourceMetadata,y=h.authorizationServerMetadata??await lp(S,{fetchFn:a,skipIssuerValidation:c}),!g)try{g=await dp(t,{resourceMetadataUrl:w},a)}catch(D){if(D instanceof TypeError)throw D}(y!==h.authorizationServerMetadata||g!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(S),resourceMetadataUrl:w?.toString(),resourceMetadata:g,authorizationServerMetadata:y})}else{let D=await TS(t,{resourceMetadataUrl:w,fetchFn:a,skipIssuerMetadataValidation:c});S=D.authorizationServerUrl,y=D.authorizationServerMetadata,g=D.resourceMetadata,k={authorizationServerUrl:String(S),resourceMetadataUrl:w?.toString(),resourceMetadata:g,authorizationServerMetadata:y}}let C=y?.issuer??String(S),U={issuer:C};if(await e.saveAuthorizationServerUrl?.(C),r!==void 0){let D=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if(D===void 0){if(e.saveDiscoveryState!==void 0)throw new hs("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",C);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(!op(D,C))throw new hs(D,C)}k&&await e.saveDiscoveryState?.(k);let O=await RS(t,e,g);O&&await e.saveResourceUrl?.(String(O));let L=wS({requestedScope:i,resourceMetadata:g,authServerMetadata:y,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),Q=ep(F,C,{canPersistStamp:e.saveClientInformation!==void 0});if(Q===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new hs(F.issuer,C);if(Q&&Q.issuer===void 0&&(Q={...Q,issuer:C},await e.saveClientInformation?.(Q,U)),!Q){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let D=y?.client_id_metadata_document_supported===!0,Ee=e.clientMetadataUrl;if(Ee&&!ws(Ee))throw new pt(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ee}`);if(D&&Ee)Q={client_id:Ee,issuer:C},await e.saveClientInformation?.(Q,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");Q={...await xS(S,{metadata:y,clientMetadata:p,scope:L,fetchFn:a}),issuer:C},await e.saveClientInformation(Q,U)}}let J=!e.redirectUrl;if(r!==void 0||J){r!==void 0&&sp({iss:o,expectedIssuer:y?.issuer,issParameterSupported:ip(y)});let D=await ES(e,S,{metadata:y,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:a});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}let V=ep(await e.tokens(U),C);if(V&&V.issuer===void 0&&(V={...V,issuer:C},await e.saveTokens(V,U)),V?.refresh_token&&!u)try{let D=await PS(S,{metadata:y,clientInformation:Q,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}catch(D){if(D instanceof np||!(!(D instanceof pt)||D.code===ue.ServerError))throw D}let Le=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:ze}=await kS(S,{metadata:y,clientInformation:Q,state:Le,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(ze),await e.redirectToAuthorization(oe),"REDIRECT"}n(ys,"authInternal");function ws(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(ws,"isHttpsUrl");async function RS(e,t,r){let o=wl(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Rl({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(RS,"selectResourceURL");function cp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=Vo(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let a=Vo(e,"scope")||void 0,c=Vo(e,"error")||void 0,u=Vo(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:a,error:c,errorDescription:u}}n(cp,"extractWWWAuthenticateParams");function Vo(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(Vo,"extractFieldFromWwwAuth");async function dp(e,t,r=fetch){let o=await CS(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 ur.parse(await o.json())}n(dp,"discoverOAuthProtectedResourceMetadata");async function up(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!Ql)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(up,"fetchWithCorsRetry");function bS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(bS,"buildWellKnownPath");async function rp(e,t,r=fetch){return await up(e,{"MCP-Protocol-Version":t},r)}n(rp,"tryMetadataDiscovery");function vS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(vS,"shouldAttemptFallback");async function CS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??Co,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let u=bS(t,i.pathname);a=new URL(u,o?.metadataServerUrl??i),a.search=i.search}let c=await rp(a,s,r);return!o?.metadataUrl&&vS(c,i.pathname)&&(c=await rp(new URL(`/.well-known/${t}`,i),s,r)),c}n(CS,"discoverMetadataWithFallback");function IS(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(IS,"buildDiscoveryUrls");async function lp(e,{fetchFn:t=fetch,protocolVersion:r=Co,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=IS(e);for(let{url:a,type:c}of s){let u=await up(a,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 ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let p=c==="oauth"?lr.parse(await u.json()):pr.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 Ss("metadata",h,p.issuer)}return p}}n(lp,"discoverAuthorizationServerMetadata");async function TS(e,t){let r,o;try{r=await dp(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 lp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(TS,"discoverOAuthServerInfo");async function kS(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(fs))throw new Error(`Incompatible auth server: does not support response type ${fs}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(gs))throw new Error(`Incompatible auth server: does not support code challenge method ${gs}`)}else c=new URL("/authorize",e);let u=await ms(),p=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",fs),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",gs),c.searchParams.set("redirect_uri",String(o)),s&&c.searchParams.set("state",s),i&&c.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:p}}n(kS,"startAuthorization");function AS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(AS,"prepareAuthorizationCodeRequest");async function pp(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:a}){let c=yS(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,c,t):o&&mS(pS(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=await(a??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await tp(p);let h=await p.json();try{return st.parse(h)}catch(g){throw typeof h=="object"&&h!==null&&"error"in h?await tp(JSON.stringify(h)):g}}n(pp,"executeTokenRequest");async function PS(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:a}){return{refresh_token:o,...await pp(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:a})}}n(PS,"refreshAuthorization");async function ES(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:a,fetchFn:c}={}){i!==void 0&&sp({iss:s,expectedIssuer:r?.issuer,issParameterSupported:ip(r)});let u=a??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=AS(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return pp(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:c})}n(ES,"fetchToken");async function xS(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 a={...r,...o===void 0?{}:{scope:o}},c=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new uS({status:c.status,body:await c.text(),submittedMetadata:a});return jt.parse(await c.json())}n(xS,"registerClient");var qT=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,$t(this,new.target)}};function US(e){let t=Mt.safeParse(e);return t.success?t.data.id:void 0}n(US,"parseJsonRpcRequestId");function mp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return US(t)}catch{return}}n(mp,"readJsonRpcRequestIdFromBody");function Ko(e){return Un.parse({jsonrpc:dr,...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(Ko,"jsonRpcErrorResponse");function hp(e){return new Go([Ao.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(hp,"urlElicitationRequiredError");var Zo=l.record(l.string(),l.unknown()),OS=l.record(l.string(),l.unknown()),ht=l.array(l.string().min(1)).min(1).optional(),qS=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:OS.optional(),_meta:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),zS=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),MS=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:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),jS=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:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),NS=l.array(l.union([l.string(),qS])),$S=l.array(l.union([l.string(),zS])),DS=l.array(l.union([l.string(),MS])),LS=l.array(l.union([l.string(),jS])),HS=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),BS=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:HS.optional()}).strict(),FS=l.object({tools:NS.optional(),prompts:$S.optional(),resources:DS.optional(),resourceTemplates:LS.optional(),accessControl:BS.optional()}).strict(),mt=[{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 JS(e,t){return _u(FS,e,`MCP capability filter policy "${t}"`)}n(JS,"parseMcpCapabilityFilterOptions");function ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ye,"isRecord");function Gn(e){return typeof e.method=="string"?e.method:void 0}n(Gn,"messageMethod");function fp(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(fp,"correlationKey");function gp(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(gp,"asStringArray");function yp(e,t){if(!ye(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>ye(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(yp,"readClaimValues");function vs(e,t){if(typeof e=="string")return{key:e,public:!1};if(!ye(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:gp(e.roles),groups:gp(e.groups),public:e.public===!0}}n(vs,"normalizeEntry");function GS(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(GS,"isCallerAllowed");function Wo(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let a=vs(s,t);a!==void 0&&GS(a,r,o)&&i.push(a.key)}return i}n(Wo,"allowedKeys");var wp=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(yp(e.user?.data,o)),a=new Set(yp(e.user?.data,i));return{tools:Wo(r.tools,"name",s,a),prompts:Wo(r.prompts,"name",s,a),resources:Wo(r.resources,"uri",s,a),resourceTemplates:Wo(r.resourceTemplates,"uriTemplate",s,a)}},"claimsCapabilityResolver");function VS(e,t){let r=[];for(let o of mt){let i=e[o.option];if(i!==void 0)for(let s of i){let a=vs(s,o.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new 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(VS,"assertNoConflictingMarkup");function KS(e,t){let r=[];for(let o of mt){let i=e[o.option];if(i!==void 0)for(let s of i){let a=vs(s,o.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new 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(KS,"assertNoMarkup");function WS(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,a,c)=>{let u=await i(s,a,c);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(WS,"buildCustomResolver");function ZS(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 WS(r,t)}if(o==="rolesAndGroups")return VS(e,t),wp;KS(e,t)}n(ZS,"buildCapabilityResolver");function YS(e){let t={};for(let r of mt){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let a=r_(s,r.itemProperty);a!==void 0&&i.set(a.key,a)}t[r.option]=i}return t}n(YS,"buildProjectionMaps");function Rs(e){return e===void 0?void 0:mt.find(t=>t.listMethod===e)}n(Rs,"findListRule");function XS(e){return e===void 0?void 0:mt.find(t=>t.directMethods.includes(e))}n(XS,"findDirectRule");function QS(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(QS,"directCapabilityAccess");function e_(e){let t=XS(Gn(e));if(t===void 0||!ye(e.raw))return;let r=e.raw.params;if(!ye(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(e_,"rawDirectCapabilityAccess");function t_(e){return Response.json(Ko({...e==null?{}:{id:e},error:{code:P.MethodNotFound,message:"Method not found"}}))}n(t_,"methodNotFoundResponse");function r_(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!ye(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(r_,"buildProjection");function Sp(e){let t=e.base[e.property],r=e.overlay[e.property];return ye(r)?ye(t)?{...t,...r}:r:t}n(Sp,"mergeRecordProperty");function n_(e,t){let r={...e,...t.overlay},o=Sp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Sp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(n_,"applyProjection");function _p(e,t,r,o){if(!ye(e))return e;let i=e.result;if(!ye(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(a=>ye(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.flatMap(a=>{if(!ye(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let u=r.get(c);return u===void 0?[]:[n_(a,u)]})}}}n(_p,"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=Rs(Gn(p)),g=h===void 0?void 0:fp(p.id);h!==void 0&&g!==void 0&&u.set(g,h)}return u.size===0?r:r.map(p=>{if(!ye(p)||"error"in p)return p;let h=fp(p.id),g=h===void 0?void 0:u.get(h),S=g===void 0?void 0:o[g.option];return g===void 0||S===void 0?p:_p(p,g,S,i?.[g.option])})}if(t.shape!=="single"||!ye(r)||"error"in r)return r;let s=t.messages[0],a=Rs(s===void 0?void 0:Gn(s)),c=a===void 0?void 0:o[a.option];return a===void 0||c===void 0?r:_p(r,a,c,i?.[a.option])}n(o_,"filterResponseBody");function i_(e){return e.headers.get("content-type")?.includes("json")??!1}n(i_,"isJsonResponse");var bs=class extends Ro{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=JS(t,r);super(o,r),this.#r=r,this.#e=YS(o),this.#t=ZS(o,r)}async handler(t,r){let o=await il(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let a of o.messages){let c=a.type==="request"?QS(a):e_(a);if(c===void 0)continue;let u=this.#e[c.option];if(u===void 0)continue;let p=i?.[c.option];if(!u.has(c.target)||p!==void 0&&!p.has(c.target))return t_(a.type==="request"?a.id:a.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async a=>{if(!i_(a))return a;let c;try{c=await a.clone().json()}catch{return a}let u=o_({envelope:o,responseBody:c,projectionMaps:s,allowedSets:i});if(u===c)return a;let p=new Headers(a.headers);return p.delete("content-length"),new Response(JSON.stringify(u),{status:a.status,statusText:a.statusText,headers:p})}),t}#n(t){return t.messages.some(r=>{let o=Gn(r);return o===void 0?!1:mt.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=Rs(Gn(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(a){r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; denying configured capabilities`,a);let c={};for(let u of mt)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let s={};for(let a of mt){let c=this.#e[a.option];if(c===void 0)continue;let u=i[a.option];if(u===void 0)continue;let p=new Set;if(Array.isArray(u))for(let h of u)typeof h=="string"&&c.has(h)&&p.add(h);s[a.option]=p}return s}};var Cs="zuplo.com",s_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),a_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Rp(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Rp,"s2FaviconHref");function c_(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(c_,"strictFaviconHref");var Yo=Rp(Cs);function Is(e){let t=e.toLowerCase();return t===Cs||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Rp(Cs):c_(e)}n(Is,"resolveIconHref");function d_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(d_,"hostnameFromHost");function u_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(u_,"isLocalOrAddressHost");function l_(e){let t=d_(e).toLowerCase().replace(/\.$/,"");if(u_(t)||a_.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=s_.has(o)?3:2;return r.slice(-i).join(".")}n(l_,"inferFaviconDomain");function Ts(e){return{src:Is(l_(e)),mimeType:"image/png",sizes:["128x128"]}}n(Ts,"resolveMcpFaviconIcon");function Xo(e){try{return Ts(new URL(e).host)}catch{return}}n(Xo,"resolveMcpFaviconIconFromUrl");function ft(e){let t=Ae().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(ft,"getUpstreamServerConfig");function Qo(e){let t=Ae().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(Qo,"getUpstreamAuthConfig");function wr(e,t){let r=Qo({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(wr,"requireUpstreamOAuthConfig");function bp(e,t){let r=Qo({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new K(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(bp,"requireUpstreamIdJagConfig");function vp(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(vp,"mergeAbortSignals");async function p_(e){try{await e.cancel()}catch{}}n(p_,"cancelReader");async function ei(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 p_(r),t.createLimitError();o.push(u),s=await r.read()}let a=new Uint8Array(i),c=0;for(let u of o)a.set(u,c),c+=u.byteLength;return a}n(ei,"readBoundedByteStream");var m_=2,h_=1024*1024,f_=1e4,g_=new Set([301,302,303,307,308]),y_=["authorization","proxy-authorization","cookie","cookie2"];function ks(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(ks,"readRequestUrl");function Rr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Rr,"readRequestMethod");function S_(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:{[I]:r}})}n(S_,"assertContentLengthWithinLimit");async function __(e,t,r){return S_(e,t,r),ei(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}}),"createLimitError")})}n(__,"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 R_(e,t){if(!g_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(R_,"resolveRedirectUrl");function Cp(e,t){try{return t.validateUrl(e)}catch(r){throw new v({message:"Outbound URL was not allowed.",extensionMembers:{[I]:t.problemCode}},{cause:r})}}n(Cp,"validateOutboundUrl");function b_(e,t){throw e instanceof v&&Eo(e.extensionMembers?.[I])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[I]:t}},{cause:e})}n(b_,"normalizeFetchError");function Vn(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(Vn,"logOutboundFailure");async function v_(e,t,r,o,i,s,a){let c=Rr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";Vn(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:ee(s),error:u,extra:{abortReason:a()}}),b_(u,i)}}n(v_,"fetchWithNormalizedError");function C_(e){if(e.redirects>=e.maxRedirects)throw new v({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[I]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new v({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[I]:e.problemCode}})}n(C_,"assertRedirectAllowed");function I_(e,t){let r=new Headers(e);for(let o of y_)r.delete(o);for(let o of t)r.delete(o);return r}n(I_,"stripCrossOriginHeaders");function T_(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=I_(e.headers,i)),s}n(T_,"buildRedirectInit");function k_(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(k_,"buildInitialRequestInit");function A_(e){let t=Rr(e.currentInput,e.currentInit);C_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Cp(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:T_(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(A_,"followRedirect");async function As(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??m_,s=r.maxResponseBytes??h_,a=r.timeoutMs??f_,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,g=vp(h,t.signal),S=!1,y=setTimeout(()=>{S=!0,h.abort()},a),k=e,w=k_(e,t,h.signal),C;try{C=Cp(ks(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw Vn(p,{event:"outbound_url_blocked",problemCode:o,method:Rr(e,t),host:ee(ks(e)),error:O}),clearTimeout(y),g?.(),O}let U=0;try{for(;;){let O=await v_(p,c,k,w,o,C,()=>S?`timeout_after_${a}ms`:void 0),L=R_(O,C);if(L!==void 0)try{let F=A_({currentInput:k,currentInit:w,currentUrl:C,redirectUrl:L,redirects:U,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});k=F.currentInput,w=F.currentInit,C=F.currentUrl,U=F.redirects;continue}catch(F){throw Vn(p,{event:"outbound_redirect_blocked",problemCode:o,method:Rr(k,w),host:ee(C),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:ee(L)}}),F}try{return w_(O,await __(O,s,o))}catch(F){throw Vn(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Rr(k,w),host:ee(C),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(y),g?.()}}n(As,"runSafeOutboundExchange");async function Kn(e,t,r){let o=await As(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Vn(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Rr(e,t),host:ee(ks(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:{[I]:r.problemCode??"invalid_request"}},{cause:i})}}n(Kn,"runSafeOutboundJsonExchange");function Ip(e,t={},r={}){return As(e,t,{...r,validateUrl:jn})}n(Ip,"fetchConfiguredOutbound");function Tp(e,t={},r={}){return Kn(e,t,{...r,validateUrl:jn})}n(Tp,"fetchConfiguredOutboundJson");function ti(e,t={},r={}){return Kn(e,t,{...r,validateUrl:Ku})}n(ti,"fetchIdentityProviderJson");function kp(e,t={},r={}){return Kn(e,t,{...r,validateUrl:jo})}n(kp,"fetchCimdClientMetadataJson");function Ap(e,t={},r={}){return Kn(e,t,{...r,validateUrl:Nn})}n(Ap,"fetchCimdClientJwksJson");import{errors as qp,jwtVerify as zp,SignJWT as Mp}from"jose";var Se="zuplo-mcp-gateway",ve=Se,Ce="HS256";import{base64url as P_}from"jose";var E_=new TextEncoder,x_="MCP gateway could not initialize secure key material.",U_=32,Pp=new Map,Ep=new Map,O_;function q_(){return O_??wa.instance.authPrivateKey}n(q_,"readAuthPrivateKey");function xp(e){return new ke(x_,e===void 0?void 0:{cause:e})}n(xp,"createGeneratedKeyMaterialError");function Up(e,t){let r=P_.decode(t);if(r.byteLength!==U_)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Up,"decodeJwkKeyField");function z_(e){let t=q_();if(!t)throw xp();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=Up("d",r.d);Up("x",r.x);let i=E_.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 xp(r)}}n(z_,"decodeGeneratedKeyMaterial");function M_(e){let t=Pp.get(e);return t||(t=z_(e),Pp.set(e,t)),t}n(M_,"getMasterKeyMaterial");async function $e(e){let t=Ep.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(M_(e.keyMaterialPurpose));return Ep.set(e.purpose,r),r}n($e,"readCachedDerivedKey");var j_="SHA-256",N_=32,$_="zuplo-mcp-gateway:",D_=new TextEncoder,Op=new WeakMap;async function gt(e,t){let r=Op.get(e);r||(r=new Map,Op.set(e,r));let o=r.get(t);if(o)return o;let i=await L_(e,t);return r.set(t,i),i}n(gt,"deriveGatewaySigningKey");async function L_(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=D_.encode(`${$_}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:j_,salt:new Uint8Array,info:me(i)},o,N_*8);return new Uint8Array(s)}n(L_,"hkdfExpand");var jp=900,H_=900,B_=Eu.extend({id:Qu}),F_=B_.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Np=Mi.extend({id:el,purpose:l.literal("browser_connect")}),J_=Mi.extend({purpose:l.literal("browser_connect")}),G_=Np.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),$p=jp*1e3;async function Dp(){return $e({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>gt(e,"oauth-state"),"derive")})}n(Dp,"getOAuthStateKey");async function Lp(){return $e({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>gt(e,"browser-connect"),"derive")})}n(Lp,"getBrowserConnectKey");async function Hp(e){let t=Math.floor(Date.now()/1e3)+jp;return new Mp(e).setProtectedHeader({alg:Ce,typ:"JWT"}).setIssuer(Se).setAudience(ve).setIssuedAt().setExpirationTime(t).sign(await Dp())}n(Hp,"signOAuthState");async function ri(e){try{let{payload:t}=await zp(e,await Dp(),{algorithms:[Ce],issuer:Se,audience:ve});return F_.parse(t)}catch(t){throw t instanceof qp.JWTExpired?new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"OAuth state could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(ri,"verifyOAuthState");async function Bp(e){let t=Math.floor(Date.now()/1e3)+H_,r=J_.parse(e),o=Np.parse({...r,id:ol()});return new Mp(o).setProtectedHeader({alg:Ce,typ:"JWT"}).setIssuer(Se).setAudience(ve).setIssuedAt().setExpirationTime(t).sign(await Lp())}n(Bp,"signBrowserConnectTicket");async function Fp(e){try{let{payload:t}=await zp(e,await Lp(),{algorithms:[Ce],issuer:Se,audience:ve});return G_.parse(t)}catch(t){throw t instanceof qp.JWTExpired?new v({message:"Browser connect ticket has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"Browser connect ticket could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(Fp,"verifyBrowserConnectTicket");async function Jp(e){if((await j().consumeBrowserConnectTicket({id:e.id,expiresAt:$(new Date(e.exp*1e3)),now:$(new Date)})).kind==="consumed")throw new v({message:"Browser connect ticket has already been used",extensionMembers:{[I]:"oauth_state_reused"}})}n(Jp,"consumeBrowserConnectTicket");function V_(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(V_,"buildConnectRequiredMessage");async function K_(e){let t=re(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 Bp({...zn(e),purpose:"browser_connect"})),r.toString()}n(K_,"buildGatewayBrowserTicketUrl");function W_(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(W_,"buildGatewayConnectPath");async function Ps(e){return K_({...e,path:W_(e.upstreamServerId),redirect:!0})}n(Ps,"buildGatewayConnectUrl");async function ni(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Ps(t),message:V_(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ni,"buildRedirectConnectRequiredResponse");function Gp(e){return Z_({...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(Gp,"buildAdminConnectRequiredResponse");function Z_(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(Z_,"buildAdminSetupRequiredResponse");var Vp=12;async function Kp(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(Kp,"sha256Hex");async function Dt(e){if(e)return(await Kp(e)).slice(0,Vp)}n(Dt,"fingerprintSecret");async function br(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Kp(t)).slice(0,Vp)}n(br,"fingerprintConnectionIdentity");var Y_=6e4;function vr(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(vr,"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()+Y_)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var Wp=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function X_(e,t){return e&&e.length>0?e.join(t):void 0}n(X_,"joinOAuthScopes");function Q_(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Wp)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Q_,"sanitizeAuthorizationServerMetadata");function Zp(e){let t=Q_(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Zp,"sanitizeOAuthDiscoveryState");function Yp(e){let t=new URL(e);for(let r of Wp){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Yp,"dedupeSingletonAuthorizationRequestParams");function oi(e){let t=new URL(e);return Re(t)&&Su(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(oi,"normalizeLoopbackOAuthRedirectUri");function Xp(e){return X_(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Xp,"readProtectedResourceMetadataScope");function ew(e){return`Zuplo MCP Gateway - ${e}`}n(ew,"buildGatewayOAuthClientName");function tw(e,t){return e&&e.length>0?e.join(t):void 0}n(tw,"joinOAuthScopeList");function rw(e){if(e.clientRegistration.mode!=="auto")return tw(e.scopes,e.scopeDelimiter)}n(rw,"readPublicClientMetadataScope");function Es(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Es,"buildOAuthClientMetadataDocumentUrl");function xs(e){let t=ft(e.upstreamServerId);return{client_name:ew(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(xs,"buildGatewayOAuthClientMetadata");function Qp(e,t,r){let o=wr(t,r),i=rw(o);return{client_id:Es({origin:e,upstreamServerId:t}),...xs({origin:e,upstreamServerId:t,redirectUri:oi(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Qp,"buildOAuthClientMetadataDocument");import{base64url as yt}from"jose";var nw="SHA-256",Cr="AES-GCM",ow=12,Os="zuplo-secret",qs=1,em="generated:auth_private_key:token-encryption",iw=l.object({version:l.literal(qs),keyId:l.literal(em),algorithm:l.literal(Cr),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Us(){return $e({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(nw,me(e));return crypto.subtle.importKey("raw",t,{name:Cr},!1,["encrypt","decrypt"])},"derive")})}n(Us,"getEncryptionKey");function tm(e){return me(new TextEncoder().encode(`${Os}:v${e.version}:${e.keyId}`))}n(tm,"getAssociatedData");function sw(e){return`${Os}:v${e.version}:${yt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(sw,"encodeEnvelope");function aw(e){let t=`${Os}:v${qs}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(yt.decode(r));return iw.parse(JSON.parse(o))}n(aw,"decodeEnvelope");async function We(e){let t=await Us(),r=crypto.getRandomValues(new Uint8Array(ow)),o={version:qs,keyId:em},i=await crypto.subtle.encrypt({name:Cr,iv:r,additionalData:tm(o)},t,new TextEncoder().encode(e));return sw({...o,algorithm:Cr,iv:yt.encode(r),ciphertext:yt.encode(new Uint8Array(i))})}n(We,"encryptSecret");async function Ze(e){let t=aw(e);if(t){let a=await Us(),c=await crypto.subtle.decrypt({name:Cr,iv:me(yt.decode(t.iv)),additionalData:tm(t)},a,me(yt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ke("Encrypted payload is malformed");let i=await Us(),s=await crypto.subtle.decrypt({name:Cr,iv:me(yt.decode(r))},i,me(yt.decode(o)));return new TextDecoder().decode(s)}n(Ze,"decryptSecret");var rm={issuer:l.string().min(1).optional()},cw=l.union([jt.extend(rm),On.extend(rm)]),nm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:ur.optional(),authorizationServerMetadata:l.union([lr,pr]).optional()}).passthrough(),dw="Bearer",uw="__zuplo_refresh_only_upstream_access_token__";function zs(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(zs,"splitScopes");function Ms(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ms,"scopesCover");function lw(e){return hr.parse(e)}n(lw,"parsePkceCodeVerifier");function pw(e){if(typeof e.expires_in=="number")return $(new Date(Date.now()+e.expires_in*1e3))}n(pw,"readTokenExpiry");async function om(e){if(e!==void 0)return We(JSON.stringify(e))}n(om,"encryptJson");async function im(e,t){if(!e)return;let r=await Ze(e);try{return t.parse(JSON.parse(r))}catch(o){throw new v({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:o})}}n(im,"decryptJson");function mw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(mw,"clientInformationAllowsRedirectUri");function hw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(hw,"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 yw(e,t){return Xp({state:e,delimiter:t})}n(yw,"readResourceMetadataScope");function Sw(e,t){return e&&e.length>0?e.join(t):void 0}n(Sw,"joinOAuthScopeList");function _w(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 jt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(_w,"buildManualOAuthClientInformation");function ww(e,t){let r=Es({origin:new URL(t).origin,upstreamServerId:e});return ws(r)?r:void 0}n(ww,"buildClientMetadataUrl");function Rw(e){for(let t of e)if(t!==void 0)return t}n(Rw,"firstDefined");function bw(e){let t=wr(e.target.upstreamServerId,e.target.authProfileId),r=Sw(t.scopes,t.scopeDelimiter),o=xs({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,configuredClientInformation:_w({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}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(bw,"buildInitialOAuthClientSetup");function vw(e,t){if(t===void 0)return Rw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(vw,"readEncryptedClientInformation");function Cw(e){return e.pendingState?.encryptedDiscoveryState}n(Cw,"readEncryptedDiscoveryState");function js(e,t){return t===void 0?e:{...e,issuer:t}}n(js,"applyIssuerStamp");var St=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=bw({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.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=vw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Cw(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}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 Ms(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 br({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Dt(await Ze(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await j().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 Hp({id:t.id,...zn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?js(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 om(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Zp(nm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await om(r),await this.syncPendingState(!1),W()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ee(r.authorizationServerUrl),resourceMetadataHost:ee(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=yw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let 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 js(r,t?.issuer)}async saveTokens(t){let r=st.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,a=r.refresh_token?await We(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:st.parse({...r,refresh_token:await Ze(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:i?.id??No(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await We(r.access_token),encryptedRefreshToken:a,scopes:zs(r.scope??this.readEffectiveScope()),expiresAt:pw(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(c,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ms(p.connection.scopes,c.scopes)||!vr(i,p.connection))){h=!0;let S=p.connection,y={id:S.id,ownerMode:S.ownerMode,subjectId:S.subjectId,upstreamServerId:S.upstreamServerId,authProfileId:S.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?S.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:S.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:S.id,sourceUpdatedAt:i?.updatedAt,winnerUpdatedAt:S.updatedAt,sourceScopeCount:i?.scopes.length,winnerScopeCount:S.scopes.length,resultingScopeCount:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),p=await this.conditionalUpsertCredential(y,{expectedUpdatedAt:S.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,vr(i,p.connection)&&he(p.connection)==="usable"&&Ms(p.connection.scopes,c.scopes)?this.adoptPeerConnection(p.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),h){let S=p.kind==="persisted"?"succeeded":p.kind==="precondition_failed"?"lost":"exhausted";W()?.info({event:`upstream_oauth_bounded_rebase_${S}`,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 ${S}`)}let g=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:g?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Dt(r.refresh_token),reusedSnapshotRefreshToken:s,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:p.kind,rebaseAttempted:h,resultingUpdatedAt:g?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:g?.scopes.length??this.credentialState.currentConnection?.scopes.length},g?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Yp(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:lw(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new v({message:"OAuth code verifier is missing",extensionMembers:{[I]:"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:nl(),...zn({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:$(new Date(Date.now()+$p)),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 j().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 im(this.encryptedClientInformation,cw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!mw(r,this.redirectUriValue)||!hw({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=js(On.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 im(this.encryptedDiscoveryState,nm)}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 Ze(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Ze(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Dt(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=st.parse({access_token:r??uw,token_type:dw,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 a=await this.conditionalUpsertCredential(s,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,vr(r,a.connection)&&he(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=W();if(c){let u=a.kind==="missing"?void 0:a.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:a.kind};a.kind==="precondition_failed"?c.warn({...p,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(p,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(p,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Iw=3e4,Tw=256*1024,kw=2,Aw="does not support dynamic client registration",Pw=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Ew=["HTTP 403 Forbidden","Access Denied","permission to access"],xw=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function Uw(e){return e instanceof Error&&e.message.includes(Aw)}n(Uw,"isDynamicClientRegistrationUnsupported");function Ow(e){return e instanceof Error&&Pw.some(t=>e.message.includes(t))}n(Ow,"isProtectedResourceMetadataUnavailable");function qw(e){return e instanceof Error&&Ew.some(t=>e.message.includes(t))}n(qw,"isUpstreamProviderAccessDenied");function zw(e){return e instanceof pt&&xw.has(e.code)}n(zw,"isStoredConnectionReconsentError");function Mw(e){if(e.error instanceof v&&e.error.extensionMembers?.[I]!==void 0)return e.error;if(Uw(e.error))return new v({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.`,extensionMembers:{[I]:"upstream_client_registration_required"}},{cause:e.error});if(Ow(e.error))return new v({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.`,extensionMembers:{[I]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(qw(e.error))return new v({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[I]:"upstream_provider_access_denied"}},{cause:e.error})}n(Mw,"mapUpstreamOAuthSetupError");function jw(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(jw,"readOAuthFetchRequest");function Nw(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Nw,"responseLooksJson");function $w(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($w,"responseLooksHtml");function Dw(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:{[I]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[at]:e.response.status,[fr]:r,[ct]:e.request.url.toString(),[gr]:e.body}})}n(Dw,"throwUpstreamHtmlError");function Lw(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(Lw,"readUpstreamOAuthErrorBody");function Hw(e){let{error:t,errorDescription:r}=Lw(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:ee(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(Hw,"logUpstreamOAuthHttpError");function am(e){return async(t,r)=>{let o=jw(t),i=W(),s=Date.now(),a=await Ip(t,r,{maxRedirects:kw,maxResponseBytes:Tw,problemCode:"upstream_token_exchange_failed",timeoutMs:Iw}),c=await a.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:ee(o.url),path:o.url.pathname,status:a.status,durationMs:Date.now()-s,responseChars:c.length},"Upstream OAuth HTTP request completed"),a.ok||Hw({log:i,upstreamServerId:e,request:o,response:a,body:c}),!a.ok&&$w(a,c)&&Dw({upstreamServerId:e,request:o,response:a,body:c}),!Nw(a,c))return a;try{JSON.parse(c)}catch(u){throw new v({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}},{cause:u})}return a}}n(am,"createUpstreamOAuthFetch");function cm(e){W()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ee(e.serverUrl),resourceMetadataHost:ee(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(cm,"logUpstreamOAuthFlowStarted");function dm(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ee(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof v?e.error.extensionMembers?.[I]: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(dm,"logUpstreamOAuthFlowFailed");function um(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(um,"readAuthorizationRequestScope");async function lm(e,t){e.applyChallengeScope(t.requestedScope),cm({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:am(t.upstreamServerId)},o=um(e,t);return o!==void 0&&(r.scope=o),await _s(e,r)}catch(r){dm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Mw({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(lm,"runUpstreamOAuth");async function Bw(e,t){e.applyChallengeScope(t.requestedScope),cm({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:am(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=um(e,t);o!==void 0&&(r.scope=o);try{return await _s(e,r)}catch(i){throw dm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(Bw,"exchangeUpstreamAuthorizationCode");async function sm(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await j().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||he(r)!=="usable"||!vr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(sm,"adoptPeerCredentialAtResolutionBoundary");async function pm(e,t){let r=await lm(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:{[I]:"upstream_token_exchange_failed"}}):new v({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(pm,"requireUpstreamAuthorizationRedirect");async function mm(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 br({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 a;try{a=await lm(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!zw(c))throw c;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.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 sm({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 Ns({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Ns({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new v({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[I]:"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:{[I]:"upstream_token_exchange_failed"}});return await sm({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 Ns({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(mm,"authorizeUpstreamOAuthSession");async function Fw(e){let t=await ri(e.stateToken),r=await j().consumeUpstreamOAuthState({id:t.id,now:$(new Date)}),o=Jw(r);return Gw({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Vw(o),o}n(Fw,"consumeStoredCallbackState");function Jw(e){switch(e.kind){case"consumed":throw new v({message:"OAuth state has already been used",extensionMembers:{[I]:"oauth_state_reused"}});case"missing":throw new v({message:"OAuth state is missing or expired",extensionMembers:{[I]:"oauth_state_expired"}});case"available":return e.record}}n(Jw,"readConsumedCallbackState");function Gw(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:{[I]:"oauth_callback_mismatch"}})}n(Gw,"assertStoredCallbackStateMatches");function Vw(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}})}n(Vw,"assertStoredCallbackStateFresh");async function Ns(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),Gp(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),ni(t)}n(Ns,"buildOAuthConnectRequiredResponse");async function hm(e){let t=await Fw({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Oo(t),[o]=await j().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 St(i),a=await Bw(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(a==="AUTHORIZED"){let c=s.readUsablePeerAdoption();if(c!==void 0&&await s.adoptConnectionForDirectResolution(c,"cas_loss"),!s.tokenWriteWasPersisted&&c===void 0)throw new v({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new v({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(hm,"finishUpstreamOAuthCallback");import{importPKCS8 as Kw,SignJWT as Ww}from"jose";var gm=1e4,ym=64*1024,Sm=2,Zw=300,qe=l.string().min(1),Yw=l.object({access_token:qe,issued_token_type:l.literal(Ni),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:qe.optional()}).passthrough(),Xw=l.object({id_token:qe,token_type:qe.optional(),expires_in:l.number().int().positive().optional(),refresh_token:qe.optional(),scope:qe.optional()}).passthrough(),Qw=l.object({access_token:qe,token_type:qe,expires_in:l.number().int().positive().optional(),scope:qe.optional(),resource:qe.optional(),refresh_token:qe.optional()}).passthrough();function fm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(fm,"formEncodeClientCredential");function eR(e){return e.replaceAll("\\n",`
|
|
25
|
+
import{$ as Ea,$a as Cc,$b as vd,$c as pu,$e as hr,$f as ji,A as Ro,Aa as Xa,Ab as Yc,Ac as $d,Af as ku,Ag as jo,Ba as Qa,Bb as Xc,Bc as Dd,Bf as Uo,Bg as Nn,Ca as ec,Cb as Qc,Cc as Ld,Cf as qn,Cg as Wu,Da as tc,Db as ed,Dc as Hd,Df as Au,Dg as Zu,Ea as rc,Eb as td,Ec as Bd,Ef as yr,Eg as Yu,Fa as nc,Fb as rd,Fc as Fd,Ff as Pu,Fg as Xu,Ga as oc,Gb as nd,Gc as Jd,Gf as Mi,Gg as Qu,Ha as ic,Hb as od,Hc as Gd,Hf as Eu,Hg as el,Ia as Ti,Ib as id,Ic as Vd,If as zn,Ig as tl,Ja as sc,Jb as sd,Jc as Kd,Jf as Oo,Jg as rl,Ka as ac,Kb as ad,Kc as Wd,Kf as xu,Kg as No,La as cc,Lb as cd,Lc as Zd,Lf as Uu,Lg as nl,Ma as dc,Mb as dd,Mc as Yd,Mf as Ou,Mg as ol,Na as uc,Nb as ud,Nc as Xd,Nf as qu,Ng as j,Oa as lc,Ob as ld,Oc as Qd,Of as Ae,Og as G,Pa as pc,Pb as pd,Pc as eu,Pf as de,Pg as me,Q as Co,Qa as mc,Qb as md,Qc as tu,Qf as zu,Qg as Ke,R as bi,Ra as hc,Rb as ki,Rc as ru,Rf as Mu,Rg as Y,S as sr,Sa as fc,Sb as hd,Sc as nu,Sf as $,Sg as $o,T as En,Ta as gc,Tb as fd,Tc as ou,Te as Su,Tf as Ge,Tg as Qf,U as ar,Ua as yc,Ub as gd,Uc as iu,Ue as Re,Uf as Sr,Ug as eg,V as cr,Va as Sc,Vb as yd,Vc as su,Ve as _u,Vf as pe,W as xn,Wa as _c,Wb as Sd,Wc as au,We as wu,Wf as ee,X as dr,Xa as wc,Xb as _d,Xc as cu,Xe as re,Xf as ju,Y as ka,Ya as Rc,Yb as wd,Yc as du,Ye as Ru,Yf as W,Z as Aa,Za as bc,Zb as Rd,Zc as uu,Ze as mr,Zf as Nu,_ as Pa,_a as vc,_b as bd,_c as lu,_e as bu,_f as ut,aa as xa,ab as Ic,ac as Cd,ad as ur,af as I,ag as qo,ba as Ua,bb as Tc,bc as Id,bd as lr,bf as fr,bg as Ni,ca as Oa,cb as kc,cc as Td,cd as mu,cf as gr,cg as zo,da as qa,db as Ac,dc as kd,dd as pr,df as at,dg as Mn,ea as za,eb as Pc,ec as Ad,ed as st,ef as ct,eg as _r,fa as Ma,fb as Ec,fc as Pd,fd as zi,ff as Eo,fg as $u,ga as ja,gb as xc,gc as Ai,gd as Po,gf as vu,gg as Ve,ha as Na,hb as Uc,hc as Io,hd as hu,hf as Oe,hg as $i,ia as $a,ib as Oc,ic as To,id as On,if as Cu,ig as Di,ja as Da,jb as qc,jc as Pi,jd as jt,jf as Je,jg as Du,k as Fe,ka as La,kb as zc,kc as Ei,kd as fu,kf as x,kg as Mo,la as Ha,lb as Mc,lc as xi,ld as gu,lf as xo,lg as Li,ma as Mt,mb as jc,mc as Ed,mf as le,mg as Hi,na as vi,nb as Nc,nc as Ui,nf as dt,ng as Lu,oa as Ci,ob as $c,oc as Oi,of as Bf,og as ne,pa as Un,pb as Dc,pc as xd,pf as Ff,pg as Hu,qa as Ii,qb as Lc,qc as Ud,qf as Jf,qg as Bu,r as zt,ra as Ba,rb as Hc,rc as qi,rd as yu,rf as Gf,rg as Bi,s as Ra,sa as Fa,sb as Bc,sc as ko,sf as Vf,sg as Fu,ta as Ja,tb as Fc,tc as Ao,tf as Kf,tg as Ju,ua as Ga,ub as Jc,uc as Od,uf as Wf,ug as Fi,va as Va,vb as Gc,vc as qd,vf as Zf,vg as Gu,wa as Ka,wb as Vc,wc as zd,wf as Yf,wg as Nt,xa as Wa,xb as Kc,xc as Md,xf as Xf,xg as Vu,y as va,ya as Za,yb as Wc,yc as jd,yf as Iu,yg as jn,za as Ya,zb as Zc,zc as Nd,zf as Tu,zg as Ku}from"../chunk-TPXAFGLU.js";import"../chunk-B3D32RUX.js";import{a as H}from"../chunk-4VE55TG3.js";import{a as il}from"../chunk-6SNZ4DOC.js";import{a as ba}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as f,B as z,C as Ri,D as vo,G as l,h as _i,i as An,j as Ca,k as d,l as Ia,m as Ta,n as b,o as E,p as bo,r as q,s as _,t as m,u as M,v as A,w as wi,x as Pn,y as T,z as N}from"../chunk-4CDML74A.js";import"../chunk-UKQQD2JN.js";import{W as ke,X as v,Y as K,Z as wa,_ as wo}from"../chunk-4POCC75H.js";import{a as n}from"../chunk-TYV53J3B.js";var tg=Object.create,Do=Object.defineProperty,rg=Object.getOwnPropertyDescriptor,ng=Object.getOwnPropertyNames,og=Object.getPrototypeOf,ig=Object.prototype.hasOwnProperty,sl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),al=n((e,t)=>{let r={};for(var o in e)Do(r,o,{get:e[o],enumerable:!0});return t&&Do(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),sg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=ng(t),s=0,a=i.length,c;s<a;s++)c=i[s],!ig.call(e,c)&&c!==r&&Do(e,c,{get:(u=>t[u]).bind(null,c),enumerable:!(o=rg(t,c))||o.enumerable});return e},"__copyProps"),cl=n((e,t,r)=>(r=e!=null?tg(og(e)):{},sg(t||!e||!e.__esModule?Do(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var ag=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function dl(e){return typeof e=="string"&&ag.has(e.replace(/#$/,""))}n(dl,"declares2019Dialect");var Zi=Symbol.for("mcp.sdk.errorBrands");function $t(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,Zi,{value:r,enumerable:!1,configurable:!0})}n($t,"stampErrorBrands");function be(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Zi)){let r=t[Zi];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(be,"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})({}),pt=class _l extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return be(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 be(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",$t(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 _l(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})({}),te=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",$t(this,new.target)}},_g=class extends te{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 wl(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(wl,"resourceUrlFromServerUrl");function Rl({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(Rl,"checkResourceAllowed");var wg="2026-07-28";function bl(e){return e>=wg}n(bl,"isModernProtocolVersion");function vl(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(vl,"appendTextFallbackForNonObject");var Cl=["task","inputRequests","requestState"];function Rg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Cl.some(t=>t in e)?e:{...e,content:[]}}n(Rg,"normalizeContentlessToolResult");function bg(){let e=Ri(()=>A([d(),b(),E(),bo(),T(d(),e),_(e)])),t=T(d(),e),r=A([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),a=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),c=m({_meta:a.optional()}),u=c.extend({task:i.optional()}),p=m({method:d(),params:c.loose().optional()}),h=m({_meta:a.optional()}),g=m({method:d(),params:h.loose().optional()}),S=M({_meta:a.optional()}),y=A([d(),b().int()]),k=S.strict(),w=h.extend({requestId:y.optional(),reason:d().optional()}),C=g.extend({method:f("notifications/cancelled"),params:w}),U=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:N(["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()}),Q=Pn(m({applyDefaults:E().optional()}),t),J=vo(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,Pn(m({form:Q.optional(),url:t.optional()}),t.optional())),V=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),Le=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),oe=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:V.optional(),extensions:T(d(),t).optional()}),ze=c.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),D=p.extend({method:f("initialize"),params:ze}),Ee=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:Le.optional(),extensions:T(d(),t).optional()}),qr=S.extend({protocolVersion:d(),capabilities:Ee,serverInfo:F,instructions:d().optional()}),Bt=g.extend({method:f("notifications/initialized"),params:h.optional()}),et=p.extend({method:f("ping"),params:c.optional()}),bt=m({progress:b(),total:z(b()),message:z(d())}),Me=m({...h.shape,...bt.shape,progressToken:r}),tt=g.extend({method:f("notifications/progress"),params:Me}),Ft=c.extend({cursor:o.optional()}),He=p.extend({params:Ft.optional()}),Be=S.extend({nextCursor:o.optional()}),Jt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),Gt=Jt.extend({text:d()}),vt=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vt=Jt.extend({blob:vt}),je=N(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:An.datetime({offset:!0}).optional()}),Ct=m({...L.shape,...O.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:xe.optional(),_meta:z(M({}))}),zr=m({...L.shape,...O.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:xe.optional(),_meta:z(M({}))}),Mr=He.extend({method:f("resources/list")}),jr=Be.extend({resources:_(Ct)}),rt=He.extend({method:f("resources/templates/list")}),Kt=Be.extend({resourceTemplates:_(zr)}),It=c.extend({uri:d()}),Nr=It,$r=p.extend({method:f("resources/read"),params:Nr}),Dr=S.extend({contents:_(A([Gt,Vt]))}),Lr=g.extend({method:f("notifications/resources/list_changed"),params:h.optional()}),Hr=It,Br=p.extend({method:f("resources/subscribe"),params:Hr}),Fr=It,Jr=p.extend({method:f("resources/unsubscribe"),params:Fr}),Gr=h.extend({uri:d()}),Vr=g.extend({method:f("notifications/resources/updated"),params:Gr}),Kr=m({name:d(),description:z(d()),required:z(E())}),Wr=m({...L.shape,...O.shape,description:z(d()),arguments:z(_(Kr)),_meta:z(M({}))}),Zr=He.extend({method:f("prompts/list")}),Yr=Be.extend({prompts:_(Wr)}),Xr=c.extend({name:d(),arguments:T(d(),d()).optional()}),Qr=p.extend({method:f("prompts/get"),params:Xr}),Tt=m({type:f("text"),text:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),kt=m({type:f("image"),data:vt,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),At=m({type:f("audio"),data:vt,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),en=m({type:f("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),nt=m({type:f("resource"),resource:A([Gt,Vt]),annotations:xe.optional(),_meta:T(d(),q()).optional()}),tn=Ct.extend({type:f("resource_link")}),Te=A([Tt,kt,At,tn,nt]),Wt=m({role:je,content:Te}),Zt=S.extend({description:d().optional(),messages:_(Wt)}),Pt=g.extend({method:f("notifications/prompts/list_changed"),params:h.optional()}),rn=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yt=m({taskSupport:N(["required","optional","forbidden"]).optional()}),Et=m({...L.shape,...O.shape,description:d().optional(),inputSchema:m({type:f("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()),outputSchema:m({type:f("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()).optional(),annotations:rn.optional(),execution:Yt.optional(),_meta:T(d(),q()).optional()}),Xt=He.extend({method:f("tools/list")}),Qt=Be.extend({tools:_(Et)}),er=S.extend({content:_(Te),structuredContent:T(d(),q()).optional(),isError:E().optional()}),ae=u.extend({name:d(),arguments:T(d(),q()).optional()}),nn=p.extend({method:f("tools/call"),params:ae}),ro=g.extend({method:f("notifications/tools/list_changed"),params:h.optional()}),tr=N(["debug","info","notice","warning","error","critical","alert","emergency"]),on=c.extend({level:tr}),sn=p.extend({method:f("logging/setLevel"),params:on}),an=h.extend({level:tr,logger:d().optional(),data:q()}),cn=g.extend({method:f("notifications/message"),params:an}),dn=m({name:d().optional()}),un=m({hints:_(dn).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),ln=m({mode:N(["auto","required","none"]).optional()}),no=m({type:f("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(Te),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),pn=wi("type",[Tt,kt,At]),ot=wi("type",[Tt,kt,At,en,no]),mn=m({role:je,content:A([ot,_(ot)]),_meta:T(d(),q()).optional()}),hn=u.extend({messages:_(mn),modelPreferences:un.optional(),systemPrompt:d().optional(),includeContext:N(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Et).optional(),toolChoice:ln.optional()}),fn=p.extend({method:f("sampling/createMessage"),params:hn}),gn=S.extend({model:d(),stopReason:z(N(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:pn}),yn=S.extend({model:d(),stopReason:z(N(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:A([ot,_(ot)])}),Sn=m({type:f("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),_n=m({type:f("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:N(["email","uri","date","date-time"]).optional(),default:d().optional()}),wn=m({type:N(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Rn=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),bn=m({type:f("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),vn=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Cn=A([Rn,bn]),xt=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:f("string"),enum:_(d())}),default:_(d()).optional()}),Ut=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),oo=A([xt,Ut]),io=A([vn,Cn,oo]),_e=A([io,Sn,_n,wn]),we=u.extend({mode:f("form").optional(),message:d(),requestedSchema:m({type:f("object"),properties:T(d(),_e),required:_(d()).optional()}).catchall(q())}),In=u.extend({mode:f("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=A([we,In]),so=p.extend({method:f("elicitation/create"),params:Ue}),ao=h.extend({elicitationId:d()}),co=g.extend({method:f("notifications/elicitation/complete"),params:ao}),uo=S.extend({action:N(["accept","decline","cancel"]),content:vo(ce=>ce===null?void 0:ce,T(d(),A([d(),b(),E(),_(d())])).optional())}),lo=m({type:f("ref/resource"),uri:d()}),po=m({type:f("ref/prompt"),name:d()}),mo=c.extend({ref:A([po,lo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),Tn=p.extend({method:f("completion/complete"),params:mo}),ho=S.extend({completion:M({values:_(d()).max(100),total:z(b().int()),hasMore:z(E())})}),fo=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),rr=p.extend({method:f("roots/list"),params:c.optional()}),kn=S.extend({roots:_(fo)}),go=g.extend({method:f("notifications/roots/list_changed"),params:h.optional()}),yo=M({ttl:b().optional(),pollInterval:b().optional()}),So=N(["working","input_required","completed","failed","cancelled"]),it=m({taskId:d(),status:So,ttl:A([b(),bo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:z(b()),statusMessage:z(d())}),fe=S.extend({task:it}),_o=h.merge(it),Ot=g.extend({method:f("notifications/tasks/status"),params:_o}),nr=p.extend({method:f("tasks/get"),params:c.extend({taskId:d()})}),or=S.merge(it),ir=p.extend({method:f("tasks/result"),params:c.extend({taskId:d()})}),Si=S.loose(),ge=He.extend({method:f("tasks/list")}),Z=Be.extend({tasks:_(it)}),qt=p.extend({method:f("tasks/cancel"),params:c.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:u,RequestSchema:p,NotificationsParamsSchema:h,NotificationSchema:g,ResultSchema:S,RequestIdSchema:y,EmptyResultSchema:k,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:C,IconSchema:U,IconsSchema:O,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Le,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:ze,InitializeRequestSchema:D,ServerCapabilitiesSchema:Ee,InitializeResultSchema:qr,InitializedNotificationSchema:Bt,PingRequestSchema:et,ProgressSchema:bt,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:tt,PaginatedRequestParamsSchema:Ft,PaginatedRequestSchema:He,PaginatedResultSchema:Be,ResourceContentsSchema:Jt,TextResourceContentsSchema:Gt,BlobResourceContentsSchema:Vt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:Ct,ResourceTemplateSchema:zr,ListResourcesRequestSchema:Mr,ListResourcesResultSchema:jr,ListResourceTemplatesRequestSchema:rt,ListResourceTemplatesResultSchema:Kt,ResourceRequestParamsSchema:It,ReadResourceRequestParamsSchema:Nr,ReadResourceRequestSchema:$r,ReadResourceResultSchema:Dr,ResourceListChangedNotificationSchema:Lr,SubscribeRequestParamsSchema:Hr,SubscribeRequestSchema:Br,UnsubscribeRequestParamsSchema:Fr,UnsubscribeRequestSchema:Jr,ResourceUpdatedNotificationParamsSchema:Gr,ResourceUpdatedNotificationSchema:Vr,PromptArgumentSchema:Kr,PromptSchema:Wr,ListPromptsRequestSchema:Zr,ListPromptsResultSchema:Yr,GetPromptRequestParamsSchema:Xr,GetPromptRequestSchema:Qr,TextContentSchema:Tt,ImageContentSchema:kt,AudioContentSchema:At,ToolUseContentSchema:en,EmbeddedResourceSchema:nt,ResourceLinkSchema:tn,ContentBlockSchema:Te,PromptMessageSchema:Wt,GetPromptResultSchema:Zt,PromptListChangedNotificationSchema:Pt,ToolAnnotationsSchema:rn,ToolExecutionSchema:Yt,ToolSchema:Et,ListToolsRequestSchema:Xt,ListToolsResultSchema:Qt,CallToolResultSchema:er,CallToolRequestParamsSchema:ae,CallToolRequestSchema:nn,ToolListChangedNotificationSchema:ro,LoggingLevelSchema:tr,SetLevelRequestParamsSchema:on,SetLevelRequestSchema:sn,LoggingMessageNotificationParamsSchema:an,LoggingMessageNotificationSchema:cn,ModelHintSchema:dn,ModelPreferencesSchema:un,ToolChoiceSchema:ln,ToolResultContentSchema:no,SamplingContentSchema:pn,SamplingMessageContentBlockSchema:ot,SamplingMessageSchema:mn,CreateMessageRequestParamsSchema:hn,CreateMessageRequestSchema:fn,CreateMessageResultSchema:gn,CreateMessageResultWithToolsSchema:yn,BooleanSchemaSchema:Sn,StringSchemaSchema:_n,NumberSchemaSchema:wn,UntitledSingleSelectEnumSchemaSchema:Rn,TitledSingleSelectEnumSchemaSchema:bn,LegacyTitledEnumSchemaSchema:vn,SingleSelectEnumSchemaSchema:Cn,UntitledMultiSelectEnumSchemaSchema:xt,TitledMultiSelectEnumSchemaSchema:Ut,MultiSelectEnumSchemaSchema:oo,EnumSchemaSchema:io,PrimitiveSchemaDefinitionSchema:_e,ElicitRequestFormParamsSchema:we,ElicitRequestURLParamsSchema:In,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:so,ElicitationCompleteNotificationParamsSchema:ao,ElicitationCompleteNotificationSchema:co,ElicitResultSchema:uo,ResourceTemplateReferenceSchema:lo,PromptReferenceSchema:po,CompleteRequestParamsSchema:mo,CompleteRequestSchema:Tn,CompleteResultSchema:ho,RootSchema:fo,ListRootsRequestSchema:rr,ListRootsResultSchema:kn,RootsListChangedNotificationSchema:go,TaskCreationParamsSchema:yo,TaskStatusSchema:So,TaskSchema:it,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:_o,TaskStatusNotificationSchema:Ot,GetTaskRequestSchema:nr,GetTaskResultSchema:or,GetTaskPayloadRequestSchema:ir,GetTaskPayloadResultSchema:Si,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:qt,CancelTaskResultSchema:S.merge(it),ClientRequestSchema:A([et,D,Tn,sn,Qr,Zr,Mr,rt,$r,Br,Jr,nn,Xt,nr,ir,ge,qt]),ClientNotificationSchema:A([C,tt,Bt,go,Ot]),ClientResultSchema:A([k,gn,yn,uo,kn,or,Z,fe]),ServerRequestSchema:A([et,fn,so,rr,nr,ir,ge,qt]),ServerNotificationSchema:A([C,tt,cn,Vr,Lr,ro,Pt,Ot,co]),ServerResultSchema:A([k,qr,ho,Zt,Yr,jr,Kt,Dr,er,Qt,or,Z,fe]),CallToolResultWireSchema:q().superRefine((ce,Hf)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let _a of Cl)if(_a in ce){Hf.addIssue({code:"custom",message:`content is required when the body carries '${_a}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Rg).pipe(er)}}n(bg,"build$1");var vg;function rs(){return vg??=bg()}n(rs,"buildSchemas2025");function Il(e){return e.type!=="object"}n(Il,"isNonObjectJsonSchemaRoot");var Cg=new Set(["const","enum","default","examples"]),Ig=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ul(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(ul,"establishesNewBase");function Tg(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ul(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=dl(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&&ul(i.$id))return i;let a={},c=!1;for(let[u,p]of Object.entries(i))s?a[u]=o(p,!1):(u==="$ref"||u==="$dynamicRef")&&typeof p=="string"?a[u]=p==="#"?"#/properties/result":p.startsWith("#/")?`#/properties/result${p.slice(1)}`:p:u==="$recursiveRef"&&p==="#"&&r?c=!0:Cg.has(u)?a[u]=p:Ig.has(u)?a[u]=o(p,!0):a[u]=o(p,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(Tg,"wrapOutputSchemaForLegacy");var Tl={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},kl={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},kg={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},Lo;function Jo(){if(Lo)return Lo;let e=rs();return Lo={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}},Lo}n(Jo,"registryMaps");function Ag(){Jo()}n(Ag,"warmRegistryMaps2025");function Al(e){return Object.prototype.hasOwnProperty.call(Tl,e)}n(Al,"hasRequestMethod2025");function Pl(e){return Object.prototype.hasOwnProperty.call(kl,e)}n(Pl,"hasNotificationMethod2025");function Pg(e){return Object.prototype.hasOwnProperty.call(kg,e)}n(Pg,"hasResultMethod");function Eg(e){return Pg(e)?Jo().resultSchemas[e]:void 0}n(Eg,"getResultSchema");function xg(e){return Al(e)?Jo().requestSchemas[e]:void 0}n(xg,"getRequestSchema");function Ug(e){return Pl(e)?Jo().notificationSchemas[e]:void 0}n(Ug,"getNotificationSchema");var II=Object.keys(Tl),TI=Object.keys(kl);function Yi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Yi,"isPlainObject$4");function Ho(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(Ho,"triState$1");var ll={ok:!1,reason:"not-in-era"};function pl(e){return Yi(e)&&Yi(e.outputSchema)&&Il(e.outputSchema)}n(pl,"toolNeedsLegacyWrap");var ns={era:"2025-11-25",hasRequestMethod:Al,hasNotificationMethod:Pl,validateRequest:n((e,t)=>Ho(xg(e),t),"validateRequest"),validateResult:n((e,t)=>Ho(Eg(e),t),"validateResult"),validateNotification:n((e,t)=>Ho(Ug(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>ll,"validateInputRequest"),validateInputResponse:n(()=>ll,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=rs();return Ho(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=vl(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Il(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(Yi(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=>pl(o))?t:{...t,tools:r.map(o=>pl(o)?{...o,outputSchema:Tg(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function Og(){let e=Ri(()=>A([d(),b(),E(),bo(),T(d(),e),_(e)])),t=T(d(),e),r=A([d(),b().int()]),o=d(),i=A([d(),b().int()]),s=N(["user","assistant"]),a=N(["debug","info","notice","warning","error","critical","alert","emergency"]),c=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=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":p.optional()}),g=m({_meta:h.optional()}),S=g.extend({task:u.optional()}),y=m({_meta:h.optional()}),k=m({method:d(),params:y.loose().optional()}),w=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:N(["light","dark"]).optional()}),C=m({icons:_(w).optional()}),U=m({name:d(),title:d().optional()}),O=U.extend({...U.shape,...C.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),L=Pn(m({applyDefaults:E().optional()}),t),F=vo(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,Pn(m({form:L.optional(),url:t.optional()}),t.optional())),Q=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),J=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({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:E().optional()}).optional(),tasks:Q.optional(),extensions:T(d(),t).optional()}),Le=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:J.optional(),extensions:T(d(),t).optional()}),oe=m({progress:b(),total:z(b()),message:z(d())}),ze=m({...y.shape,...oe.shape,progressToken:r}),D=k.extend({method:f("notifications/progress"),params:ze}),Ee=y.extend({level:a,logger:d().optional(),data:q()}),qr=k.extend({method:f("notifications/message"),params:Ee}),Bt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),et=Bt.extend({text:d()}),bt=Bt.extend({blob:c}),Me=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:An.datetime({offset:!0}).optional()}),tt=m({...U.shape,...C.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:Me.optional(),_meta:z(M({}))}),Ft=m({...U.shape,...C.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:Me.optional(),_meta:z(M({}))}),He=k.extend({method:f("notifications/resources/list_changed"),params:y.optional()}),Be=y.extend({uri:d()}),Jt=k.extend({method:f("notifications/resources/updated"),params:Be}),Gt=m({name:d(),description:z(d()),required:z(E())}),vt=m({...U.shape,...C.shape,description:z(d()),arguments:z(_(Gt)),_meta:z(M({}))}),Vt=k.extend({method:f("notifications/prompts/list_changed"),params:y.optional()}),je=m({type:f("text"),text:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),xe=m({type:f("image"),data:c,mimeType:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),Ct=m({type:f("audio"),data:c,mimeType:d(),annotations:Me.optional(),_meta:T(d(),q()).optional()}),zr=m({type:f("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),Mr=m({type:f("resource"),resource:A([et,bt]),annotations:Me.optional(),_meta:T(d(),q()).optional()}),jr=tt.extend({type:f("resource_link")}),rt=A([je,xe,Ct,jr,Mr]),Kt=m({role:s,content:rt}),It=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Nr=k.extend({method:f("notifications/tools/list_changed"),params:y.optional()}),$r=m({name:d().optional()}),Dr=m({hints:_($r).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Lr=m({mode:N(["auto","required","none"]).optional()}),Hr=m({type:f("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Br=m({type:f("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:N(["email","uri","date","date-time"]).optional(),default:d().optional()}),Fr=m({type:N(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Jr=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Gr=m({type:f("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),Vr=m({type:f("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Kr=A([Jr,Gr]),Wr=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:f("string"),enum:_(d())}),default:_(d()).optional()}),Zr=m({type:f("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),Yr=A([Wr,Zr]),Xr=A([Vr,Kr,Yr]),Qr=A([Xr,Hr,Br,Fr]),Tt=S.extend({mode:f("form").optional(),message:d(),requestedSchema:m({type:f("object"),properties:T(d(),Qr),required:_(d()).optional()}).catchall(q())}),kt=m({type:f("ref/resource"),uri:d()}),At=m({type:f("ref/prompt"),name:d()}),en=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),nt=V.shape,tn=m({experimental:nt.experimental,sampling:nt.sampling,elicitation:nt.elicitation,roots:nt.roots,extensions:nt.extensions}),Te=Le.shape,Wt=m({experimental:Te.experimental,logging:Te.logging,completions:Te.completions,prompts:Te.prompts,resources:Te.resources,tools:Te.tools,extensions:Te.extensions}),Zt=M({progressToken:r.optional(),[sr]:d(),[En]:O.optional(),[cr]:tn,[xn]:a.optional()}),Pt=m({...U.shape,...C.shape,description:d().optional(),inputSchema:M({$schema:d().optional(),type:f("object")}),outputSchema:M({$schema:d().optional()}).optional(),annotations:It.optional(),_meta:T(d(),q()).optional()}),rn=m({type:f("tool_result"),toolUseId:d(),content:_(rt),structuredContent:q().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),Yt=A([je,xe,Ct,zr,rn]),Et=m({role:s,content:A([Yt,_(Yt)]),_meta:T(d(),q()).optional()}),Xt=d(),Qt=M({[ar]:O.optional().catch(void 0)}),er=Qt.optional();function ae(Z){return M({_meta:er,resultType:Xt.default("complete"),...Z})}n(ae,"wireResult");let nn=ae({}),ro=ae({nextCursor:o.optional()}),tr=ae({content:_(rt),structuredContent:q().optional(),isError:E().optional()}),on=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),tools:_(Pt),nextCursor:o.optional()}),sn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),prompts:_(vt),nextCursor:o.optional()}),an=ae({description:d().optional(),messages:_(Kt)}),cn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resources:_(tt),nextCursor:o.optional()}),dn=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resourceTemplates:_(Ft),nextCursor:o.optional()}),un=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),contents:_(A([et,bt]))}),ln=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),no=ae({ttlMs:b().int().min(0),cacheScope:N(["public","private"])}),pn=ae({ttlMs:b().int().min(0).catch(0),cacheScope:N(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Wt,instructions:d().optional()}),ot=m({messages:_(Et),modelPreferences:Dr.optional(),systemPrompt:d().optional(),includeContext:N(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Pt).optional(),toolChoice:Lr.optional()}),mn=m({method:f("sampling/createMessage"),params:ot}),hn=m({method:f("roots/list"),params:m({_meta:T(d(),q()).optional()}).optional()}),fn=m({...Et.shape,model:d(),stopReason:d().optional()}),gn=m({roots:_(en)}),yn=m({action:N(["accept","decline","cancel"]),content:T(d(),A([d(),b(),E(),_(d())])).optional()}),Sn=m({mode:f("url"),message:d(),url:d().url()}),_n=A([Tt,Sn]),wn=m({method:f("elicitation/create"),params:_n}),Rn=A([mn,hn,wn]),bn=A([fn,gn,yn]),vn=T(d(),Rn),Cn=T(d(),bn),xt=ae({inputRequests:vn.optional(),requestState:d().optional()}),Ut={inputResponses:Cn.optional(),requestState:d().optional()},oo=m({_meta:Zt,...Ut}),io=M({progressToken:r.optional()});function _e(Z,qt){return m({method:f(Z),params:m({_meta:Zt,...qt})})}n(_e,"wireRequest");function we(Z,qt){return m({method:f(Z),params:m({_meta:io.optional(),...qt}).optional()})}n(we,"dispatchRequest");let In={name:d(),arguments:T(d(),q()).optional(),...Ut},Ue={cursor:o.optional()},so=_e("tools/call",In),ao=_e("tools/list",Ue),co=_e("prompts/list",Ue),uo=_e("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Ut}),lo=_e("resources/list",Ue),po=_e("resources/templates/list",Ue),mo=_e("resources/read",{uri:d(),...Ut}),Tn={ref:A([At,kt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},ho=_e("completion/complete",Tn),fo=_e("server/discover",{}),rr=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:_(d()).optional()}),kn={notifications:rr},go=_e("subscriptions/listen",kn),yo=Qt.extend({"io.modelcontextprotocol/subscriptionId":i}),So=M({_meta:yo,resultType:Xt.default("complete")}),it={"tools/call":we("tools/call",In),"tools/list":we("tools/list",Ue),"prompts/get":we("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":we("prompts/list",Ue),"resources/list":we("resources/list",Ue),"resources/templates/list":we("resources/templates/list",Ue),"resources/read":we("resources/read",{uri:d()}),"completion/complete":we("completion/complete",Tn),"server/discover":we("server/discover",{}),"subscriptions/listen":we("subscriptions/listen",kn)};function fe(Z){return M({_meta:er,...Z})}n(fe,"liftedResult");let _o={"tools/call":fe({content:_(rt),structuredContent:q().optional(),isError:E().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),tools:_(Pt),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Kt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),prompts:_(vt),nextCursor:o.optional()}),"resources/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resources:_(tt),nextCursor:o.optional()}),"resources/templates/list":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),resourceTemplates:_(Ft),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:N(["public","private"]),contents:_(A([et,bt]))}),"completion/complete":fe({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":fe({ttlMs:b().int().min(0).catch(0),cacheScope:N(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Wt,instructions:d().optional()}),"subscriptions/listen":fe({})},Ot=M({"io.modelcontextprotocol/subscriptionId":i.optional()}),nr=m({method:f("notifications/subscriptions/acknowledged"),params:m({_meta:Ot.optional(),notifications:rr})}),or=m({_meta:Ot.optional(),requestId:i,reason:d().optional()}),ir=m({method:f("notifications/cancelled"),params:or}),Si={"notifications/cancelled":ir,"notifications/progress":D,"notifications/message":qr,"notifications/resources/updated":Jt,"notifications/resources/list_changed":He,"notifications/tools/list_changed":Nr,"notifications/prompts/list_changed":Vt,"notifications/subscriptions/acknowledged":nr},ge=n(Z=>m({jsonrpc:f("2.0"),id:A([d(),b().int()]),result:Z}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:i,RoleSchema:s,LoggingLevelSchema:a,TaskMetadataSchema:u,RelatedTaskMetadataSchema:p,RequestMetaSchema:h,BaseRequestParamsSchema:g,TaskAugmentedRequestParamsSchema:S,NotificationsParamsSchema:y,NotificationSchema:k,IconSchema:w,IconsSchema:C,BaseMetadataSchema:U,ImplementationSchema:O,ClientTasksCapabilitySchema:Q,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:V,ServerCapabilitiesSchema:Le,ProgressSchema:oe,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:Ee,LoggingMessageNotificationSchema:qr,ResourceContentsSchema:Bt,TextResourceContentsSchema:et,BlobResourceContentsSchema:bt,AnnotationsSchema:Me,ResourceSchema:tt,ResourceTemplateSchema:Ft,ResourceListChangedNotificationSchema:He,ResourceUpdatedNotificationParamsSchema:Be,ResourceUpdatedNotificationSchema:Jt,PromptArgumentSchema:Gt,PromptSchema:vt,PromptListChangedNotificationSchema:Vt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:Ct,ToolUseContentSchema:zr,EmbeddedResourceSchema:Mr,ResourceLinkSchema:jr,ContentBlockSchema:rt,PromptMessageSchema:Kt,ToolAnnotationsSchema:It,ToolListChangedNotificationSchema:Nr,ModelHintSchema:$r,ModelPreferencesSchema:Dr,ToolChoiceSchema:Lr,BooleanSchemaSchema:Hr,StringSchemaSchema:Br,NumberSchemaSchema:Fr,UntitledSingleSelectEnumSchemaSchema:Jr,TitledSingleSelectEnumSchemaSchema:Gr,LegacyTitledEnumSchemaSchema:Vr,SingleSelectEnumSchemaSchema:Kr,UntitledMultiSelectEnumSchemaSchema:Wr,TitledMultiSelectEnumSchemaSchema:Zr,MultiSelectEnumSchemaSchema:Yr,EnumSchemaSchema:Xr,PrimitiveSchemaDefinitionSchema:Qr,ElicitRequestFormParamsSchema:Tt,ResourceTemplateReferenceSchema:kt,PromptReferenceSchema:At,RootSchema:en,ClientCapabilities2026Schema:tn,ServerCapabilities2026Schema:Wt,RequestMetaEnvelopeSchema:Zt,ToolSchema:Pt,ToolResultContentSchema:rn,SamplingMessageContentBlockSchema:Yt,SamplingMessageSchema:Et,ResultTypeSchema:Xt,ResultMetaSchema:Qt,ResultSchema:nn,PaginatedResultSchema:ro,CallToolResultSchema:tr,ListToolsResultSchema:on,ListPromptsResultSchema:sn,GetPromptResultSchema:an,ListResourcesResultSchema:cn,ListResourceTemplatesResultSchema:dn,ReadResourceResultSchema:un,CompleteResultSchema:ln,CacheableResultSchema:no,DiscoverResultSchema:pn,CreateMessageRequestParamsSchema:ot,CreateMessageRequestSchema:mn,ListRootsRequestSchema:hn,CreateMessageResultSchema:fn,ListRootsResultSchema:gn,ElicitResultSchema:yn,ElicitRequestURLParamsSchema:Sn,ElicitRequestParamsSchema:_n,ElicitRequestSchema:wn,InputRequestSchema:Rn,InputResponseSchema:bn,InputRequestsSchema:vn,InputResponsesSchema:Cn,InputRequiredResultSchema:xt,InputResponseRequestParamsSchema:oo,CallToolRequestSchema:so,ListToolsRequestSchema:ao,ListPromptsRequestSchema:co,GetPromptRequestSchema:uo,ListResourcesRequestSchema:lo,ListResourceTemplatesRequestSchema:po,ReadResourceRequestSchema:mo,CompleteRequestSchema:ho,DiscoverRequestSchema:fo,SubscriptionFilterSchema:rr,SubscriptionsListenRequestSchema:go,SubscriptionsListenResultMetaSchema:yo,SubscriptionsListenResultSchema:So,dispatchRequestSchemas:it,dispatchResultSchemas:_o,NotificationMetaSchema:Ot,SubscriptionsAcknowledgedNotificationSchema:nr,CancelledNotificationParamsSchema:or,CancelledNotificationSchema:ir,notificationSchemas2026:Si,JSONRPCResultResponseSchema:ge(nn),CallToolResultResponseSchema:ge(A([tr,xt])),ListToolsResultResponseSchema:ge(on),ListPromptsResultResponseSchema:ge(sn),GetPromptResultResponseSchema:ge(A([an,xt])),ListResourcesResultResponseSchema:ge(cn),ListResourceTemplatesResultResponseSchema:ge(dn),ReadResourceResultResponseSchema:ge(A([un,xt])),CompleteResultResponseSchema:ge(ln),DiscoverResultResponseSchema:ge(pn)}}n(Og,"build");var qg;function lt(){return qg??=Og()}n(lt,"buildSchemas2026");var zg=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Mg(e){return zg.includes(e)}n(Mg,"isCacheableResultMethod");var os=Symbol("modelcontextprotocol.resultCacheHintFallback");function jg(e){return e[os]}n(jg,"cacheHintFallbackOf");function El(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(El,"isValidCacheTtlMs");function xl(e){return e==="public"||e==="private"}n(xl,"isValidCacheScope");var P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),se=class Ul extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return be(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 be(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",$t(this,new.target)}static fromError(t,r,o){if(t===P.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new Go(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 Ol(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 zl({requiredCapabilities:i.requiredCapabilities},r)}return new Ul(t,r,o)}},Ol=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}},Go=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}},zl=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}},Ng=0,$g="private",Dg=["tools/call","prompts/get","resources/read"];function Lg(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Dg.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(Lg,"stampResultType");function Hg(e,t){let r=jg(t);if(t.resultType!=="complete"||!Mg(e))return r===void 0?t:Vg(t);let o=t,i=El(o.ttlMs)?o.ttlMs:Jg(r),s=xl(o.cacheScope)?o.cacheScope:Gg(r),a={...o,ttlMs:i,cacheScope:s};return delete a[os],a}n(Hg,"fillCacheFields");function Bg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Bg,"isPlainObject$3");function Fg(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ar]:t}}:!Bg(r)||r[ar]!==void 0?e:{...e,_meta:{...r,[ar]:t}}}n(Fg,"stampServerInfoMeta");function Jg(e){return e!==void 0&&El(e.ttlMs)?e.ttlMs:Ng}n(Jg,"resolveTtlMs");function Gg(e){return e!==void 0&&xl(e.cacheScope)?e.cacheScope:$g}n(Gg,"resolveCacheScope");function Vg(e){let t={...e};return delete t[os],t}n(Vg,"stripCacheHintFallback");var Kg=["elicitation/create","sampling/createMessage","roots/list"],Bo;function is(){if(Bo)return Bo;let e=lt();return Bo={request:{"elicitation/create":m({method:f("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:f("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:f("roots/list"),params:M({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Bo}n(is,"inputSchemaMaps");function Wg(){is()}n(Wg,"warmInputSchemaMaps2026");function Ml(e){return Kg.includes(e)}n(Ml,"isInputRequestMethod2026");function Ji(e){return Ml(e)?is().request[e]:void 0}n(Ji,"getInputRequestSchema2026");function Zg(e){return Ml(e)?is().response[e]:void 0}n(Zg,"getInputResponseSchema2026");var ss={"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},jl={"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 Nl(e){return Object.prototype.hasOwnProperty.call(ss,e)}n(Nl,"hasRequestMethod2026");function $l(e){return Object.prototype.hasOwnProperty.call(jl,e)}n($l,"hasNotificationMethod2026");function Yg(e){return Object.prototype.hasOwnProperty.call(ss,e)}n(Yg,"hasResultMethod2026");function Xg(e){return Nl(e)?lt().dispatchRequestSchemas[e]:void 0}n(Xg,"getRequestSchema2026");function Qg(e){return Yg(e)?lt().dispatchResultSchemas[e]:void 0}n(Qg,"getResultSchema2026");function ey(e){return $l(e)?lt().notificationSchemas2026[e]:void 0}n(ey,"getNotificationSchema2026");var kI=Object.keys(ss),AI=Object.keys(jl);function Ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ln,"isPlainObject$2");function $n(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($n,"triState");var ty={ok:!1,reason:"not-in-era"},ry=[sr,cr];function ny(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(c=>Ln(c)&&"execution"in c)&&(i().tools=s.map(c=>{if(!Ln(c)||!("execution"in c))return c;let u={...c};return delete u.execution,u}));let a=t.capabilities;if(Ln(a)&&"tasks"in a){let c={...a};delete c.tasks,i().capabilities=c}return r}n(ny,"enforceDeletedFields");var as={era:"2026-07-28",hasRequestMethod:Nl,hasNotificationMethod:$l,hasInputRequestMethod:n(e=>Ji(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>$n(Xg(e),t),"validateRequest"),validateResult:n((e,t)=>$n(Qg(e),t),"validateResult"),validateNotification:n((e,t)=>$n(ey(e),t),"validateNotification"),validateInputRequest:n((e,t)=>$n(Ji(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>$n(Zg(e),t),"validateInputResponse"),samplingResultVariant:n(()=>ty,"samplingResultVariant"),outboundEnvelope(e){return{[sr]:e.protocolVersion,[En]:e.clientInfo,[cr]:e.clientCapabilities,...e.logLevel!==void 0&&{[xn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of ry)o in e||t.push({key:o,problem:"missing"});let r=lt().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(a=>a.key===s&&a.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>vl(e),"projectCallToolResult"),inputRequestSchema:Ji,decodeResult(e,t){if(!Ln(t))return{kind:"invalid",error:new te(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new te(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 te(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Ln(a)?a:{},u=t.requestState;return Object.keys(c).length===0&&typeof u!="string"?{kind:"invalid",error:new te(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:c,...typeof u=="string"&&{requestState:u}}}if(r!=="complete")return{kind:"invalid",error:new te(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Dl(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let a=i.safeParse(t);if(!a.success)return{kind:"invalid",error:new te(ie.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return Fg(Hg(e,Lg(e,ny(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=lt().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("; ")}`}},Fo;function Dl(){if(Fo)return Fo;let e=lt();return Fo={"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},Fo}n(Dl,"getWireResultSchemas");function oy(){Dl()}n(oy,"warmWireResultSchemas2026");var cs="2026-07-28";function Bn(e){return e!==void 0&&bl(e)?as:ns}n(Bn,"codecForVersion");function ml(e){return e.revision!==void 0?Bn(e.revision).era:e.era==="modern"?as.era:ns.era}n(ml,"classifiedWireEra");function Gi(e){return Ll.some(t=>t.hasRequestMethod(e))}n(Gi,"isSpecRequestMethod");function Vi(e){return Ll.some(t=>t.hasNotificationMethod(e))}n(Vi,"isSpecNotificationMethod");var Ll=[ns,as],iy=al({AnnotationsSchema:n(()=>yc,"AnnotationsSchema"),AudioContentSchema:n(()=>Zc,"AudioContentSchema"),BaseMetadataSchema:n(()=>Wa,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>za,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>fc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Ai,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>ld,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>pd,"CallToolRequestSchema"),CallToolResultSchema:n(()=>dd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>iu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>su,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Ja,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Ga,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Qa,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>cu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>au,"ClientRequestSchema"),ClientResultSchema:n(()=>du,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Ya,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>ud,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Dd,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>Ld,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Hd,"CompleteResultSchema"),ContentBlockSchema:n(()=>ed,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Td,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>kd,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Ad,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>Pd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Zd,"CreateTaskResultSchema"),CursorSchema:n(()=>xa,"CursorSchema"),DiscoverRequestSchema:n(()=>ic,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Ti,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>ko,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Od,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>qd,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Ao,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>jd,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>zd,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>Md,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Xc,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Fa,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Ud,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Gc,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Vc,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>rd,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>tu,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>ru,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Qd,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>eu,"GetTaskResultSchema"),IconSchema:n(()=>Va,"IconSchema"),IconsSchema:n(()=>Ka,"IconsSchema"),ImageContentSchema:n(()=>Wc,"ImageContentSchema"),ImplementationSchema:n(()=>Za,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>ec,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>tc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>nc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>oc,"InitializedNotificationSchema"),JSONArraySchema:n(()=>Pa,"JSONArraySchema"),JSONObjectSchema:n(()=>Aa,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Un,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>Ii,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>vi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Mt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Ba,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Ci,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>ka,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>xi,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>ki,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Fc,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Jc,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>bc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>vc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>wc,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Rc,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Fd,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Jd,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>nu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>ou,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>ad,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>cd,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>hd,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>yd,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>Sd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>_d,"ModelHintSchema"),ModelPreferencesSchema:n(()=>wd,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>xd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>$a,"NotificationSchema"),NotificationsParamsSchema:n(()=>Na,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>To,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>uc,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>lc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>pc,"PaginatedResultSchema"),PingRequestSchema:n(()=>sc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>qi,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>cc,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>dc,"ProgressNotificationSchema"),ProgressSchema:n(()=>ac,"ProgressSchema"),ProgressTokenSchema:n(()=>Ea,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Hc,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>nd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>td,"PromptMessageSchema"),PromptReferenceSchema:n(()=>$d,"PromptReferenceSchema"),PromptSchema:n(()=>Bc,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Ic,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Tc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>kc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Oa,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Ha,"RequestIdSchema"),RequestMetaSchema:n(()=>qa,"RequestMetaSchema"),RequestSchema:n(()=>ja,"RequestSchema"),ResourceContentsSchema:n(()=>mc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Qc,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Ac,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Cc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>Sc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Nd,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>_c,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Dc,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>Lc,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Da,"ResultMetaObjectSchema"),ResultSchema:n(()=>La,"ResultSchema"),RoleSchema:n(()=>gc,"RoleSchema"),RootSchema:n(()=>Bd,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Gd,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>vd,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Cd,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Id,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>rc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>lu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>uu,"ServerRequestSchema"),ServerResultSchema:n(()=>pu,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Xa,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>fd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>gd,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Ed,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Io,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>Pc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Ec,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Oc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>Mc,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>jc,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>qc,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>zc,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Nc,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>$c,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>Ma,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Vd,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>Ua,"TaskMetadataSchema"),TaskSchema:n(()=>Wd,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Yd,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Xd,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>Kd,"TaskStatusSchema"),TextContentSchema:n(()=>Kc,"TextContentSchema"),TextResourceContentsSchema:n(()=>hc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Oi,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Ei,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>od,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Rd,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>id,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>md,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>bd,"ToolResultContentSchema"),ToolSchema:n(()=>sd,"ToolSchema"),ToolUseContentSchema:n(()=>Yc,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>xc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Uc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ui,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Pi,"UntitledSingleSelectEnumSchemaSchema")});var Hl=n(e=>Mt.safeParse(e).success,"isJSONRPCRequest"),Bl=n(e=>vi.safeParse(e).success,"isJSONRPCNotification"),Xi=n(e=>Ci.safeParse(e).success,"isJSONRPCResultResponse"),Fl=n(e=>Un.safeParse(e).success,"isJSONRPCErrorResponse");var Hn=-32020,PI=[{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:[Hn,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:[Hn],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:[Hn],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."}],EI={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Hn]:400};function ds(e,t){return Ca(e,t)}n(ds,"parseSchema");function Dn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Dn,"shapeKeys");function Qi(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(Qi,"isStandardSchema");var hl=!1,es="draft-2020-12";function sy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:es});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().");hl||(hl=!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=_i(e,{target:es,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:Jl(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(sy,"standardSchemaToJsonSchema");function Jl(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"||Jl(o)))}return!1}n(Jl,"isProvablyObjectShapedRoot");function ay(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(ay,"formatIssue");async function Ki(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>ay(o)).join(", ")}:{success:!0,data:r.value}}n(Ki,"validateStandardSchema");function cy(e){let t=_i(e,{target:es,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(cy,"zodEmittedPattern");var dy=/\\\.\\d\{(\d+)\}/;function uy(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=>An.datetime({local:o,offset:i,precision:s}))))}n(uy,"datetimeReferenceSchemas");function ly(e,t){let r;switch(e){case"email":r=[Ia()];break;case"uri":r=[Ta()];break;case"date":r=[An.date()];break;case"date-time":r=uy(t);break}return new Set(r.map(o=>cy(o)).filter(o=>o!==void 0))}n(ly,"referencePatternsForFormat");function py(e,t,r){return r!=="zod"?!0:ly(e,t).has(t)}n(py,"isLibraryFormatPattern");function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Fn,"isJsonObject");function my(e){try{return sy(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(my,"convertStandardElicitationSchema");var hy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function us(e){return hy.has(e)||e.startsWith("x-")}n(us,"isAnnotationOnlyJsonSchemaKeyword");var fy=new Set(["$schema",...Object.keys(ko.shape.requestedSchema.shape)]),fl={string:Dn([Io,Pi,Ei,xi]),number:Dn([To]),integer:Dn([To]),boolean:Dn([Ai]),array:Dn([Ui,Oi])},gy=new Set(Io.shape.format.unwrap().options);function yy(e,t,r,o){if(!Fn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(fl,e.type)?fl[e.type]:void 0;if(i===void 0)return e;let s={};for(let[a,c]of Object.entries(e))i.has(a)||us(a)?s[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?gy.has(e.format)?(typeof c!="string"||!py(e.format,c,r))&&o.push(`${t}.${a}`):s[a]=c:o.push(`${t}.${a}`);return s}n(yy,"walkProperty");function Sy(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Fn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([a,c])=>[a,yy(c,`properties.${a}`,t,o)])):fy.has(i)?r[i]=s:us(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(Sy,"walkRequestedSchema");function _y(e,t){if(!Fn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!ds(qi,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(_y,"describeUnsupportedProperties");function ts(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>ts(o,t[i],`${r}[${i}]`)):!Fn(e)||!Fn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?ts(i,t[o],s):us(o)?[]:[s]})}n(ts,"findDroppedConstraintPaths");function wy(e){if(!Qi(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Sy(my(e.requestedSchema),t),o=ds(ko.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): ${_y(r,o.error.message)}`);let i=ts(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(a=>!Object.prototype.hasOwnProperty.call(o.data.properties,a));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(wy,"normalizeElicitInputParams");function Ry(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(Ry,"buildInputRequired");var xI=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(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 by=["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"],vy={IdJagTokenExchangeResponseSchema:zi,OAuthClientInformationFullSchema:jt,OAuthClientInformationSchema:On,OAuthClientMetadataSchema:hu,OAuthClientRegistrationErrorSchema:fu,OAuthErrorResponseSchema:Po,OAuthMetadataSchema:lr,OAuthProtectedResourceMetadataSchema:ur,OAuthTokenRevocationRequestSchema:gu,OAuthTokensSchema:st,OpenIdProviderDiscoveryMetadataSchema:pr,OpenIdProviderMetadataSchema:mu},Gl={},Vl={};function Kl(e,t){let r=e.slice(0,-6);Gl[r]=t,Vl[r]=o=>t.safeParse(o).success}n(Kl,"register");for(let e of by)Kl(e,iy[e]);for(let[e,t]of Object.entries(vy))Kl(e,t);var Cy=Object.freeze(Gl),Iy=Object.freeze(Vl);function Ty(e){switch(e){case"initialize":case"notifications/initialized":return Bn(void 0);case"server/discover":return Bn(cs);default:return}}n(Ty,"bootstrapOutboundCodec");var Wl=6e4,ky=[sr,En,cr,xn],Ay=["inputResponses","requestState"];function gl(e,t){let r=e.params;if(!Wi(r))return{message:e,lifted:{}};let o=r._meta,i=Wi(o)?ky.filter(u=>u in o):[],s=t==="request"?Ay.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let a={},c={...r};if(i.length>0&&Wi(o)){let u={},p={...o};for(let h of i)u[h]=o[h],delete p[h];a.envelope=u,Object.keys(p).length>0?c._meta=p:delete c._meta}for(let u of s)u==="inputResponses"&&(a.inputResponses=c[u]),u==="requestState"&&(a.requestState=c[u]),delete c[u];return{message:{...e,params:c},lifted:a}}n(gl,"liftWireOnlyMaterial");function yl(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(yl,"codecResultValidator");function Zl(e){return()=>e}n(Zl,"requestStateAccessor");var Py=Zl(void 0),Ey,xy=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{Ey=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??bi,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 te(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 te(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),Xi(i)||Fl(i)?this._onresponse(i):Hl(i)?this._onrequest(i,s):Bl(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 te(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}=gl(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=ml(t.classification);if(a!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${o.era}`));return}}if(Vi(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(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:o}=gl(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,a=n((w,C,U)=>{let O={jsonrpc:"2.0",id:r.id,error:{code:w,message:C,...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=ml(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 C=t.classification.revision??w;a(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${C}`,{supported:this._supportedProtocolVersions,requested:C});return}}if(Gi(r.method)&&!i.hasRequestMethod(r.method)){a(P.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(P.MethodNotFound,"Method not found");return}let u=i.checkInboundEnvelope(o);if(u!==void 0){a(P.InvalidParams,u);return}let p=n((w,C)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...C,relatedRequestId:r.id}),"sendNotification"),h=n((w,C,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,C,{...U,relatedRequestId:r.id}),"sendRequest"),g=new AbortController;this._requestHandlerAbortControllers.set(r.id,g);let S=o.inputResponses===void 0?void 0:Uy(o.inputResponses),y={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...S!==void 0&&{inputResponses:S.accepted},...S!==void 0&&S.droppedKeys.length>0&&{droppedInputResponseKeys:S.droppedKeys},requestState:o.requestState===void 0?Py:Zl(o.requestState),signal:g.signal,send:n(((w,C,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),Qi(C))return h(w,C,U);let L=yl(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,C)}),"send"),notify:p},http:t?.authInfo?{authInfo:t.authInfo}:void 0},k=this.buildContext(y,t);Promise.resolve().then(()=>c(r,k)).then(async w=>{if(g.signal.aborted)return;let C;try{C=i.encodeResult(r.method,w,this._outboundServerInfo())}catch(O){this._onerror(new Error(`Failed to encode result for ${r.method}: ${O}`)),a(P.InternalError,"Internal error");return}let U={result:C,jsonrpc:"2.0",id:r.id};await s?.send(U)},async w=>{if(g.signal.aborted)return;let C=Number.isSafeInteger(w.code)?w.code:P.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:i.encodeErrorCode(C),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)===g&&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),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);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),Xi(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),Qi(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=yl(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 Bn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ty(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Gi(t)&&!e.hasRequestMethod(t))throw new te(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:a,headers:c}=o??{},u=Date.now(),p,h;return new Promise((g,S)=>{let y=n(J=>{S(J)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){y(J);return}if(o?.signal?.aborted){let J=o.signal.reason;throw J instanceof te?J:new te(ie.RequestTimeout,String(J))}let k=e.era===cs&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;h=w;let C={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),C.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let U=this._envelopeOutbound(C),O=!1,L=n(J=>{O||(this._progressHandlers.delete(w),k===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(J)}}),{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),S(J instanceof te?J:new te(ie.RequestTimeout,String(J))))},"cancel");this._responseHandlers.set(w,J=>{if(o?.signal?.aborted)return;if(O=!0,J instanceof Error)return S(J);let V;try{V=e.decodeResult(t.method,J.result)}catch(oe){return S(oe instanceof Error?oe:new Error(String(oe)))}if(V.kind==="invalid")return S(V.error);if(V.kind==="input_required"){if(o?.allowInputRequired===!0)return g(Oy(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((ze,D)=>this._requestWithSchemaViaCodec(e,ze===void 0?{method:t.method}:{method:t.method,params:ze},r,D),"retry")};return g(this._resolveNonCompleteResult(V,oe))}let Le=V.result;Ki(r,Le).then(oe=>{oe.success?g(oe.data):S(new te(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},S)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??Wl,Q=n(()=>L(new te(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,Q,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a,headers:c,requestSignal:k?.signal}).catch(J=>{this._progressHandlers.delete(w),S(J)})}).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 te(ie.NotConnected,"Not connected");if(Vi(t.method)&&!e.hasNotificationMethod(t.method))throw new te(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(!Gi(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,i);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,i)),!c.ok)throw c.reason==="not-in-era"?new se(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let a=await Ki(t.params,{...i.params});if(!a.success)throw new se(P.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.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(!Vi(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 Ki(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 Wi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Wi,"isPlainObject$1");function Sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Sl,"isPlainObject");function Uy(e){let t={},r=[];if(!Sl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!Sl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(Uy,"partitionInputResponses");function Oy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(Oy,"manualInputRequiredValue");var qy=sl((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(c){if(!c)throw new TypeError("argument string is required");var u=typeof c=="object"?s(c):c;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 g=new a(h.toLowerCase());if(p!==-1){var S,y,k;for(t.lastIndex=p;y=t.exec(u);){if(y.index!==p)throw new TypeError("invalid parameter format");p+=y[0].length,S=y[1].toLowerCase(),k=y[2],k.charCodeAt(0)===34&&(k=k.slice(1,-1),k.indexOf("\\")!==-1&&(k=k.replace(r,"$1"))),g.parameters[S]=k}if(p!==u.length)throw new TypeError("invalid parameter format")}return g}n(i,"parse");function s(c){var u;if(typeof c.getHeader=="function"?u=c.getHeader("content-type"):typeof c.headers=="object"&&(u=c.headers&&c.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}n(s,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}n(a,"ContentType")})),UI=cl(qy(),1);var zy=10*1024*1024;function ls(){rs(),lt(),Ag(),Wg(),oy()}n(ls,"preloadSchemas");var FI=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 My=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ny=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,$y=/^(?=.{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,Dy=/^(?:[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,Ly=/^(?:(?:[^\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,Hy=/^(?:(?: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,By=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Fy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Jy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Gy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Vy=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"),Ky=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Wy=/^((([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,Zy=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 Ne(e){return e.test.bind(e)}n(Ne,"bind");var JI={date:Yl,time:Xl.bind(void 0,!1),"date-time":Qy,duration:Zy,uri:rS,"uri-reference":Ne(Dy),"uri-template":Ne(Ly),url:Ne(Hy),email:Vy,hostname:Ne($y),ipv4:Ne(Ky),ipv6:Ne(Wy),regex:oS,uuid:Ne(By),"json-pointer":Ne(Fy),"json-pointer-uri-fragment":Ne(Jy),"relative-json-pointer":Ne(Gy)};function Yy(e){return e%4===0&&(e%100!==0||e%400===0)}n(Yy,"isLeapYear");function Yl(e){let t=e.match(My);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&Yy(r)?29:jy[o])}n(Yl,"date");function Xl(e,t){let r=t.match(Ny);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||a)}n(Xl,"time");var Xy=/t|\s/i;function Qy(e){let t=e.split(Xy);return t.length==2&&Yl(t[0])&&Xl(!0,t[1])}n(Qy,"date_time");var eS=/\/|:/,tS=/^(?:[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 rS(e){return eS.test(e)&&tS.test(e)}n(rS,"uri");var nS=/[^\\]\\Z/;function oS(e){if(nS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(oS,"regex");ls();var Ql=!1;var ps;ps=globalThis.crypto;async function sS(e){return(await ps).getRandomValues(new Uint8Array(e))}n(sS,"getRandomValues");async function aS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await sS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(aS,"random");async function cS(e){return await aS(e)}n(cS,"generateVerifier");async function dS(e){let t=await(await ps).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 ms(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await cS(e),r=await dS(t);return{code_verifier:t,code_challenge:r}}n(ms,"pkceChallenge");var Jn=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e){super(e),this.name=new.target.name,$t(this,new.target)}},Ss=class extends Jn{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}},uS=class extends Jn{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}},np=class extends Jn{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}},hs=class extends Jn{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}},UT=class extends Jn{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 ep(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):op(e.issuer,t)?e:void 0}n(ep,"discardIfIssuerMismatch");function op(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(op,"issuersMatch");var OT=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",$t(this,new.target)}};function ip(e){return e?.authorization_response_iss_parameter_supported===!0}n(ip,"isIssParameterSupported");function sp({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Ss("authorization_response",t,void 0);return}if(e!==t)throw new Ss("authorization_response",t,e)}}n(sp,"validateAuthorizationResponseIssuer");function lS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(lS,"isClientAuthMethod");var fs="code",gs="S256";function pS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&lS(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(pS,"selectClientAuthMethod");function mS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":hS(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(mS,"applyClientAuthentication");function hS(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(hS,"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 ap(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(ap,"isLoopbackHost");function yS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!ap(t.hostname))throw new np(t.href);return t}n(yS,"assertSecureTokenEndpoint");function SS(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||ap(r.hostname))return"native"}return"web"}n(SS,"deriveApplicationType");function _S(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??SS(t.redirect_uris)}}n(_S,"resolveClientMetadata");async function tp(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Po.parse(JSON.parse(r));return pt.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pt(ue.ServerError,i)}}n(tp,"parseErrorResponse");async function _s(e,t){try{return await ys(e,t)}catch(r){if(r instanceof pt){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ys(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await ys(e,t)}throw r}}n(_s,"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 ys(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:u}){let p=_S(e),h=await e.discoveryState?.(),g,S,y,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(S=h.authorizationServerUrl,g=h.resourceMetadata,y=h.authorizationServerMetadata??await lp(S,{fetchFn:a,skipIssuerValidation:c}),!g)try{g=await dp(t,{resourceMetadataUrl:w},a)}catch(D){if(D instanceof TypeError)throw D}(y!==h.authorizationServerMetadata||g!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(S),resourceMetadataUrl:w?.toString(),resourceMetadata:g,authorizationServerMetadata:y})}else{let D=await TS(t,{resourceMetadataUrl:w,fetchFn:a,skipIssuerMetadataValidation:c});S=D.authorizationServerUrl,y=D.authorizationServerMetadata,g=D.resourceMetadata,k={authorizationServerUrl:String(S),resourceMetadataUrl:w?.toString(),resourceMetadata:g,authorizationServerMetadata:y}}let C=y?.issuer??String(S),U={issuer:C};if(await e.saveAuthorizationServerUrl?.(C),r!==void 0){let D=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if(D===void 0){if(e.saveDiscoveryState!==void 0)throw new hs("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",C);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(!op(D,C))throw new hs(D,C)}k&&await e.saveDiscoveryState?.(k);let O=await RS(t,e,g);O&&await e.saveResourceUrl?.(String(O));let L=wS({requestedScope:i,resourceMetadata:g,authServerMetadata:y,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),Q=ep(F,C,{canPersistStamp:e.saveClientInformation!==void 0});if(Q===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new hs(F.issuer,C);if(Q&&Q.issuer===void 0&&(Q={...Q,issuer:C},await e.saveClientInformation?.(Q,U)),!Q){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let D=y?.client_id_metadata_document_supported===!0,Ee=e.clientMetadataUrl;if(Ee&&!ws(Ee))throw new pt(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ee}`);if(D&&Ee)Q={client_id:Ee,issuer:C},await e.saveClientInformation?.(Q,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");Q={...await xS(S,{metadata:y,clientMetadata:p,scope:L,fetchFn:a}),issuer:C},await e.saveClientInformation(Q,U)}}let J=!e.redirectUrl;if(r!==void 0||J){r!==void 0&&sp({iss:o,expectedIssuer:y?.issuer,issParameterSupported:ip(y)});let D=await ES(e,S,{metadata:y,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:a});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}let V=ep(await e.tokens(U),C);if(V&&V.issuer===void 0&&(V={...V,issuer:C},await e.saveTokens(V,U)),V?.refresh_token&&!u)try{let D=await PS(S,{metadata:y,clientInformation:Q,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}catch(D){if(D instanceof np||!(!(D instanceof pt)||D.code===ue.ServerError))throw D}let Le=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:ze}=await kS(S,{metadata:y,clientInformation:Q,state:Le,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(ze),await e.redirectToAuthorization(oe),"REDIRECT"}n(ys,"authInternal");function ws(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(ws,"isHttpsUrl");async function RS(e,t,r){let o=wl(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Rl({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(RS,"selectResourceURL");function cp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=Vo(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let a=Vo(e,"scope")||void 0,c=Vo(e,"error")||void 0,u=Vo(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:a,error:c,errorDescription:u}}n(cp,"extractWWWAuthenticateParams");function Vo(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(Vo,"extractFieldFromWwwAuth");async function dp(e,t,r=fetch){let o=await CS(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 ur.parse(await o.json())}n(dp,"discoverOAuthProtectedResourceMetadata");async function up(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!Ql)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(up,"fetchWithCorsRetry");function bS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(bS,"buildWellKnownPath");async function rp(e,t,r=fetch){return await up(e,{"MCP-Protocol-Version":t},r)}n(rp,"tryMetadataDiscovery");function vS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(vS,"shouldAttemptFallback");async function CS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??Co,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let u=bS(t,i.pathname);a=new URL(u,o?.metadataServerUrl??i),a.search=i.search}let c=await rp(a,s,r);return!o?.metadataUrl&&vS(c,i.pathname)&&(c=await rp(new URL(`/.well-known/${t}`,i),s,r)),c}n(CS,"discoverMetadataWithFallback");function IS(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(IS,"buildDiscoveryUrls");async function lp(e,{fetchFn:t=fetch,protocolVersion:r=Co,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=IS(e);for(let{url:a,type:c}of s){let u=await up(a,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 ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let p=c==="oauth"?lr.parse(await u.json()):pr.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 Ss("metadata",h,p.issuer)}return p}}n(lp,"discoverAuthorizationServerMetadata");async function TS(e,t){let r,o;try{r=await dp(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 lp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(TS,"discoverOAuthServerInfo");async function kS(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(fs))throw new Error(`Incompatible auth server: does not support response type ${fs}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(gs))throw new Error(`Incompatible auth server: does not support code challenge method ${gs}`)}else c=new URL("/authorize",e);let u=await ms(),p=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",fs),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",gs),c.searchParams.set("redirect_uri",String(o)),s&&c.searchParams.set("state",s),i&&c.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:p}}n(kS,"startAuthorization");function AS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(AS,"prepareAuthorizationCodeRequest");async function pp(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:a}){let c=yS(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,c,t):o&&mS(pS(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=await(a??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await tp(p);let h=await p.json();try{return st.parse(h)}catch(g){throw typeof h=="object"&&h!==null&&"error"in h?await tp(JSON.stringify(h)):g}}n(pp,"executeTokenRequest");async function PS(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:a}){return{refresh_token:o,...await pp(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:a})}}n(PS,"refreshAuthorization");async function ES(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:a,fetchFn:c}={}){i!==void 0&&sp({iss:s,expectedIssuer:r?.issuer,issParameterSupported:ip(r)});let u=a??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=AS(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return pp(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:c})}n(ES,"fetchToken");async function xS(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 a={...r,...o===void 0?{}:{scope:o}},c=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new uS({status:c.status,body:await c.text(),submittedMetadata:a});return jt.parse(await c.json())}n(xS,"registerClient");var qT=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return be(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 be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,$t(this,new.target)}};function US(e){let t=Mt.safeParse(e);return t.success?t.data.id:void 0}n(US,"parseJsonRpcRequestId");function mp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return US(t)}catch{return}}n(mp,"readJsonRpcRequestIdFromBody");function Ko(e){return Un.parse({jsonrpc:dr,...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(Ko,"jsonRpcErrorResponse");function hp(e){return new Go([Ao.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(hp,"urlElicitationRequiredError");var Zo=l.record(l.string(),l.unknown()),OS=l.record(l.string(),l.unknown()),ht=l.array(l.string().min(1)).min(1).optional(),qS=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:OS.optional(),_meta:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),zS=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),MS=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:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),jS=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:Zo.optional(),roles:ht,groups:ht,public:l.boolean().optional()}).strict(),NS=l.array(l.union([l.string(),qS])),$S=l.array(l.union([l.string(),zS])),DS=l.array(l.union([l.string(),MS])),LS=l.array(l.union([l.string(),jS])),HS=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),BS=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:HS.optional()}).strict(),FS=l.object({tools:NS.optional(),prompts:$S.optional(),resources:DS.optional(),resourceTemplates:LS.optional(),accessControl:BS.optional()}).strict(),mt=[{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 JS(e,t){return _u(FS,e,`MCP capability filter policy "${t}"`)}n(JS,"parseMcpCapabilityFilterOptions");function ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ye,"isRecord");function Gn(e){return typeof e.method=="string"?e.method:void 0}n(Gn,"messageMethod");function fp(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(fp,"correlationKey");function gp(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(gp,"asStringArray");function yp(e,t){if(!ye(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>ye(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(yp,"readClaimValues");function vs(e,t){if(typeof e=="string")return{key:e,public:!1};if(!ye(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:gp(e.roles),groups:gp(e.groups),public:e.public===!0}}n(vs,"normalizeEntry");function GS(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(GS,"isCallerAllowed");function Wo(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let a=vs(s,t);a!==void 0&&GS(a,r,o)&&i.push(a.key)}return i}n(Wo,"allowedKeys");var wp=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(yp(e.user?.data,o)),a=new Set(yp(e.user?.data,i));return{tools:Wo(r.tools,"name",s,a),prompts:Wo(r.prompts,"name",s,a),resources:Wo(r.resources,"uri",s,a),resourceTemplates:Wo(r.resourceTemplates,"uriTemplate",s,a)}},"claimsCapabilityResolver");function VS(e,t){let r=[];for(let o of mt){let i=e[o.option];if(i!==void 0)for(let s of i){let a=vs(s,o.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new 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(VS,"assertNoConflictingMarkup");function KS(e,t){let r=[];for(let o of mt){let i=e[o.option];if(i!==void 0)for(let s of i){let a=vs(s,o.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new 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(KS,"assertNoMarkup");function WS(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,a,c)=>{let u=await i(s,a,c);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(WS,"buildCustomResolver");function ZS(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 WS(r,t)}if(o==="rolesAndGroups")return VS(e,t),wp;KS(e,t)}n(ZS,"buildCapabilityResolver");function YS(e){let t={};for(let r of mt){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let a=r_(s,r.itemProperty);a!==void 0&&i.set(a.key,a)}t[r.option]=i}return t}n(YS,"buildProjectionMaps");function Rs(e){return e===void 0?void 0:mt.find(t=>t.listMethod===e)}n(Rs,"findListRule");function XS(e){return e===void 0?void 0:mt.find(t=>t.directMethods.includes(e))}n(XS,"findDirectRule");function QS(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(QS,"directCapabilityAccess");function e_(e){let t=XS(Gn(e));if(t===void 0||!ye(e.raw))return;let r=e.raw.params;if(!ye(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(e_,"rawDirectCapabilityAccess");function t_(e){return Response.json(Ko({...e==null?{}:{id:e},error:{code:P.MethodNotFound,message:"Method not found"}}))}n(t_,"methodNotFoundResponse");function r_(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!ye(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(r_,"buildProjection");function Sp(e){let t=e.base[e.property],r=e.overlay[e.property];return ye(r)?ye(t)?{...t,...r}:r:t}n(Sp,"mergeRecordProperty");function n_(e,t){let r={...e,...t.overlay},o=Sp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Sp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(n_,"applyProjection");function _p(e,t,r,o){if(!ye(e))return e;let i=e.result;if(!ye(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(a=>ye(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.flatMap(a=>{if(!ye(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let u=r.get(c);return u===void 0?[]:[n_(a,u)]})}}}n(_p,"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=Rs(Gn(p)),g=h===void 0?void 0:fp(p.id);h!==void 0&&g!==void 0&&u.set(g,h)}return u.size===0?r:r.map(p=>{if(!ye(p)||"error"in p)return p;let h=fp(p.id),g=h===void 0?void 0:u.get(h),S=g===void 0?void 0:o[g.option];return g===void 0||S===void 0?p:_p(p,g,S,i?.[g.option])})}if(t.shape!=="single"||!ye(r)||"error"in r)return r;let s=t.messages[0],a=Rs(s===void 0?void 0:Gn(s)),c=a===void 0?void 0:o[a.option];return a===void 0||c===void 0?r:_p(r,a,c,i?.[a.option])}n(o_,"filterResponseBody");function i_(e){return e.headers.get("content-type")?.includes("json")??!1}n(i_,"isJsonResponse");var bs=class extends Ro{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=JS(t,r);super(o,r),this.#r=r,this.#e=YS(o),this.#t=ZS(o,r)}async handler(t,r){let o=await il(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let a of o.messages){let c=a.type==="request"?QS(a):e_(a);if(c===void 0)continue;let u=this.#e[c.option];if(u===void 0)continue;let p=i?.[c.option];if(!u.has(c.target)||p!==void 0&&!p.has(c.target))return t_(a.type==="request"?a.id:a.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async a=>{if(!i_(a))return a;let c;try{c=await a.clone().json()}catch{return a}let u=o_({envelope:o,responseBody:c,projectionMaps:s,allowedSets:i});if(u===c)return a;let p=new Headers(a.headers);return p.delete("content-length"),new Response(JSON.stringify(u),{status:a.status,statusText:a.statusText,headers:p})}),t}#n(t){return t.messages.some(r=>{let o=Gn(r);return o===void 0?!1:mt.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=Rs(Gn(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(a){r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; denying configured capabilities`,a);let c={};for(let u of mt)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let s={};for(let a of mt){let c=this.#e[a.option];if(c===void 0)continue;let u=i[a.option];if(u===void 0)continue;let p=new Set;if(Array.isArray(u))for(let h of u)typeof h=="string"&&c.has(h)&&p.add(h);s[a.option]=p}return s}};var Cs="zuplo.com",s_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),a_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Rp(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Rp,"s2FaviconHref");function c_(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(c_,"strictFaviconHref");var Yo=Rp(Cs);function Is(e){let t=e.toLowerCase();return t===Cs||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Rp(Cs):c_(e)}n(Is,"resolveIconHref");function d_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(d_,"hostnameFromHost");function u_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(u_,"isLocalOrAddressHost");function l_(e){let t=d_(e).toLowerCase().replace(/\.$/,"");if(u_(t)||a_.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=s_.has(o)?3:2;return r.slice(-i).join(".")}n(l_,"inferFaviconDomain");function Ts(e){return{src:Is(l_(e)),mimeType:"image/png",sizes:["128x128"]}}n(Ts,"resolveMcpFaviconIcon");function Xo(e){try{return Ts(new URL(e).host)}catch{return}}n(Xo,"resolveMcpFaviconIconFromUrl");function ft(e){let t=Ae().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(ft,"getUpstreamServerConfig");function Qo(e){let t=Ae().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(Qo,"getUpstreamAuthConfig");function wr(e,t){let r=Qo({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(wr,"requireUpstreamOAuthConfig");function bp(e,t){let r=Qo({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new K(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(bp,"requireUpstreamIdJagConfig");function vp(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(vp,"mergeAbortSignals");async function p_(e){try{await e.cancel()}catch{}}n(p_,"cancelReader");async function ei(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 p_(r),t.createLimitError();o.push(u),s=await r.read()}let a=new Uint8Array(i),c=0;for(let u of o)a.set(u,c),c+=u.byteLength;return a}n(ei,"readBoundedByteStream");var m_=2,h_=1024*1024,f_=1e4,g_=new Set([301,302,303,307,308]),y_=["authorization","proxy-authorization","cookie","cookie2"];function ks(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(ks,"readRequestUrl");function Rr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Rr,"readRequestMethod");function S_(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:{[I]:r}})}n(S_,"assertContentLengthWithinLimit");async function __(e,t,r){return S_(e,t,r),ei(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}}),"createLimitError")})}n(__,"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 R_(e,t){if(!g_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(R_,"resolveRedirectUrl");function Cp(e,t){try{return t.validateUrl(e)}catch(r){throw new v({message:"Outbound URL was not allowed.",extensionMembers:{[I]:t.problemCode}},{cause:r})}}n(Cp,"validateOutboundUrl");function b_(e,t){throw e instanceof v&&Eo(e.extensionMembers?.[I])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[I]:t}},{cause:e})}n(b_,"normalizeFetchError");function Vn(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(Vn,"logOutboundFailure");async function v_(e,t,r,o,i,s,a){let c=Rr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";Vn(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:ee(s),error:u,extra:{abortReason:a()}}),b_(u,i)}}n(v_,"fetchWithNormalizedError");function C_(e){if(e.redirects>=e.maxRedirects)throw new v({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[I]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new v({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[I]:e.problemCode}})}n(C_,"assertRedirectAllowed");function I_(e,t){let r=new Headers(e);for(let o of y_)r.delete(o);for(let o of t)r.delete(o);return r}n(I_,"stripCrossOriginHeaders");function T_(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=I_(e.headers,i)),s}n(T_,"buildRedirectInit");function k_(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(k_,"buildInitialRequestInit");function A_(e){let t=Rr(e.currentInput,e.currentInit);C_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Cp(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:T_(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(A_,"followRedirect");async function As(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??m_,s=r.maxResponseBytes??h_,a=r.timeoutMs??f_,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,g=vp(h,t.signal),S=!1,y=setTimeout(()=>{S=!0,h.abort()},a),k=e,w=k_(e,t,h.signal),C;try{C=Cp(ks(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw Vn(p,{event:"outbound_url_blocked",problemCode:o,method:Rr(e,t),host:ee(ks(e)),error:O}),clearTimeout(y),g?.(),O}let U=0;try{for(;;){let O=await v_(p,c,k,w,o,C,()=>S?`timeout_after_${a}ms`:void 0),L=R_(O,C);if(L!==void 0)try{let F=A_({currentInput:k,currentInit:w,currentUrl:C,redirectUrl:L,redirects:U,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});k=F.currentInput,w=F.currentInit,C=F.currentUrl,U=F.redirects;continue}catch(F){throw Vn(p,{event:"outbound_redirect_blocked",problemCode:o,method:Rr(k,w),host:ee(C),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:ee(L)}}),F}try{return w_(O,await __(O,s,o))}catch(F){throw Vn(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Rr(k,w),host:ee(C),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(y),g?.()}}n(As,"runSafeOutboundExchange");async function Kn(e,t,r){let o=await As(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Vn(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Rr(e,t),host:ee(ks(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:{[I]:r.problemCode??"invalid_request"}},{cause:i})}}n(Kn,"runSafeOutboundJsonExchange");function Ip(e,t={},r={}){return As(e,t,{...r,validateUrl:jn})}n(Ip,"fetchConfiguredOutbound");function Tp(e,t={},r={}){return Kn(e,t,{...r,validateUrl:jn})}n(Tp,"fetchConfiguredOutboundJson");function ti(e,t={},r={}){return Kn(e,t,{...r,validateUrl:Ku})}n(ti,"fetchIdentityProviderJson");function kp(e,t={},r={}){return Kn(e,t,{...r,validateUrl:jo})}n(kp,"fetchCimdClientMetadataJson");function Ap(e,t={},r={}){return Kn(e,t,{...r,validateUrl:Nn})}n(Ap,"fetchCimdClientJwksJson");import{errors as qp,jwtVerify as zp,SignJWT as Mp}from"jose";var Se="zuplo-mcp-gateway",ve=Se,Ce="HS256";import{base64url as P_}from"jose";var E_=new TextEncoder,x_="MCP gateway could not initialize secure key material.",U_=32,Pp=new Map,Ep=new Map,O_;function q_(){return O_??wa.instance.authPrivateKey}n(q_,"readAuthPrivateKey");function xp(e){return new ke(x_,e===void 0?void 0:{cause:e})}n(xp,"createGeneratedKeyMaterialError");function Up(e,t){let r=P_.decode(t);if(r.byteLength!==U_)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Up,"decodeJwkKeyField");function z_(e){let t=q_();if(!t)throw xp();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=Up("d",r.d);Up("x",r.x);let i=E_.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 xp(r)}}n(z_,"decodeGeneratedKeyMaterial");function M_(e){let t=Pp.get(e);return t||(t=z_(e),Pp.set(e,t)),t}n(M_,"getMasterKeyMaterial");async function $e(e){let t=Ep.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(M_(e.keyMaterialPurpose));return Ep.set(e.purpose,r),r}n($e,"readCachedDerivedKey");var j_="SHA-256",N_=32,$_="zuplo-mcp-gateway:",D_=new TextEncoder,Op=new WeakMap;async function gt(e,t){let r=Op.get(e);r||(r=new Map,Op.set(e,r));let o=r.get(t);if(o)return o;let i=await L_(e,t);return r.set(t,i),i}n(gt,"deriveGatewaySigningKey");async function L_(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=D_.encode(`${$_}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:j_,salt:new Uint8Array,info:me(i)},o,N_*8);return new Uint8Array(s)}n(L_,"hkdfExpand");var jp=900,H_=900,B_=Eu.extend({id:Qu}),F_=B_.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Np=Mi.extend({id:el,purpose:l.literal("browser_connect")}),J_=Mi.extend({purpose:l.literal("browser_connect")}),G_=Np.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),$p=jp*1e3;async function Dp(){return $e({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>gt(e,"oauth-state"),"derive")})}n(Dp,"getOAuthStateKey");async function Lp(){return $e({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>gt(e,"browser-connect"),"derive")})}n(Lp,"getBrowserConnectKey");async function Hp(e){let t=Math.floor(Date.now()/1e3)+jp;return new Mp(e).setProtectedHeader({alg:Ce,typ:"JWT"}).setIssuer(Se).setAudience(ve).setIssuedAt().setExpirationTime(t).sign(await Dp())}n(Hp,"signOAuthState");async function ri(e){try{let{payload:t}=await zp(e,await Dp(),{algorithms:[Ce],issuer:Se,audience:ve});return F_.parse(t)}catch(t){throw t instanceof qp.JWTExpired?new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"OAuth state could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(ri,"verifyOAuthState");async function Bp(e){let t=Math.floor(Date.now()/1e3)+H_,r=J_.parse(e),o=Np.parse({...r,id:ol()});return new Mp(o).setProtectedHeader({alg:Ce,typ:"JWT"}).setIssuer(Se).setAudience(ve).setIssuedAt().setExpirationTime(t).sign(await Lp())}n(Bp,"signBrowserConnectTicket");async function Fp(e){try{let{payload:t}=await zp(e,await Lp(),{algorithms:[Ce],issuer:Se,audience:ve});return G_.parse(t)}catch(t){throw t instanceof qp.JWTExpired?new v({message:"Browser connect ticket has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"Browser connect ticket could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(Fp,"verifyBrowserConnectTicket");async function Jp(e){if((await j().consumeBrowserConnectTicket({id:e.id,expiresAt:$(new Date(e.exp*1e3)),now:$(new Date)})).kind==="consumed")throw new v({message:"Browser connect ticket has already been used",extensionMembers:{[I]:"oauth_state_reused"}})}n(Jp,"consumeBrowserConnectTicket");function V_(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(V_,"buildConnectRequiredMessage");async function K_(e){let t=re(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 Bp({...zn(e),purpose:"browser_connect"})),r.toString()}n(K_,"buildGatewayBrowserTicketUrl");function W_(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(W_,"buildGatewayConnectPath");async function Ps(e){return K_({...e,path:W_(e.upstreamServerId),redirect:!0})}n(Ps,"buildGatewayConnectUrl");async function ni(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Ps(t),message:V_(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ni,"buildRedirectConnectRequiredResponse");function Gp(e){return Z_({...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(Gp,"buildAdminConnectRequiredResponse");function Z_(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(Z_,"buildAdminSetupRequiredResponse");var Vp=12;async function Kp(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(Kp,"sha256Hex");async function Dt(e){if(e)return(await Kp(e)).slice(0,Vp)}n(Dt,"fingerprintSecret");async function br(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Kp(t)).slice(0,Vp)}n(br,"fingerprintConnectionIdentity");var Y_=6e4;function vr(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(vr,"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()+Y_)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var Wp=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function X_(e,t){return e&&e.length>0?e.join(t):void 0}n(X_,"joinOAuthScopes");function Q_(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Wp)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Q_,"sanitizeAuthorizationServerMetadata");function Zp(e){let t=Q_(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Zp,"sanitizeOAuthDiscoveryState");function Yp(e){let t=new URL(e);for(let r of Wp){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Yp,"dedupeSingletonAuthorizationRequestParams");function oi(e){let t=new URL(e);return Re(t)&&Su(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(oi,"normalizeLoopbackOAuthRedirectUri");function Xp(e){return X_(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Xp,"readProtectedResourceMetadataScope");function ew(e){return`Zuplo MCP Gateway - ${e}`}n(ew,"buildGatewayOAuthClientName");function tw(e,t){return e&&e.length>0?e.join(t):void 0}n(tw,"joinOAuthScopeList");function rw(e){if(e.clientRegistration.mode!=="auto")return tw(e.scopes,e.scopeDelimiter)}n(rw,"readPublicClientMetadataScope");function Es(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Es,"buildOAuthClientMetadataDocumentUrl");function xs(e){let t=ft(e.upstreamServerId);return{client_name:ew(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(xs,"buildGatewayOAuthClientMetadata");function Qp(e,t,r){let o=wr(t,r),i=rw(o);return{client_id:Es({origin:e,upstreamServerId:t}),...xs({origin:e,upstreamServerId:t,redirectUri:oi(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Qp,"buildOAuthClientMetadataDocument");import{base64url as yt}from"jose";var nw="SHA-256",Cr="AES-GCM",ow=12,Os="zuplo-secret",qs=1,em="generated:auth_private_key:token-encryption",iw=l.object({version:l.literal(qs),keyId:l.literal(em),algorithm:l.literal(Cr),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Us(){return $e({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(nw,me(e));return crypto.subtle.importKey("raw",t,{name:Cr},!1,["encrypt","decrypt"])},"derive")})}n(Us,"getEncryptionKey");function tm(e){return me(new TextEncoder().encode(`${Os}:v${e.version}:${e.keyId}`))}n(tm,"getAssociatedData");function sw(e){return`${Os}:v${e.version}:${yt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(sw,"encodeEnvelope");function aw(e){let t=`${Os}:v${qs}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(yt.decode(r));return iw.parse(JSON.parse(o))}n(aw,"decodeEnvelope");async function We(e){let t=await Us(),r=crypto.getRandomValues(new Uint8Array(ow)),o={version:qs,keyId:em},i=await crypto.subtle.encrypt({name:Cr,iv:r,additionalData:tm(o)},t,new TextEncoder().encode(e));return sw({...o,algorithm:Cr,iv:yt.encode(r),ciphertext:yt.encode(new Uint8Array(i))})}n(We,"encryptSecret");async function Ze(e){let t=aw(e);if(t){let a=await Us(),c=await crypto.subtle.decrypt({name:Cr,iv:me(yt.decode(t.iv)),additionalData:tm(t)},a,me(yt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ke("Encrypted payload is malformed");let i=await Us(),s=await crypto.subtle.decrypt({name:Cr,iv:me(yt.decode(r))},i,me(yt.decode(o)));return new TextDecoder().decode(s)}n(Ze,"decryptSecret");var rm={issuer:l.string().min(1).optional()},cw=l.union([jt.extend(rm),On.extend(rm)]),nm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:ur.optional(),authorizationServerMetadata:l.union([lr,pr]).optional()}).passthrough(),dw="Bearer",uw="__zuplo_refresh_only_upstream_access_token__";function zs(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(zs,"splitScopes");function Ms(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ms,"scopesCover");function lw(e){return hr.parse(e)}n(lw,"parsePkceCodeVerifier");function pw(e){if(typeof e.expires_in=="number")return $(new Date(Date.now()+e.expires_in*1e3))}n(pw,"readTokenExpiry");async function om(e){if(e!==void 0)return We(JSON.stringify(e))}n(om,"encryptJson");async function im(e,t){if(!e)return;let r=await Ze(e);try{return t.parse(JSON.parse(r))}catch(o){throw new v({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:o})}}n(im,"decryptJson");function mw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(mw,"clientInformationAllowsRedirectUri");function hw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(hw,"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 yw(e,t){return Xp({state:e,delimiter:t})}n(yw,"readResourceMetadataScope");function Sw(e,t){return e&&e.length>0?e.join(t):void 0}n(Sw,"joinOAuthScopeList");function _w(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 jt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(_w,"buildManualOAuthClientInformation");function ww(e,t){let r=Es({origin:new URL(t).origin,upstreamServerId:e});return ws(r)?r:void 0}n(ww,"buildClientMetadataUrl");function Rw(e){for(let t of e)if(t!==void 0)return t}n(Rw,"firstDefined");function bw(e){let t=wr(e.target.upstreamServerId,e.target.authProfileId),r=Sw(t.scopes,t.scopeDelimiter),o=xs({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,configuredClientInformation:_w({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}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(bw,"buildInitialOAuthClientSetup");function vw(e,t){if(t===void 0)return Rw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(vw,"readEncryptedClientInformation");function Cw(e){return e.pendingState?.encryptedDiscoveryState}n(Cw,"readEncryptedDiscoveryState");function js(e,t){return t===void 0?e:{...e,issuer:t}}n(js,"applyIssuerStamp");var St=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=bw({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.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=vw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Cw(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}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 Ms(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 br({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Dt(await Ze(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await j().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 Hp({id:t.id,...zn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?js(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 om(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Zp(nm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await om(r),await this.syncPendingState(!1),W()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ee(r.authorizationServerUrl),resourceMetadataHost:ee(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=yw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let 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 js(r,t?.issuer)}async saveTokens(t){let r=st.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,a=r.refresh_token?await We(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:st.parse({...r,refresh_token:await Ze(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:i?.id??No(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await We(r.access_token),encryptedRefreshToken:a,scopes:zs(r.scope??this.readEffectiveScope()),expiresAt:pw(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(c,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ms(p.connection.scopes,c.scopes)||!vr(i,p.connection))){h=!0;let S=p.connection,y={id:S.id,ownerMode:S.ownerMode,subjectId:S.subjectId,upstreamServerId:S.upstreamServerId,authProfileId:S.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?S.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:S.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:S.id,sourceUpdatedAt:i?.updatedAt,winnerUpdatedAt:S.updatedAt,sourceScopeCount:i?.scopes.length,winnerScopeCount:S.scopes.length,resultingScopeCount:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),p=await this.conditionalUpsertCredential(y,{expectedUpdatedAt:S.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,vr(i,p.connection)&&he(p.connection)==="usable"&&Ms(p.connection.scopes,c.scopes)?this.adoptPeerConnection(p.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),h){let S=p.kind==="persisted"?"succeeded":p.kind==="precondition_failed"?"lost":"exhausted";W()?.info({event:`upstream_oauth_bounded_rebase_${S}`,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 ${S}`)}let g=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:g?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Dt(r.refresh_token),reusedSnapshotRefreshToken:s,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:p.kind,rebaseAttempted:h,resultingUpdatedAt:g?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:g?.scopes.length??this.credentialState.currentConnection?.scopes.length},g?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Yp(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:lw(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new v({message:"OAuth code verifier is missing",extensionMembers:{[I]:"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:nl(),...zn({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:$(new Date(Date.now()+$p)),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 j().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 im(this.encryptedClientInformation,cw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!mw(r,this.redirectUriValue)||!hw({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=js(On.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 im(this.encryptedDiscoveryState,nm)}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 Ze(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Ze(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Dt(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=st.parse({access_token:r??uw,token_type:dw,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 a=await this.conditionalUpsertCredential(s,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,vr(r,a.connection)&&he(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=W();if(c){let u=a.kind==="missing"?void 0:a.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:a.kind};a.kind==="precondition_failed"?c.warn({...p,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(p,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(p,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Iw=3e4,Tw=256*1024,kw=2,Aw="does not support dynamic client registration",Pw=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Ew=["HTTP 403 Forbidden","Access Denied","permission to access"],xw=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function Uw(e){return e instanceof Error&&e.message.includes(Aw)}n(Uw,"isDynamicClientRegistrationUnsupported");function Ow(e){return e instanceof Error&&Pw.some(t=>e.message.includes(t))}n(Ow,"isProtectedResourceMetadataUnavailable");function qw(e){return e instanceof Error&&Ew.some(t=>e.message.includes(t))}n(qw,"isUpstreamProviderAccessDenied");function zw(e){return e instanceof pt&&xw.has(e.code)}n(zw,"isStoredConnectionReconsentError");function Mw(e){if(e.error instanceof v&&e.error.extensionMembers?.[I]!==void 0)return e.error;if(Uw(e.error))return new v({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.`,extensionMembers:{[I]:"upstream_client_registration_required"}},{cause:e.error});if(Ow(e.error))return new v({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.`,extensionMembers:{[I]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(qw(e.error))return new v({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[I]:"upstream_provider_access_denied"}},{cause:e.error})}n(Mw,"mapUpstreamOAuthSetupError");function jw(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(jw,"readOAuthFetchRequest");function Nw(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Nw,"responseLooksJson");function $w(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($w,"responseLooksHtml");function Dw(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:{[I]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[at]:e.response.status,[fr]:r,[ct]:e.request.url.toString(),[gr]:e.body}})}n(Dw,"throwUpstreamHtmlError");function Lw(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(Lw,"readUpstreamOAuthErrorBody");function Hw(e){let{error:t,errorDescription:r}=Lw(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:ee(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(Hw,"logUpstreamOAuthHttpError");function am(e){return async(t,r)=>{let o=jw(t),i=W(),s=Date.now(),a=await Ip(t,r,{maxRedirects:kw,maxResponseBytes:Tw,problemCode:"upstream_token_exchange_failed",timeoutMs:Iw}),c=await a.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:ee(o.url),path:o.url.pathname,status:a.status,durationMs:Date.now()-s,responseChars:c.length},"Upstream OAuth HTTP request completed"),a.ok||Hw({log:i,upstreamServerId:e,request:o,response:a,body:c}),!a.ok&&$w(a,c)&&Dw({upstreamServerId:e,request:o,response:a,body:c}),!Nw(a,c))return a;try{JSON.parse(c)}catch(u){throw new v({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}},{cause:u})}return a}}n(am,"createUpstreamOAuthFetch");function cm(e){W()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ee(e.serverUrl),resourceMetadataHost:ee(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(cm,"logUpstreamOAuthFlowStarted");function dm(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ee(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof v?e.error.extensionMembers?.[I]: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(dm,"logUpstreamOAuthFlowFailed");function um(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(um,"readAuthorizationRequestScope");async function lm(e,t){e.applyChallengeScope(t.requestedScope),cm({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:am(t.upstreamServerId)},o=um(e,t);return o!==void 0&&(r.scope=o),await _s(e,r)}catch(r){dm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Mw({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(lm,"runUpstreamOAuth");async function Bw(e,t){e.applyChallengeScope(t.requestedScope),cm({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:am(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=um(e,t);o!==void 0&&(r.scope=o);try{return await _s(e,r)}catch(i){throw dm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(Bw,"exchangeUpstreamAuthorizationCode");async function sm(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await j().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||he(r)!=="usable"||!vr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(sm,"adoptPeerCredentialAtResolutionBoundary");async function pm(e,t){let r=await lm(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:{[I]:"upstream_token_exchange_failed"}}):new v({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(pm,"requireUpstreamAuthorizationRedirect");async function mm(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 br({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 a;try{a=await lm(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!zw(c))throw c;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.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 sm({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 Ns({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Ns({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new v({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[I]:"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:{[I]:"upstream_token_exchange_failed"}});return await sm({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 Ns({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(mm,"authorizeUpstreamOAuthSession");async function Fw(e){let t=await ri(e.stateToken),r=await j().consumeUpstreamOAuthState({id:t.id,now:$(new Date)}),o=Jw(r);return Gw({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Vw(o),o}n(Fw,"consumeStoredCallbackState");function Jw(e){switch(e.kind){case"consumed":throw new v({message:"OAuth state has already been used",extensionMembers:{[I]:"oauth_state_reused"}});case"missing":throw new v({message:"OAuth state is missing or expired",extensionMembers:{[I]:"oauth_state_expired"}});case"available":return e.record}}n(Jw,"readConsumedCallbackState");function Gw(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:{[I]:"oauth_callback_mismatch"}})}n(Gw,"assertStoredCallbackStateMatches");function Vw(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}})}n(Vw,"assertStoredCallbackStateFresh");async function Ns(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),Gp(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),ni(t)}n(Ns,"buildOAuthConnectRequiredResponse");async function hm(e){let t=await Fw({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Oo(t),[o]=await j().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 St(i),a=await Bw(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(a==="AUTHORIZED"){let c=s.readUsablePeerAdoption();if(c!==void 0&&await s.adoptConnectionForDirectResolution(c,"cas_loss"),!s.tokenWriteWasPersisted&&c===void 0)throw new v({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new v({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(hm,"finishUpstreamOAuthCallback");import{importPKCS8 as Kw,SignJWT as Ww}from"jose";var gm=1e4,ym=64*1024,Sm=2,Zw=300,qe=l.string().min(1),Yw=l.object({access_token:qe,issued_token_type:l.literal(Ni),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:qe.optional()}).passthrough(),Xw=l.object({id_token:qe,token_type:qe.optional(),expires_in:l.number().int().positive().optional(),refresh_token:qe.optional(),scope:qe.optional()}).passthrough(),Qw=l.object({access_token:qe,token_type:qe,expires_in:l.number().int().positive().optional(),scope:qe.optional(),resource:qe.optional(),refresh_token:qe.optional()}).passthrough();function fm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(fm,"formEncodeClientCredential");function eR(e){return e.replaceAll("\\n",`
|
|
26
26
|
`)}n(eR,"normalizePem");async function tR(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??Zw,o=await Kw(eR(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new Ww({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(tR,"createPrivateKeyJwtClientAssertion");async function rR(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=fm(e.clientAuth.clientId),r=fm(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",zo),e.form.set("client_assertion",await tR({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(rR,"appendClientAuthentication");async function $s(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await rR({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n($s,"buildFormRequest");function _m(e){return(t,r)=>ti(t,r,{context:e,maxRedirects:Sm,maxResponseBytes:ym,problemCode:"upstream_token_exchange_failed",timeoutMs:gm})}n(_m,"defaultIdpFetchJson");function nR(e){return(t,r)=>Tp(t,r,{context:e,maxRedirects:Sm,maxResponseBytes:ym,problemCode:"upstream_token_exchange_failed",timeoutMs:gm})}n(nR,"defaultResourceAsFetchJson");function ii(e){let t={[I]:e.code,[ct]:e.tokenUrl};return e.response!==void 0&&(t[at]=e.response.status),new v({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(ii,"runtimeError");function Ds(e){if(!e.response.ok)throw ii({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(Ds,"assertTokenEndpointSucceeded");function oR(e){let t=Xw.safeParse(e.json);if(!t.success)throw ii({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(oR,"parseIdpRefreshTokenResponse");function iR(e){let t=Yw.safeParse(e.json);if(!t.success)throw ii({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(iR,"parseIdJagTokenExchangeResponse");function sR(e){let t=Qw.safeParse(e.json);if(!t.success)throw ii({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(sR,"parseAccessTokenResponse");async function wm(e){let t=new URLSearchParams({grant_type:qo,requested_token_type:Ni,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??_m(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await $s({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Ds({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),iR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(wm,"requestIdJag");async function Rm(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??_m(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await $s({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Ds({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),oR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Rm,"refreshIdpSubjectToken");async function bm(e){let t=new URLSearchParams({grant_type:ut,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??nR(e.context),{response:o,json:i}=await r(e.resourceAs.tokenUrl,await $s({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Ds({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),sR({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(bm,"exchangeIdJagForAccessToken");function aR(e){return he(e)==="usable"}n(aR,"hasUsableAccessToken");function cR(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:{[I]:"upstream_token_response_invalid"}})}n(cR,"assertBearerToken");function vm(e,t){if(t===_r)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(vm,"hasExpiredSubjectToken");async function dR(e){let t=await Ze(e.encryptedSubjectToken);if(e.subjectTokenType!==_r)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Rm({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:Mn};let o=await j().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 We(r.refreshToken),idpSubjectTokenType:_r,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 Dt(t),newSubjectRefreshTokenFingerprint:await Dt(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:Mn}}n(dR,"resolveIdJagSubjectToken");async function Cm(e){let t="preloadedConnection"in e?e.preloadedConnection:(await j().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=he(t),o=!!e.forceRefresh,i=!o&&r==="usable",s=W(),a=s?await br({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:a,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&&aR(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Ze(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||u===void 0||vm(t,u))return s?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:u,subjectTokenExpired:u!==void 0&&vm(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=ft(e.upstreamServerId),h=bp(e.upstreamServerId,e.authProfileId),g=h.resourceAs.resource??p.transport.baseUrl,S=e.requestedScope??(h.scopes.length===0?void 0:h.scopes.join(h.scopeDelimiter)),y=await dR({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:u,idp:{tokenUrl:h.idp.tokenUrl},clientAuth:h.idp.clientAuth,context:e.context}),k=await wm({idp:{tokenUrl:h.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:h.resourceAs.audience,resource:g,scope:S,clientAuth:h.idp.clientAuth,context:e.context}),w=k.scope??S,C=await bm({resourceAs:{tokenUrl:h.resourceAs.tokenUrl},assertion:k.assertion,resource:g,scope:w,clientAuth:h.resourceAs.clientAuth,context:e.context});if(cR(C),t!==void 0){let O=(C.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],L=C.expiresIn===void 0?void 0:$(new Date(Date.now()+C.expiresIn*1e3)),F=await j().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await We(C.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:O,expiresAt:L,metadata:y.connection.metadata});s?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:F.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:O.length,expiresAt:L},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:C.accessToken}}}n(Cm,"authorizeUpstreamIdJagRequest");var si=new Map;function uR(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(uR,"normalizeRefreshFlightScope");function lR(e){return oi(new URL(e.callbackPath,re(e.requestUrl,e.requestHeaders))).toString()}n(lR,"buildGatewayOAuthRedirectUri");async function Ls(e){let t=ft(e.upstreamServerId),r=wr(e.upstreamServerId,e.authProfileId),o=lR({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await j().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:re(e.request.url,e.request.headers)}}}n(Ls,"prepareUpstreamOAuthRequest");async function Im(e){let t=await Ls(e),r=new St({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return pm(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Im,"startUpstreamConnect");async function Tm(e){let t=await Ls(e),r=new St({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>mm({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=tl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),s=JSON.stringify([i,uR(r.configuredAuthorizationScope??e.requestedScope)]),a=si.get(s);if(a!==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 a;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,...g}=e;if(t=await Ls(g),r=new St({...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 c=o(),u;return u=c.then(()=>{let p=r.currentConnection;return p!==void 0&&he(p)==="usable"?{kind:"usable",connection:p}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{si.get(s)===u&&si.delete(s)}),si.set(s,u),c}n(Tm,"authorizeUpstreamRequest");async function Ir(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Tm({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 Cm({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 ke(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Ir,"resolveUpstreamCredentialForRoute");async function km(e){if(e.connectRequest.authMode==="id-jag")throw new ke(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Im({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(km,"startUpstreamConnectForRequest");async function Am(e){let r=(await ri(e.callbackRequest.state)).authProfileId;if(Qo({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new ke(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return hm({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:ft(e.callbackRequest.upstreamServerId)})}n(Am,"finishUpstreamCallbackForRequest");function pR(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(pR,"buildRouteAuthBaseFromConnection");function Pm(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:xu(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Pm,"buildRouteAuthBaseFromPolicyOptions");function ai(e,t){let o=Ae().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 pR({connection:o.connection,operationId:t})}n(ai,"resolveRouteAuthBase");function Hs(e,t){switch(e){case"user":return yr(t);case"shared":return Pu()}}n(Hs,"buildOwnerForSubject");function Tr(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:Hs("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:Hs("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:Hs("user",t),initiatedBySubjectId:t}}}n(Tr,"resolveRouteAuthForSubject");var mR=P.InvalidRequest,hR=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function fR(e,t){return{credentialType:e.type,forceRefresh:t}}n(fR,"buildCredentialResolvedAttributes");function gR(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(gR,"connectRequiredReasonCode");function Em(e){G(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:fR(e.credential,e.forceRefresh===!0)})}n(Em,"emitCredentialResolvedAnalyticsEvent");function xm(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(G(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"){G(e.context,{eventType:H.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}G(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:gR(e.payload.state),reasonClass:"auth",attributes:t})}n(xm,"emitCredentialMissingAnalyticsEvents");function yR(e){let t=e.route.raw();return Uo.parse(t?.operationId)}n(yR,"readOperationId");async function SR(e,t,r,o){let i=await Ir({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return xm({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(Em({context:o,credential:s,routeBinding:t}),s.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${s.token}`]]};let a=await s.provider.tokens();return a?{kind:"headers",headers:[["authorization",`${a.token_type??"Bearer"} ${a.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(SR,"buildCredentialHeaders");var _R=new Set(["authorization","cookie","cookie2"]);function wR(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(wR,"readJsonRequestMethod");function RR(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(RR,"isJsonResponse");function Bs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Bs,"isRecord");function bR(e){return Array.isArray(e)&&e.length>0}n(bR,"hasIconList");function vR(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Xo(Iu(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(vR,"readFallbackServerIcons");function CR(e){if(!Bs(e.body))return e.body;let t=e.body.result;if(!Bs(t))return e.body;let r=t.serverInfo;return!Bs(r)||bR(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(CR,"addMissingServerIcons");function IR(e,t){let r=Um(e);for(let o of _R)r.delete(o);for(let[o,i]of t)r.set(o,i);return new ba(e,{headers:r})}n(IR,"applyUpstreamHeaders");var TR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function kR(e){let t=e.get("connection");return t===null?[]:t.split(",").map(r=>r.trim()).filter(r=>TR.test(r))}n(kR,"connectionNominatedHeaderNames");function Um(e){let t=new Headers(e.headers);for(let r of kR(t))t.delete(r);for(let r of hR)t.delete(r);return t}n(Um,"buildProxyHeaders");async function AR(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(AR,"readRetryBody");function Om(e,t){let r=t.authUrl===void 0?void 0:hp({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Ko({id:mp(e),error:{code:r?.code??mR,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Om,"connectRequiredJsonRpcResponse");async function PR(e){let{scope:t}=cp(e.upstreamResponse),r=await Ir({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return xm({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(Em({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(PR,"applyRefreshedCredentialHeaders");function ER(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await PR({request:e.request,context:e.context,headers:Um(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Om(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=Tu({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return wo.fetch(i.url,i.init)})}n(ER,"installUpstreamAuthRetryHook");function xR(e){if(wR(e.requestBody)!=="initialize")return;let t=vR({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!RR(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=CR({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(xR,"installInitializeIconHook");async function Fs(e,t,r){let o=yR(t),i=await AR(e),s=Pm({connection:r,operationId:o}),a=Nt(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),ju(t,a);let c=Tr(s,a.subjectId),u=await SR(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Om(i,u.payload);if(u instanceof Response)return u;let p=IR(e,u.headers);return ER({request:p,context:t,requestBody:i,routeAuth:c}),xR({context:t,requestBody:i,connection:r}),p}n(Fs,"mcpTokenExchangePolicy");var Js=class extends Ro{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=Uu(t,r);super(o,r),this.#e=o}async handler(t,r){return Fs(t,r,this.#e)}};var qm=Symbol("Html");function UR(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(UR,"escapeHtml");function OR(e){return e===null||typeof e!="object"?!1:e[qm]===!0}n(OR,"isHtml");function zm(e){return e==null||e===!1?"":Array.isArray(e)?e.map(zm).join(""):OR(e)?e.value:UR(String(e))}n(zm,"renderValue");function Ye(e){return{[qm]:!0,value:e}}n(Ye,"trustedHtml");var Pe=Ye("");function B(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=zm(t[o]),r+=e[o+1]??"";return Ye(r)}n(B,"html");function kr(e){return e.value}n(kr,"renderHtml");function Mm(e){return B`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(Mm,"renderBrowserErrorPage");var Ar=Ye('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@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 Pr(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(Pr,"renderShell");var qR="text/html; charset=utf-8";function Er(e){try{return new URL(e).host}catch{return""}}n(Er,"safeHostFromUrl");function De(e){let t=MR(e.kind??"authorization_failed"),r=zR(e);return new Response(kr(Pr({title:e.title??t.title,iconHref:"",styles:Ar,headerIcon:Pe,heading:e.title??t.title,subhead:"",body:Mm({detail:e.detail,guidance:B`<p class="card__description">${t.guidance}</p>`,technicalDetails:LR({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:$R(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":qR,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(De,"browserErrorPageResponse");function zR(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??jR(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??NR(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(zR,"buildBrowserErrorDiagnostic");function MR(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(MR,"readBrowserErrorPagePresentation");function jR(e){switch(e){case"upstream_oauth_discovery_unavailable":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(jR,"readBrowserErrorStage");function NR(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_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(NR,"readBrowserErrorSuggestedFix");function $R(e){return e===void 0?Pe:B`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n($R,"renderAction");function DR(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(`
|