@onyxsecurity/mcp-gateway 2.1.43 → 2.1.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/bin/mcp-gateway.js +2 -2
  2. package/dist/bin/mcp-gateway.js.map +1 -1
  3. package/dist/cli-CNtgMMkg.js +3 -0
  4. package/dist/cli-CNtgMMkg.js.map +1 -0
  5. package/dist/env-BDKldJJk.js +2 -0
  6. package/dist/env-BDKldJJk.js.map +1 -0
  7. package/dist/env-CgxPliUz.js +1 -0
  8. package/dist/helpers-DOLqaEj0.js +93 -0
  9. package/dist/helpers-DOLqaEj0.js.map +1 -0
  10. package/dist/index.d.ts +21 -0
  11. package/dist/index.js +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/logger-CilZJgRr.js +5 -0
  14. package/dist/{logger-CWUh95SA.js.map → logger-CilZJgRr.js.map} +1 -1
  15. package/dist/logger-e6I79GjO.js +1 -0
  16. package/dist/main-BFGMEBYS.js +6 -0
  17. package/dist/main-BFGMEBYS.js.map +1 -0
  18. package/dist/{normalizeUrl-DoppHGlo.js → normalizeUrl-DUUGubD4.js} +1 -1
  19. package/dist/{normalizeUrl-DoppHGlo.js.map → normalizeUrl-DUUGubD4.js.map} +1 -1
  20. package/dist/oauthProvidersClient-CbHTOMq_.js +2 -0
  21. package/dist/oauthProvidersClient-CbHTOMq_.js.map +1 -0
  22. package/dist/oauthProvidersClient-gES4TS6R.js +1 -0
  23. package/dist/pkce-C7ZxslWt.js +1 -0
  24. package/dist/{pkce-DKfQXsGm.js → pkce-DUsFn3Kw.js} +1 -1
  25. package/dist/{pkce-DKfQXsGm.js.map → pkce-DUsFn3Kw.js.map} +1 -1
  26. package/dist/{providers-DiyaT-nZ.js → providers-DdC7BWQI.js} +2 -2
  27. package/dist/{providers-DiyaT-nZ.js.map → providers-DdC7BWQI.js.map} +1 -1
  28. package/dist/proxyFetch-C1EVTHaR.js +2 -0
  29. package/dist/proxyFetch-C1EVTHaR.js.map +1 -0
  30. package/dist/{secretstore-B7UBzLo4.js → secretstore-Bb_yKd3c.js} +3 -3
  31. package/dist/{secretstore-B7UBzLo4.js.map → secretstore-Bb_yKd3c.js.map} +1 -1
  32. package/dist/transportDetection-Dw8flZ7W.js +136 -0
  33. package/dist/transportDetection-Dw8flZ7W.js.map +1 -0
  34. package/dist/upstreamNegotiation-CRw30abB.js +15 -0
  35. package/dist/upstreamNegotiation-CRw30abB.js.map +1 -0
  36. package/package.json +1 -1
  37. package/dist/chunk-CrDKVgUD.js +0 -1
  38. package/dist/cli-C7vmKlGv.js +0 -3
  39. package/dist/cli-C7vmKlGv.js.map +0 -1
  40. package/dist/env-BYAgFtQA.js +0 -1
  41. package/dist/env-DXIcThnP.js +0 -2
  42. package/dist/env-DXIcThnP.js.map +0 -1
  43. package/dist/helpers-BLNSu673.js +0 -92
  44. package/dist/helpers-BLNSu673.js.map +0 -1
  45. package/dist/logger-CWUh95SA.js +0 -5
  46. package/dist/main-CIjGR_ZE.js +0 -6
  47. package/dist/main-CIjGR_ZE.js.map +0 -1
  48. package/dist/oauthProvidersClient-CC-cNbIE.js +0 -2
  49. package/dist/oauthProvidersClient-CC-cNbIE.js.map +0 -1
  50. package/dist/oauthProvidersClient-DJPWxaxB.js +0 -1
  51. package/dist/pkce-CYE2WffE.js +0 -1
  52. package/dist/transportDetection-DmhqNhkc.js +0 -136
  53. package/dist/transportDetection-DmhqNhkc.js.map +0 -1
  54. package/dist/upstreamNegotiation-BT6dzuoL.js +0 -15
  55. package/dist/upstreamNegotiation-BT6dzuoL.js.map +0 -1
@@ -61,4 +61,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
61
61
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function S_(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
62
62
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
63
63
  `&&r++}}return[t,n]}var C_=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(E_(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(E_(this),t)}};function w_(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function T_(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(T_).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${T_(e.cause)}`:e.message:`${e}`}function E_(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var D_=e=>{throw TypeError(e)},O_=(e,t,n)=>t.has(e)||D_(`Cannot `+n),Q=(e,t,n)=>(O_(e,t,`read from private field`),n?n.call(e):t.get(e)),k_=(e,t,n)=>t.has(e)?D_(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),$=(e,t,n,r)=>(O_(e,t,`write to private field`),t.set(e,n),n),A_=(e,t,n)=>(O_(e,t,`access private method`),n),j_,M_,N_,P_,F_,I_,L_,R_,z_,B_,V_,H_,U_,W_,G_,K_,q_,J_,Y_,X_,Z_,Q_,$_,ev=class extends EventTarget{constructor(e,t){super(),k_(this,W_),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,k_(this,j_),k_(this,M_),k_(this,N_),k_(this,P_),k_(this,F_),k_(this,I_),k_(this,L_),k_(this,R_,null),k_(this,z_),k_(this,B_),k_(this,V_,null),k_(this,H_,null),k_(this,U_,null),k_(this,K_,async e=>{var t;Q(this,B_).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){A_(this,W_,Z_).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?$(this,N_,new URL(e.url)):$(this,N_,void 0),i!==200){A_(this,W_,Z_).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){A_(this,W_,Z_).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(Q(this,j_)===this.CLOSED)return;$(this,j_,this.OPEN);let o=new Event(`open`);if((t=Q(this,U_))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){A_(this,W_,Z_).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&Q(this,B_).feed(s.decode(t,{stream:!e})),e&&(l=!1,Q(this,B_).reset(),A_(this,W_,Q_).call(this))}while(l)}),k_(this,q_,e=>{$(this,z_,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&A_(this,W_,Q_).call(this,T_(e))}),k_(this,Y_,e=>{typeof e.id==`string`&&$(this,R_,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:Q(this,N_)?Q(this,N_).origin:Q(this,M_).origin,lastEventId:e.id||``});Q(this,H_)&&(!e.event||e.event===`message`)&&Q(this,H_).call(this,t),this.dispatchEvent(t)}),k_(this,X_,e=>{$(this,I_,e)}),k_(this,$_,()=>{$(this,L_,void 0),Q(this,j_)===this.CONNECTING&&A_(this,W_,G_).call(this)});try{if(e instanceof URL)$(this,M_,e);else if(typeof e==`string`)$(this,M_,new URL(e,tv()));else throw Error(`Invalid URL`)}catch{throw w_(`An invalid or illegal string was specified`)}$(this,B_,x_({onEvent:Q(this,Y_),onRetry:Q(this,X_)})),$(this,j_,this.CONNECTING),$(this,I_,3e3),$(this,F_,t?.fetch??globalThis.fetch),$(this,P_,t?.withCredentials??!1),A_(this,W_,G_).call(this)}get readyState(){return Q(this,j_)}get url(){return Q(this,M_).href}get withCredentials(){return Q(this,P_)}get onerror(){return Q(this,V_)}set onerror(e){$(this,V_,e)}get onmessage(){return Q(this,H_)}set onmessage(e){$(this,H_,e)}get onopen(){return Q(this,U_)}set onopen(e){$(this,U_,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){Q(this,L_)&&clearTimeout(Q(this,L_)),Q(this,j_)!==this.CLOSED&&(Q(this,z_)&&Q(this,z_).abort(),$(this,j_,this.CLOSED),$(this,z_,void 0))}};j_=new WeakMap,M_=new WeakMap,N_=new WeakMap,P_=new WeakMap,F_=new WeakMap,I_=new WeakMap,L_=new WeakMap,R_=new WeakMap,z_=new WeakMap,B_=new WeakMap,V_=new WeakMap,H_=new WeakMap,U_=new WeakMap,W_=new WeakSet,G_=function(){$(this,j_,this.CONNECTING),$(this,z_,new AbortController),Q(this,F_)(Q(this,M_),A_(this,W_,J_).call(this)).then(Q(this,K_)).catch(Q(this,q_))},K_=new WeakMap,q_=new WeakMap,J_=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...Q(this,R_)?{"Last-Event-ID":Q(this,R_)}:void 0},cache:`no-store`,signal:Q(this,z_)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},Y_=new WeakMap,X_=new WeakMap,Z_=function(e,t){var n;Q(this,j_)!==this.CLOSED&&$(this,j_,this.CLOSED);let r=new C_(`error`,{code:t,message:e});(n=Q(this,V_))==null||n.call(this,r),this.dispatchEvent(r)},Q_=function(e,t){var n;if(Q(this,j_)===this.CLOSED)return;$(this,j_,this.CONNECTING);let r=new C_(`error`,{code:t,message:e});(n=Q(this,V_))==null||n.call(this,r),this.dispatchEvent(r),$(this,L_,setTimeout(Q(this,$_),Q(this,I_)))},$_=new WeakMap,ev.CONNECTING=0,ev.OPEN=1,ev.CLOSED=2;function tv(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}var nv=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=x_({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},rv=class extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.OAuthClientFlowError`})}static[Symbol.hasInstance](e){return $d(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $d(this,e)}constructor(e){super(e),this.name=new.target.name,Qd(this,new.target)}},iv=class extends rv{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.IssuerMismatchError`})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e===`metadata`?`authorization server metadata (RFC 8414 §3.3)`:`authorization response (RFC 9207)`}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`),this.kind=e,this.expected=t,this.received=n}},av=class extends rv{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}},ov=class extends rv{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}},sv=class extends rv{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}},cv=class extends rv{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 lv(e,t,n){if(e!==void 0)return e.issuer===void 0?(n?.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):uv(e.issuer,t)?e:void 0}function uv(e,t){return e===t||e.endsWith(`/`)&&e.slice(0,-1)===t||t.endsWith(`/`)&&t.slice(0,-1)===e}function dv(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function fv(e,t,n){let{resourceMetadataUrl:r,scope:i}=Rv(t.response);if(await Nv(e,{serverUrl:t.serverUrl,resourceMetadataUrl:r,scope:i,fetchFn:t.fetchFn,...n})!==`AUTHORIZED`)throw new mv}function pv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>fv(e,n,t)}}var mv=class extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.UnauthorizedError`})}static[Symbol.hasInstance](e){return $d(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $d(this,e)}constructor(e){super(e??`Unauthorized`),this.name=`UnauthorizedError`,Qd(this,new.target)}};function hv(e){return e?.authorization_response_iss_parameter_supported===!0}function gv({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new iv(`authorization_response`,t,void 0);return}if(e!==t)throw new iv(`authorization_response`,t,e)}}function _v(...e){let t=new Set;for(let n of e){if(!n)continue;for(let e of n.split(/\s+/))e&&t.add(e)}return t.size>0?[...t].join(` `):void 0}function vv(e,t){if(!e)return!1;let n=new Set((t??``).split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!n.has(t))return!0;return!1}async function yv(e,t,n,r,i){if(typeof e==`string`)return{authorizationCode:e,iss:t};let a=e.get(`iss`)??void 0,o=e.get(`code`);if(o)return{authorizationCode:o,iss:a};let s=(await n.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await Jv(r,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new mv(`Authorization callback failed and the issuer could not be verified`);gv({iss:a,expectedIssuer:s.issuer,issParameterSupported:hv(s)});let c=e.get(`error`);throw c?new tf(c,e.get(`error_description`)??c,e.get(`error_uri`)??void 0):new mv("Authorization callback contained neither `code` nor `error`")}function bv(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const xv=`code`,Sv=`S256`;function Cv(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&bv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function wv(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Tv(i,a,n);return;case`client_secret_post`:Ev(i,a,r);return;case`none`:Dv(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Tv(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ev(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Dv(e,t){t.set(`client_id`,e)}function Ov(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function kv(e){let t=new URL(String(e));if(t.protocol!==`https:`&&!Ov(t.hostname))throw new ov(t.href);return t}function Av(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{continue}if(e.protocol!==`http:`&&e.protocol!==`https:`||Ov(e.hostname))return`native`}return`web`}function jv(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??Av(t.redirect_uris)}}async function Mv(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=kd.parse(JSON.parse(n));return tf.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new tf(ef.ServerError,r)}}async function Nv(e,t){try{return await Fv(e,t)}catch(n){if(n instanceof tf){if(n.code===ef.InvalidClient||n.code===ef.UnauthorizedClient)return await e.invalidateCredentials?.(`client`),await e.invalidateCredentials?.(`tokens`),await Fv(e,t);if(n.code===ef.InvalidGrant)return await e.invalidateCredentials?.(`tokens`),await Fv(e,t)}throw n}}function Pv(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function Fv(e,{serverUrl:t,authorizationCode:n,iss:r,scope:i,resourceMetadataUrl:a,fetchFn:o,skipIssuerMetadataValidation:s,forceReauthorization:c}){let l=jv(e),u=await e.discoveryState?.(),d,f,p,m,h=a;if(!h&&u?.resourceMetadataUrl&&(h=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(f=u.authorizationServerUrl,d=u.resourceMetadata,p=u.authorizationServerMetadata??await qv(f,{fetchFn:o,skipIssuerValidation:s}),!d)try{d=await Bv(t,{resourceMetadataUrl:h},o)}catch(e){if(e instanceof TypeError)throw e}(p!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p})}else{let e=await Jv(t,{resourceMetadataUrl:h,fetchFn:o,skipIssuerMetadataValidation:s});f=e.authorizationServerUrl,p=e.authorizationServerMetadata,d=e.resourceMetadata,m={authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p}}let g=p?.issuer??String(f),_={issuer:g};if(await e.saveAuthorizationServerUrl?.(g),n!==void 0){let t=u?.authorizationServerMetadata?.issuer??u?.authorizationServerUrl;if(t===void 0){if(e.saveDiscoveryState!==void 0)throw new sv(`discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier`,g);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) — see docs/migration/upgrade-to-v2.md §SEP-2352.`)}else if(!uv(t,g))throw new sv(t,g)}m&&await e.saveDiscoveryState?.(m);let v=await Lv(t,e,d);v&&await e.saveResourceUrl?.(String(v));let y=Pv({requestedScope:i,resourceMetadata:d,authServerMetadata:p,clientMetadata:e.clientMetadata}),b=await Promise.resolve(e.clientInformation(_)),x=lv(b,g,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&b?.issuer&&e.saveClientInformation===void 0)throw new sv(b.issuer,g);if(x&&x.issuer===void 0&&(x={...x,issuer:g},await e.saveClientInformation?.(x,_)),!x){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=p?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!Iv(r))throw new tf(ef.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)x={client_id:r,issuer:g},await e.saveClientInformation?.(x,_);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);x={...await ty(f,{metadata:p,clientMetadata:l,scope:y,fetchFn:o}),issuer:g},await e.saveClientInformation(x,_)}}let ee=!e.redirectUrl;if(n!==void 0||ee){n!==void 0&&gv({iss:r,expectedIssuer:p?.issuer,issParameterSupported:hv(p)});let t=await ey(e,f,{metadata:p,resource:v,authorizationCode:n,iss:r,scope:y,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let te=lv(await e.tokens(_),g);if(te&&te.issuer===void 0&&(te={...te,issuer:g},await e.saveTokens(te,_)),te?.refresh_token&&!c)try{let t=await $v(f,{metadata:p,clientInformation:x,refreshToken:te.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}catch(e){if(e instanceof ov||!(!(e instanceof tf)||e.code===ef.ServerError))throw e}let ne=e.state?await e.state():void 0,{authorizationUrl:re,codeVerifier:ie}=await Yv(f,{metadata:p,clientInformation:x,state:ne,redirectUrl:e.redirectUrl,scope:y,resource:v});return await e.saveCodeVerifier(ie),await e.redirectToAuthorization(re),`REDIRECT`}function Iv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Lv(e,t,n){let r=rf(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!af({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Rv(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n?.toLowerCase()!==`bearer`||!r)return{};let i=zv(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=zv(e,`scope`)||void 0,s=zv(e,`error`)||void 0,c=zv(e,`error_description`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}}function zv(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}async function Bv(e,t,n=fetch){let r=await Gv(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Cd.parse(await r.json())}async function Vv(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(!(r instanceof TypeError)||!0)throw r;if(t)try{return await n(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function Hv(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Uv(e,t,n=fetch){return await Vv(e,{"MCP-Protocol-Version":t},n)}function Wv(e,t){return e?t===`/`?!1:e.status>=400&&e.status<500||e.status===502:!0}async function Gv(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??lc,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Hv(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Uv(o,a,n);return!r?.metadataUrl&&Wv(s,i.pathname)&&(s=await Uv(new URL(`/.well-known/${t}`,i),a,n)),s}function Kv(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.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`}),r}async function qv(e,{fetchFn:t=fetch,protocolVersion:n=lc,skipIssuerValidation:r=!1}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},a=Kv(e);for(let{url:n,type:o}of a){let a=await Vv(n,i,t);if(!a)continue;if(!a.ok){if(await a.text?.().catch(()=>{}),a.status>=400&&a.status<500||a.status===502)continue;throw Error(`HTTP ${a.status} trying to load ${o===`oauth`?`OAuth`:`OpenID provider`} metadata from ${n}`)}let s=o===`oauth`?wd.parse(await a.json()):Ed.parse(await a.json());if(!r){let t=typeof e==`string`?e:e.href;if(!(s.issuer===t||t.endsWith(`/`)&&s.issuer===t.slice(0,-1)))throw new iv(`metadata`,t,s.issuer)}return s}}async function Jv(e,t){let n,r;try{n=await Bv(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await qv(r,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function Yv(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(xv))throw Error(`Incompatible auth server: does not support response type ${xv}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Sv))throw Error(`Incompatible auth server: does not support code challenge method ${Sv}`)}else s=new URL(`/authorize`,e);let c=await v_(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,xv),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Sv),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function Xv(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Zv(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=kv(t?.token_endpoint??new URL(`/token`,e)),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&wv(Cv(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Mv(l);let u=await l.json();try{return Dd.parse(u)}catch(e){throw typeof u==`object`&&u&&`error`in u?await Mv(JSON.stringify(u)):e}}async function Qv(e,{metadata:t,clientInformation:n,authorizationCode:r,iss:i,codeVerifier:a,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){return gv({iss:i,expectedIssuer:t?.issuer,issParameterSupported:hv(t)}),Zv(e,{metadata:t,tokenRequestParams:Xv(r,a,o),clientInformation:n,addClientAuthentication:c,resource:s,fetchFn:l})}async function $v(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Zv(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function ey(e,t,{metadata:n,resource:r,authorizationCode:i,iss:a,scope:o,fetchFn:s}={}){i!==void 0&&gv({iss:a,expectedIssuer:n?.issuer,issParameterSupported:hv(n)});let c=o??e.clientMetadata.scope,l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);l=Xv(i,await e.codeVerifier(),e.redirectUrl)}let u=await e.clientInformation({issuer:n?.issuer??String(t)});return Zv(t,{metadata:n,tokenRequestParams:l,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:s})}async function ty(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o={...n,...r===void 0?{}:{scope:r}},s=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw new av({status:s.status,body:await s.text(),submittedMetadata:o});return Nd.parse(await s.json())}const ny=new Set([`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`server/discover`]);var ry=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(iy(e))}set(e,t){let n=iy(e),r=ny.has(e.method),i=!this._entries.has(n);if(!r&&i&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let e of this._entries.keys())if(!ny.has(e.slice(0,e.indexOf(`\0`)))){this._entries.delete(e),this._cappedSize--;break}}let a=++this._stamp;return this._entries.set(n,{...t,stamp:a}),i&&!r&&this._cappedSize++,a}delete(e){this._entries.delete(iy(e))&&!ny.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,n=ny.has(e);for(let e of this._entries.keys())e.startsWith(t)&&(this._entries.delete(e),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function iy(e){return`${e.method}\0${JSON.stringify([e.partition??``,e.params??``])}`}function ay(e,t){return t===void 0?e:`${e}\0${t}`}var oy=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity=``;constructor(e,t,n=()=>{},r=``,i=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=r,this._now=i}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e===`public`?``:this._cachePartition])}async _probe(e,t){let n={method:e,params:t??``},r=this._partitionFor(`private`),i=await this._store.get({...n,partition:r});if(i!==void 0)return i;let a=this._partitionFor(`public`);if(a===r)return;let o=await this._store.get({...n,partition:a});return o?.scope===`public`?o:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,``)}async _deleteBoth(e,t){let n=this._partitionFor(`private`),r=this._partitionFor(`public`);try{await this._store.delete({method:e,params:t,partition:n})}catch(e){this._reportError(e)}if(r!==n)try{await this._store.delete({method:e,params:t,partition:r})}catch(e){this._reportError(e)}}async evictKey(e,t){let n=ay(e,t),r=this._evictionGeneration.get(n);r!==void 0&&this._evictionGeneration.set(n,r+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let n=ay(e,t),r=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,r),r}async write(e,t,n,r){if((this._evictionGeneration.get(ay(e,r?.params))??0)!==n)return;let i=r?.params??``,a=this._partitionFor(`private`),o=this._partitionFor(`public`),s=(r?.scope??`private`)===`public`?o:a;try{await this._store.set({method:e,params:i,partition:s},{value:sy(t),expiresAt:r?.expiresAt,scope:r?.scope})}catch(e){this._reportError(e)}if(o!==a)try{await this._store.delete({method:e,params:i,partition:s===a?o:a})}catch(e){this._reportError(e)}}async read(e,t){let n=await this._probe(e,t);if(!(n?.expiresAt===void 0||!(n.expiresAt>this.now())))try{let e=JSON.parse(n.value);if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`cached document is not an object`);return{value:e}}catch(n){this._reportError(n),await this._deleteBoth(e,t??``);return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=``}async toolDefinition(e){let t=await this._probe(`tools/list`);if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let e=this._decodeListTools(t),n=new Map;if(e!==void 0)for(let t of e.tools)n.set(t.name,t);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let n=await this._probe(`tools/list`);if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){let e=this._decodeListTools(n)??{tools:[]},r=new Map;for(let n of e.tools){let e=t(n);e!==void 0&&r.set(n.name,e)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(e=>typeof e==`object`&&!!e))throw TypeError(`cached tools/list document has a malformed tools array`);return t}catch(e){this._reportError(e);return}}};function sy(e){let t;try{t=JSON.stringify(e)}catch(e){throw TypeError(`cache value is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`string`)throw TypeError(`cache value is not JSON-serializable: it has no JSON representation`);return t}const cy=Symbol.for(`mcp.authSeamEscape`);function ly(e){if(typeof e==`object`&&e||typeof e==`function`)try{Object.defineProperty(e,cy,{value:!0,configurable:!0})}catch{}return e}function uy(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&e[cy]===!0}const dy=new Set([-32001,-32020,-32021]);function fy(e,t){switch(e.kind){case`result`:return py(e.result,t);case`rpc-error`:return my(e,t);case`http-error`:return hy(e,t);case`network-error`:return gy(e.error,t);case`auth-required`:return{kind:`error`,error:e.error};case`closed`:return t.transportKind===`stdio`?{kind:`legacy`}:gy(Error(`Connection closed during the version negotiation probe`),t);case`timeout`:return t.transportKind===`stdio`?{kind:`legacy`}:{kind:`error`,error:new q(K.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function py(e,t){let n=Ap(kp).validateResult(`server/discover`,e);if(!n.ok)return{kind:`legacy`};let r=n.value.supportedVersions,i=t.clientModernVersions.find(e=>r.includes(e));return i===void 0?t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:new Zf({supported:[...r],requested:t.requestedVersion})}:{kind:`modern`,version:i,discover:n.value}}function my(e,t){let{code:n,message:r,data:i}=e;if(n===-32022){let e=yy(i);if(e===void 0)return{kind:`legacy`};let n=new Zf({supported:e,requested:by(i)??t.requestedVersion},r),a=df(e),o=t.clientModernVersions.find(e=>a.includes(e));return o===void 0?a.length>0?{kind:`error`,error:n}:t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:n}:{kind:`corrective`,version:o,error:n}}return dy.has(n),{kind:`legacy`}}function hy(e,t){if(e.status===401||e.status===403){let t=e.status===403;return{kind:`error`,error:new nf(t?K.ClientHttpForbidden:K.ClientHttpAuthentication,`Version negotiation failed: ${t?`the server denied access (HTTP 403)`:`the server requires authorization (HTTP 401)`}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:`error`,error:new nf(K.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let n=xy(e.body);return n===void 0?{kind:`legacy`}:my(n,t)}function gy(e,t){return t.environment===`browser`&&_y(e)?{kind:`legacy`}:{kind:`error`,error:new q(K.EraNegotiationFailed,`Version negotiation probe failed: ${vy(e)}`,{cause:e})}}function _y(e){return e instanceof TypeError||e instanceof Error&&e.name===`TypeError`}function vy(e){return e instanceof Error?e.message:String(e)}function yy(e){if(typeof e!=`object`||!e)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(e=>typeof e==`string`)))return t}function by(e){if(typeof e!=`object`||!e)return;let t=e.requested;return typeof t==`string`?t:void 0}function xy(e){if(e===void 0||e===``)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let{code:r,message:i,data:a}=n;if(typeof r==`number`)return{code:r,message:typeof i==`string`?i:``,data:a}}function Sy(e,t){let n=e?.mode??`legacy`;if(n===`legacy`)return{kind:`legacy`};let r=e?.probe??{};if(typeof n==`object`){if(!lf(n.pin))throw TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:`pin`,version:n.pin,probe:r}}let i=t?df(t):[];return{kind:`auto`,modernVersions:i.length>0?i:[...cf],fallbackAvailable:t?uf(t).length>0:!0,probe:r}}function Cy(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?`browser`:`node`}function wy(e){return`stderr`in e&&`pid`in e?`stdio`:`http`}var Ty=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(e){this._transport=e,this._savedOnMessage=e.onmessage,this._savedOnError=e.onerror,this._savedOnClose=e.onclose}static async open(t){let n=new e(t);t.onmessage=e=>{let t=n._pending;if(t!==void 0&&(Rp(e)||zp(e))&&e.id===t.id){n._pending=void 0,Rp(e)?t.resolve({kind:`response`,result:e.result}):t.resolve({kind:`response`,error:e.error});return}},t.onerror=e=>{n._savedOnError?.(e)},t.onclose=()=>{let e=n._pending;e!==void 0&&(n._pending=void 0,e.resolve({kind:`closed`})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(e){throw n.detach(),e}return n}async exchange(e,t){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),this._pending?.id===n&&(this._pending=void 0),r(e))},o=setTimeout(()=>a({kind:`timeout`}),t);this._pending={id:n,resolve:a},this._transport.send(e(n)).catch(e=>a({kind:`send-error`,error:e}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let e=this._savedOnClose,t=this._transport,n=!1,r=()=>{if(!n){n=!0;return}e()};t.onclose=r,Ey.set(t,()=>{t.onclose===r&&(t.onclose=e)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let e=this._transport,t=e.start,n=!0;e.start=async function(){if(n){n=!1,e.start=t;return}return t.call(e)}}};const Ey=new WeakMap;function Dy(e){let t=Ey.get(e);Ey.delete(e),t?.()}function Oy(e,t,n,r){return{jsonrpc:`2.0`,id:e,method:`server/discover`,params:{_meta:Ap(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:r})}}}function ky(e,t){switch(e.kind){case`response`:return e.error===void 0?{kind:`result`,result:e.result}:{kind:`rpc-error`,...e.error};case`send-error`:{let t=e.error;if(uy(t)||t instanceof mv||t instanceof Error&&t.name===`UnauthorizedError`)return{kind:`auth-required`,error:t};if(t instanceof nf){let e=t.data?.text;return{kind:`http-error`,status:t.data.status,body:typeof e==`string`?e:void 0,statusText:t.data.statusText}}return{kind:`network-error`,error:t}}case`closed`:return{kind:`closed`};case`timeout`:return{kind:`timeout`,timeoutMs:t}}}async function Ay(e,t){let n=e.probe.timeoutMs??t.defaultTimeoutMs,r=Math.max(0,e.probe.maxRetries??0),i=e.kind===`pin`?[e.version]:e.modernVersions,a=e.kind===`auto`&&e.fallbackAvailable,o=await Ty.open(t.transport),s=async()=>{let s=i[0],c=!1,l=r;for(;;){let r=await o.exchange(e=>Oy(e,s,t.clientInfo,t.capabilities),n);if(r.kind===`timeout`&&l>0){l--;continue}let u=ky(r,n),d=fy(u,{clientModernVersions:i,requestedVersion:s,fallbackAvailable:a,environment:t.environment,transportKind:t.transportKind});switch(d.kind){case`modern`:return{era:`modern`,version:d.version,discover:d.discover};case`corrective`:if(c)throw d.error;c=!0,s=d.version;continue;case`legacy`:{let n=u.kind===`closed`?`the connection closed during the server/discover probe`:void 0;if(e.kind===`pin`)throw new q(K.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${n} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new q(K.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to`:`Version negotiation failed: ${n} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(n!==void 0&&t.disposableProbe!==!0)throw new q(K.EraNegotiationFailed,`Version negotiation failed: ${n} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:`legacy`}}case`error`:throw d.error}}},c;try{c=await s()}catch(e){throw o.detach(),e}return o.release(),c}function jy(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,`_dispose`))return;let n=e._serverParams;return typeof n==`object`&&n&&typeof n.command==`string`?n:void 0}async function My(e,t,n,r){let i=t.constructor,a=new i({...n,stderr:`ignore`}),o=t.close,s=!1,c,l=new Promise((e,t)=>{c=()=>t(Ny())});t.close=async function(){return s=!0,c?.(),o.call(t)};let u;try{let t=Ay(e,{...r,transport:a,transportKind:`stdio`,disposableProbe:!0});t.catch(()=>{}),u=await Promise.race([t,l])}finally{await Py(a),t.close=o}if(s)throw Ny();return u}function Ny(){return new q(K.EraNegotiationFailed,`Version negotiation failed: the transport was closed during the server/discover probe`)}async function Py(e){try{let t=e._dispose;await(typeof t==`function`?t.call(e):e.close())}catch{}}function Fy(e){let t=e._meta?.[mc];return Vm.Implementation(t)?t:void 0}function Iy(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&Iy(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&Iy(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&Iy(n,t)}}function Ly(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}function Ry(e){if(typeof e==`object`&&e&&(e.kind===`legacy`&&!(`supportedVersions`in e)&&!(`discover`in e)||e.kind===`modern`&&tl.safeParse(e.discover).success))return e;throw new q(K.EraNegotiationFailed,`connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }`)}const zy={"notifications/tools/list_changed":[`tools/list`],"notifications/prompts/list_changed":[`prompts/list`],"notifications/resources/list_changed":[`resources/list`,`resources/templates/list`]};var By=class extends Xm{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new q(K.ConnectionClosed,`subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new f_,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Am(t?.inputRequired),this._cache=new oy(t?.responseCacheStore??new ry,t?.responseCacheStore!==void 0,e=>this._reportStoreError(e),t?.cachePartition??``),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??64,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&lf(this._negotiatedProtocolVersion)&&Ip(e))return`drop`}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?ah({getRequestHandler:e=>this._getRequestHandler(e),buildContext:e=>this.buildContext(e,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new q(K.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:`input_required`,method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools(void 0,{cacheMode:`refresh`})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:`refresh`})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources(void 0,{cacheMode:`refresh`})).resources)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Qm(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error(`Cannot configure version negotiation after connecting to transport`);this._versionNegotiation=e}_wrapHandler(e,t){return e===`elicitation/create`?async(e,n)=>{let r=Ap(this._negotiatedProtocolVersion),i=r.validateRequest(`elicitation/create`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`elicitation/create`,e)),!i.ok)throw new Y(i.reason===`not-in-era`?J.InternalError:J.InvalidParams,i.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??`form`;let{supportsFormMode:o,supportsUrlMode:s}=Ly(this._capabilities.elicitation);if(a.mode===`form`&&!o)throw new Y(J.InvalidParams,`Client does not support form-mode elicitation requests`);if(a.mode===`url`&&!s)throw new Y(J.InvalidParams,`Client does not support URL-mode elicitation requests`);let c=await t(e,n),l=r.validateResult(`elicitation/create`,c);if(!l.ok&&l.reason===`not-in-era`&&(l=r.validateInputResponse(`elicitation/create`,c)),!l.ok)throw new Y(l.reason===`not-in-era`?J.InternalError:J.InvalidParams,l.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation result: ${l.message}`);let u=l.value,d=a.mode===`form`?a.requestedSchema:void 0;if(a.mode===`form`&&u.action===`accept`&&u.content&&d&&this._capabilities.elicitation?.form?.applyDefaults)try{Iy(d,u.content)}catch{}return u}:e===`sampling/createMessage`?async(e,n)=>{let r=Ap(this._negotiatedProtocolVersion),i=r.validateRequest(`sampling/createMessage`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`sampling/createMessage`,e)),!i.ok)throw new Y(i.reason===`not-in-era`?J.InternalError:J.InvalidParams,i.reason===`not-in-era`?`No wire schema for sampling/createMessage in the resolved era`:`Invalid sampling request: ${i.message}`);let{params:a}=i.value,o=await t(e,n),s=!!(a.tools||a.toolChoice),c=r.samplingResultVariant(s,o);if(!c.ok&&c.reason===`not-in-era`&&(c=r.validateInputResponse(`sampling/createMessage`,o)),!c.ok)throw new Y(c.reason===`not-in-era`?J.InternalError:J.InvalidParams,c.reason===`not-in-era`?`No result schema for sampling/createMessage in the resolved era`:`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new q(K.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Ry(t.prior),t);let n=Sy(this._versionNegotiation,this._supportedProtocolVersionsOption);return n.kind===`legacy`?this._connectPlainLegacy(e,t):this._connectNegotiated(e,n,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion?.(t);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=uf(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new q(K.EraNegotiationFailed,`Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version`);let i=await this.request({method:`initialize`,params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(i.protocolVersion),this._instructions=i.instructions,await this.notification({method:`notifications/initialized`}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(e){throw this.close(),e}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(t);return}this._resetConnectionState();let r;try{let i=wy(e),a={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Cy(),defaultTimeoutMs:n?.timeout??Um},o=i===`stdio`?jy(e):void 0;r=o===void 0?await Ay(t,{...a,transport:e,transportKind:i}):await My(t,e,o,a)}catch(t){throw await e.close().catch(()=>{}),Dy(e),t}if(Dy(e),await super.connect(e),r.era===`legacy`){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=Fy(r.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion&&e.setProtocolVersion(r.version),this._listChangedConfig){let e=this._listChangedConfig,t=this._serverCapabilities,r={...e.tools&&t?.tools?.listChanged&&{tools:e.tools},...e.prompts&&t?.prompts?.listChanged&&{prompts:e.prompts},...e.resources&&t?.resources?.listChanged&&{resources:e.resources}},i=!0;try{this._setupListChangedHandlers(r)}catch(e){i=!1,this.onerror?.(e instanceof Error?e:Error(String(e)))}let a=i?{...r.tools&&{toolsListChanged:!0},...r.prompts&&{promptsListChanged:!0},...r.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(a).length>0){let e=new AbortController,t=()=>e.abort(n?.signal?.reason);n?.signal?.aborted&&t(),n?.signal?.addEventListener(`abort`,t);try{this._autoOpenedSubscription=await this.listen(a,{timeout:n?.timeout,signal:e.signal})}catch(e){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),e;this.onerror?.(e instanceof Error?e:Error(String(e)))}finally{n?.signal?.removeEventListener(`abort`,t)}}}}async _connectFromPrior(e,t,n){if(t.kind===`legacy`)return this._connectPlainLegacy(e,n);let r=t.discover;this._resetConnectionState();let i=this._supportedProtocolVersionsOption,a=(i&&df(i).length>0?df(i):cf).find(e=>r.supportedVersions.includes(e));if(a===void 0)throw new q(K.EraNegotiationFailed,`connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.`);if(await super.connect(e),this._discoverResult=r,this._serverCapabilities=r.capabilities,this._serverVersion=Fy(r),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.instructions,this._negotiatedProtocolVersion=a,e.setProtocolVersion?.(a),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t===void 0?e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`:`${t.name}@${t.version}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return lf(e)?`modern`:`legacy`}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new q(K.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new q(K.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new q(K.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new q(K.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new q(K.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new q(K.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`server/discover`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw new q(K.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new q(K.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new q(K.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new q(K.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case`ping`:break}}async ping(e){return this.request({method:`ping`},e)}async discover(e){let t=await this._requestWithSchema({method:`server/discover`},tl,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:`completion/complete`,params:e},t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:`prompts/list`,params:e},t);let n=await this._serveFromCache(`prompts/list`,void 0,t);return n===void 0?this._listAllPages(`prompts/list`,e,t,(e,t)=>e.prompts.push(...t.prompts)):n}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]};if(e?.cursor!==void 0)return this.request({method:`resources/list`,params:e},t);let n=await this._serveFromCache(`resources/list`,void 0,t);return n===void 0?this._listAllPages(`resources/list`,e,t,(e,t)=>e.resources.push(...t.resources)):n}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:`resources/templates/list`,params:e},t);let n=await this._serveFromCache(`resources/templates/list`,void 0,t);return n===void 0?this._listAllPages(`resources/templates/list`,e,t,(e,t)=>e.resourceTemplates.push(...t.resourceTemplates)):n}async _listAllPages(e,t,n,r,i){let a=n?.cacheMode===`bypass`,o=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},n),c=s.nextCursor,l=new Set,u=1;for(;c!==void 0&&!l.has(c);){if(this._listMaxPages!==0&&u>=this._listMaxPages)throw new q(K.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});l.add(c);let i=await this.request({method:e,params:{...t,cursor:c}},n);r(s,i),c=i.nextCursor,u++}return delete s.nextCursor,i?.(s),a||await this._cache.write(e,s,o,this._freshness(s)),s}_freshness(e,t){let n=e,r=typeof n.ttlMs==`number`?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope===`public`?`public`:`private`;return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),864e5),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode===`bypass`||n?.cacheMode===`refresh`)return;let r=await this._cache.read(e,t).catch(e=>void this._reportStoreError(e));if(r!==void 0){if(n?.signal?.aborted){let e=n.signal.reason;throw e instanceof q?e:new q(K.RequestTimeout,String(e))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(e){return{ok:!1,compileError:e}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Kp(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache(`resources/read`,e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration(`resources/read`,e.uri),i=await this.request({method:`resources/read`,params:e},t);if(t?.cacheMode!==`bypass`){let n=this._freshness(i,e.uri);n.expiresAt>this._cache.now()?await this._cache.write(`resources/read`,i,r,n):t?.cacheMode===`refresh`&&await this._cache.evictKey(`resources/read`,e.uri)}return i}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},t)}async listen(e,t){if(this.transport===void 0)throw new q(K.NotConnected,`Not connected`);let n=this._negotiatedProtocolVersion;if(n===void 0||!lf(n))throw new q(K.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??`none`}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:`subscriptions/listen`,protocolVersion:n});if(t?.signal?.aborted){let e=t.signal.reason;throw e instanceof q?e:new q(K.RequestTimeout,String(e))}let r=new AbortController,i=`listen:${this._nextListenId++}`,a=`opening`,o,s,c,l,u=new Promise((e,t)=>{c=e,l=t}),d,f=new Promise(e=>{d=e}),p=e=>{if(a===`closed`)return;let n=a===`opening`;if(o!==void 0&&(clearTimeout(o),o=void 0),`ack`in e){a=`open`,c(e.ack);return}a=`closed`,s!==void 0&&t?.signal?.removeEventListener(`abort`,s),this._listenState.delete(i),r.abort(),d(e.cause),n&&l(e.error??new q(K.ConnectionClosed,`subscriptions/listen closed before the server acknowledged`))},m=async()=>{r.abort(),await this.notification({method:`notifications/cancelled`,params:{requestId:i}}).catch(()=>{})},h=async()=>{a!==`closed`&&(p({cause:`local`}),await m())};this._listenState.set(i,{settle:p});let g=t?.timeout??Um;if(o=setTimeout(()=>{p({cause:`remote`,error:new q(K.RequestTimeout,`subscriptions/listen ack timed out`,{timeout:g})}),m().catch(()=>{})},g),t?.signal){let e=t.signal;s=()=>{if(a===`closed`)return;let t=e.reason;p({cause:`local`,error:t instanceof Error?t:Error(String(t??`Aborted`))}),m().catch(()=>{})},e.addEventListener(`abort`,s,{once:!0})}let _={jsonrpc:`2.0`,id:i,method:`subscriptions/listen`,params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>p({cause:`remote`,error:Error(`subscriptions/listen: stream ended`)})})}catch(e){p({cause:`remote`,error:e instanceof Error?e:Error(String(e))})}return{honoredFilter:await u,close:h,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(zy,e.method)?zy[e.method]:void 0;if(e.method===`notifications/resources/updated`){let t=e.params?.uri;typeof t==`string`&&this._cache.evictKey(`resources/read`,t)}else if(n!==void 0)for(let e of n)this._cache.evict(e);if(e.method===`notifications/subscriptions/acknowledged`){let t=e.params?._meta?.[gc],n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){let t=this._wireCodec().validateNotification(`notifications/subscriptions/acknowledged`,e);n.settle({ack:t.ok?t.value.params.notifications:{}});return}}if(e.method===`notifications/cancelled`){let t=e.params?.requestId,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){n.settle({cause:`remote`,error:Error(`subscriptions/listen: server cancelled the subscription`)});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){zp(e)?n.settle({cause:`remote`,error:Y.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:`graceful`,error:new q(K.ConnectionClosed,`subscriptions/listen: server closed the subscription gracefully before acknowledging`)});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new q(K.ConnectionClosed,`Connection closed`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()===`modern`&&Cy()!==`browser`,r=async()=>{if(!n)return t;let r;try{r=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(e){this._reportStoreError(e)}if(!r?.valid||r.declarations.length===0)return t;let i=nm(r.declarations,e.arguments);return Object.keys(i).length===0?t:{...t,headers:{...t?.headers,...i}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)):this._compileOutputValidator(t.toolDefinition),a=()=>{if(i===void 0||i.ok)return;let t=i.compileError,n=(t instanceof Error?t.message:String(t)).slice(0,200);throw new Y(J.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${n}`)};a();let o;try{o=await this.request({method:`tools/call`,params:e},await r())}catch(s){let c=s instanceof Y&&s.code===-32020;if(!n||!c||t?.toolDefinition!==void 0)throw s;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:`refresh`};await this._cache.evict(`tools/list`),await this.listTools(void 0,l).catch(e=>this._reportStoreError(e)),i=await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)),a(),o=await this.request({method:`tools/call`,params:e},await r())}let s=i!==void 0&&i.ok?i.validator:void 0;if(s){if(o.structuredContent===void 0&&!o.isError)throw new Y(J.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent!==void 0&&!o.isError)try{let e=s(o.structuredContent);if(!e.valid)throw new Y(J.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Y?e:new Y(J.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:`tools/list`,params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let n=await this._serveFromCache(`tools/list`,void 0,t);return n===void 0?this._listAllPages(`tools/list`,e,t,(e,t)=>e.tools.push(...t.tools),e=>this._excludeInvalidXMcpHeaderTools(e)):n}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!==`modern`||!this.transport||wy(this.transport)===`stdio`)return;let t=e.tools.filter(e=>{let t=Kp(e.inputSchema);return t.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${e.name}' from tools/list: invalid x-mcp-header declaration — ${t.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,r){let i=rm(du,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},Vy=class extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.SseError`})}static[Symbol.hasInstance](e){return $d(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $d(this,e)}constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n,Qd(this,new.target)}},Hy=class{_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,dv(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=pv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ph(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(e){throw ly(e)}t&&(e.Authorization=`Bearer ${t}`),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=fh(this._requestInit?.headers);return new Headers({...e,...n})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new ev(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});if(i.status===401&&(this._last401Response=i,i.headers.has(`www-authenticate`))){let{resourceMetadataUrl:e,scope:t}=Rv(i);this._resourceMetadataUrl=e,this._scope=t}return i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(e.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let e=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:e,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,n),e=>{ly(e),this.onerror?.(e),n(e)});return}let e=ly(new mv);n(e),this.onerror?.(e);return}let r=new Vy(e.code,e.message,e);n(r),this.onerror?.(r)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{let r=e;try{if(this._endpoint=new URL(r.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t=e,n;try{n=Fc.parse(JSON.parse(t.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(n)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e,t){if(!this._oauthProvider)throw new mv(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await yv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Nv(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new mv(`Failed to authorize`)}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new q(K.NotConnected,`Not connected`);try{let n=await this._commonHeaders();n.set(`content-type`,`application/json`);let r={...this._requestInit,method:`POST`,headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._endpoint,r);if(!i.ok){if(i.status===401&&this._authProvider){if(i.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=Rv(i);this._resourceMetadataUrl=e,this._scope=t}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:i,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw ly(e)}return await i.text?.().catch(()=>{}),this._send(e,!0)}throw await i.text?.().catch(()=>{}),ly(t?new nf(K.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:i.statusText}):new mv)}let n=await i.text?.().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${n}`)}await i.text?.().catch(()=>{})}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}};const Uy={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Wy=new Set([`authorization`,`content-type`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`mcp-session-id`]);function Gy(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;let r=()=>{e.removeEventListener(`abort`,i),t.removeEventListener(`abort`,a)};function i(){r(),n.abort(e.reason)}function a(){r(),n.abort(t.reason)}return e.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`abort`,a,{once:!0}),n.signal}var Ky=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,dv(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=pv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ph(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Uy,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??`reauthorize`,this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??1)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(e){throw ly(e)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope===`throw`||!this._oauthProvider)throw new cv({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new nf(K.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??`Forbidden`,text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let n=await this._oauthProvider.tokens(),r=_v(this._scope,n?.scope,e.scope);this._scope=r;let i=vv(r,n?.scope);return Nv(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(e){throw ly(e)}t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=fh(this._requestInit?.headers);return new Headers({...e,...n})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Ip(t))return;let n=t.params?._meta?.[fc];if(typeof n!=`string`)return;e.set(`mcp-protocol-version`,n),e.set(`mcp-method`,t.method);let r=t.params,i=t.method===`resources/read`?typeof r?.uri==`string`?r.uri:void 0:typeof r?.name==`string`?r.name:void 0;i!==void 0&&e.set(`mcp-name`,em(i))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Ip(e))return!1;let t=e.params?._meta?.[fc];return typeof t==`string`&&lf(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `)),r&&a.set(`last-event-id`,r);let s=this._abortController?.signal,c=i!==void 0&&s!==void 0?Gy(s,i):i??s,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:a,signal:c});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=Rv(l);this._resourceMetadataUrl=e,this._scope=_v(this._scope,t)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw ly(e)}return await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n)}throw await l.text?.().catch(()=>{}),ly(t?new nf(K.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:l.statusText}):new mv)}if(l.status===403){let{resourceMetadataUrl:r,scope:i,error:a,errorDescription:o}=Rv(l);if(a===`insufficient_scope`){let a=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:r,errorDescription:o,statusText:l.statusText,text:a},n)!==`AUTHORIZED`)throw ly(new mv);return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new nf(K.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(n=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o}=t,s=()=>this._abortController?.signal.aborted===!0||a?.aborted===!0,c,l=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new nv({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(c=e.id,l=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Fc.parse(JSON.parse(e.data));(Rp(t)||zp(t))&&(u=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||l)&&!u&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0):s()||o?.()}catch(e){if(s())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||l)&&!u&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),o?.()}else o?.()}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new mv(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await yv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Nv(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new mv(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:a}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ip(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e));return}let o=await this._commonHeaders();this._applyBodyDerivedHeaders(o,e);let s=Array.isArray(e)?e.some(e=>Vp(e)):Vp(e);if(s&&o.delete(`mcp-session-id`),t?.headers!==void 0)for(let[e,n]of Object.entries(t.headers)){if(Wy.has(e.toLowerCase()))continue;o.set(e,n)}o.set(`content-type`,`application/json`);let c=[...o.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];o.set(`accept`,[...new Set(c)].join(`, `));let l=this._abortController?.signal,u=t?.requestSignal!==void 0&&l!==void 0?Gy(l,t.requestSignal):t?.requestSignal??l,d={...this._requestInit,method:`POST`,headers:o,body:JSON.stringify(e),signal:u},f=await(this._fetch??fetch)(this._url,d);if(s&&f.ok&&(this._sessionId=f.headers.get(`mcp-session-id`)||void 0),!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=Rv(f);this._resourceMetadataUrl=e,this._scope=_v(this._scope,t)}if(this._authProvider.onUnauthorized&&!n){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw ly(e)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,r)}throw await f.text?.().catch(()=>{}),ly(n?new nf(K.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:f.statusText}):new mv)}let i=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}=Rv(f);if(s===`insufficient_scope`){if(await this._stepUpAuthorize({scope:o,resourceMetadataUrl:a,errorDescription:c,statusText:f.statusText,text:i},r)!==`AUTHORIZED`)throw ly(new mv);return this._send(e,t,n,r+1)}}if(f.status===400&&typeof i==`string`&&this._isModernEnvelopedRequest(e))try{let t=Fc.parse(JSON.parse(i)),n=(Array.isArray(e)?e:[e]).filter(e=>Ip(e));if(zp(t)&&n.some(e=>e.id===t.id)){this.onmessage?.(t);return}}catch{}throw new nf(K.ClientHttpNotImplemented,`Error POSTing to endpoint: ${i}`,{status:f.status,statusText:f.statusText,text:i})}if(f.status===202){await f.text?.().catch(()=>{}),Hp(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let p=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),m=f.headers.get(`content-type`),h=ch(m);if(p)if(h===`text/event-stream`)this._handleSseStream(f.body,{onresumptiontoken:a,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h===`application/json`){let e=await f.json(),t=Array.isArray(e)?e.map(e=>Fc.parse(e)):[Fc.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await f.text?.().catch(()=>{}),new q(K.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await f.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new nf(K.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function qy(e){let t=typeof e==`string`?new URL(e):new URL(e.toString());return t.pathname.length>1&&t.pathname.endsWith(`/`)&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}export{ml as AnnotationsSchema,ql as AudioContentSchema,Hc as BaseMetadataSchema,Tc as BaseRequestParamsSchema,fl as BlobResourceContentsSchema,Ou as BooleanSchemaSchema,hc as CLIENT_CAPABILITIES_META_KEY,pc as CLIENT_INFO_META_KEY,cu as CallToolRequestParamsSchema,lu as CallToolRequestSchema,ou as CallToolResultSchema,md as CancelTaskRequestSchema,hd as CancelTaskResultSchema,Rc as CancelledNotificationParamsSchema,zc as CancelledNotificationSchema,By as Client,Jc as ClientCapabilitiesSchema,_d as ClientNotificationSchema,gd as ClientRequestSchema,vd as ClientResultSchema,Kc as ClientTasksCapabilitySchema,su as CompatibilityCallToolResultSchema,Yu as CompleteRequestParamsSchema,Xu as CompleteRequestSchema,Zu as CompleteResultSchema,Zl as ContentBlockSchema,wu as CreateMessageRequestParamsSchema,Tu as CreateMessageRequestSchema,Eu as CreateMessageResultSchema,Du as CreateMessageResultWithToolsSchema,ad as CreateTaskResultSchema,xc as CursorSchema,uc as DEFAULT_NEGOTIATED_PROTOCOL_VERSION,el as DiscoverRequestSchema,tl as DiscoverResultSchema,Bu as ElicitRequestFormParamsSchema,Hu as ElicitRequestParamsSchema,Uu as ElicitRequestSchema,Vu as ElicitRequestURLParamsSchema,Ku as ElicitResultSchema,Wu as ElicitationCompleteNotificationParamsSchema,Gu as ElicitationCompleteNotificationSchema,Yl as EmbeddedResourceSchema,Lc as EmptyResultSchema,Ru as EnumSchemaSchema,Ul as GetPromptRequestParamsSchema,Wl as GetPromptRequestSchema,$l as GetPromptResultSchema,ud as GetTaskPayloadRequestSchema,dd as GetTaskPayloadResultSchema,cd as GetTaskRequestSchema,ld as GetTaskResultSchema,Bc as IconSchema,Vc as IconsSchema,Od as IdJagTokenExchangeResponseSchema,Kl as ImageContentSchema,Uc as ImplementationSchema,Yc as InitializeRequestParamsSchema,Xc as InitializeRequestSchema,Qc as InitializeResultSchema,$c as InitializedNotificationSchema,yc as JSONArraySchema,H as JSONObjectSchema,Pc as JSONRPCErrorResponseSchema,Fc as JSONRPCMessageSchema,Mc as JSONRPCNotificationSchema,jc as JSONRPCRequestSchema,Ic as JSONRPCResponseSchema,Nc as JSONRPCResultResponseSchema,vc as JSONValueSchema,lc as LATEST_PROTOCOL_VERSION,_c as LOG_LEVEL_META_KEY,Nu as LegacyTitledEnumSchemaSchema,du as ListChangedOptionsBaseSchema,Vl as ListPromptsRequestSchema,Hl as ListPromptsResultSchema,yl as ListResourceTemplatesRequestSchema,bl as ListResourceTemplatesResultSchema,_l as ListResourcesRequestSchema,vl as ListResourcesResultSchema,$u as ListRootsRequestSchema,ed as ListRootsResultSchema,fd as ListTasksRequestSchema,pd as ListTasksResultSchema,iu as ListToolsRequestSchema,au as ListToolsResultSchema,fu as LoggingLevelSchema,hu as LoggingMessageNotificationParamsSchema,gu as LoggingMessageNotificationSchema,_u as ModelHintSchema,vu as ModelPreferencesSchema,Lu as MultiSelectEnumSchemaSchema,Oc as NotificationSchema,Dc as NotificationsParamsSchema,Au as NumberSchemaSchema,Nd as OAuthClientInformationFullSchema,Md as OAuthClientInformationSchema,jd as OAuthClientMetadataSchema,Pd as OAuthClientRegistrationErrorSchema,tf as OAuthError,ef as OAuthErrorCode,kd as OAuthErrorResponseSchema,wd as OAuthMetadataSchema,Cd as OAuthProtectedResourceMetadataSchema,Fd as OAuthTokenRevocationRequestSchema,Dd as OAuthTokensSchema,Ed as OpenIdProviderDiscoveryMetadataSchema,Td as OpenIdProviderMetadataSchema,fc as PROTOCOL_VERSION_META_KEY,ol as PaginatedRequestParamsSchema,sl as PaginatedRequestSchema,cl as PaginatedResultSchema,nl as PingRequestSchema,zu as PrimitiveSchemaDefinitionSchema,il as ProgressNotificationParamsSchema,al as ProgressNotificationSchema,rl as ProgressSchema,bc as ProgressTokenSchema,zl as PromptArgumentSchema,eu as PromptListChangedNotificationSchema,Ql as PromptMessageSchema,Ju as PromptReferenceSchema,Bl as PromptSchema,Y as ProtocolError,lh as ReadBuffer,Sl as ReadResourceRequestParamsSchema,Cl as ReadResourceRequestSchema,wl as ReadResourceResultSchema,Cc as RelatedTaskMetadataSchema,Ac as RequestIdSchema,wc as RequestMetaSchema,U as RequestSchema,ll as ResourceContentsSchema,Xl as ResourceLinkSchema,Tl as ResourceListChangedNotificationSchema,xl as ResourceRequestParamsSchema,hl as ResourceSchema,qu as ResourceTemplateReferenceSchema,gl as ResourceTemplateSchema,Ll as ResourceUpdatedNotificationParamsSchema,Rl as ResourceUpdatedNotificationSchema,kc as ResultMetaObjectSchema,W as ResultSchema,pl as RoleSchema,Qu as RootSchema,td as RootsListChangedNotificationSchema,mc as SERVER_INFO_META_KEY,Hy as SSEClientTransport,gc as SUBSCRIPTION_ID_META_KEY,dc as SUPPORTED_PROTOCOL_VERSIONS,xu as SamplingContentSchema,Su as SamplingMessageContentBlockSchema,Cu as SamplingMessageSchema,Zc as ServerCapabilitiesSchema,bd as ServerNotificationSchema,yd as ServerRequestSchema,xd as ServerResultSchema,qc as ServerTasksCapabilitySchema,pu as SetLevelRequestParamsSchema,mu as SetLevelRequestSchema,Pu as SingleSelectEnumSchemaSchema,Ky as StreamableHTTPClientTransport,ku as StringSchemaSchema,El as SubscribeRequestParamsSchema,Dl as SubscribeRequestSchema,Al as SubscriptionFilterSchema,Nl as SubscriptionsAcknowledgedNotificationParamsSchema,Pl as SubscriptionsAcknowledgedNotificationSchema,jl as SubscriptionsListenRequestParamsSchema,Ml as SubscriptionsListenRequestSchema,Fl as SubscriptionsListenResultMetaSchema,Il as SubscriptionsListenResultSchema,Ec as TaskAugmentedRequestParamsSchema,nd as TaskCreationParamsSchema,Sc as TaskMetadataSchema,id as TaskSchema,od as TaskStatusNotificationParamsSchema,sd as TaskStatusNotificationSchema,rd as TaskStatusSchema,Gl as TextContentSchema,ul as TextResourceContentsSchema,Iu as TitledMultiSelectEnumSchemaSchema,Mu as TitledSingleSelectEnumSchemaSchema,tu as ToolAnnotationsSchema,yu as ToolChoiceSchema,nu as ToolExecutionSchema,uu as ToolListChangedNotificationSchema,bu as ToolResultContentSchema,ru as ToolSchema,Jl as ToolUseContentSchema,mv as UnauthorizedError,Ol as UnsubscribeRequestParamsSchema,kl as UnsubscribeRequestSchema,Fu as UntitledMultiSelectEnumSchemaSchema,ju as UntitledSingleSelectEnumSchemaSchema,z as _enum,gs as _null,P as array,M as boolean,x_ as createParser,sc as date,oc as datetime,qv as discoverAuthorizationServerMetadata,Bv as discoverOAuthProtectedResourceMetadata,Es as discriminatedUnion,Uo as email,Qv as exchangeAuthorization,Os as intersection,$s as lazy,B as literal,I as looseObject,qy as normalizeUrl,j as number,F as object,V as optional,rc as preprocess,R as record,$v as refreshAuthorization,ty as registerClient,wo as safeParse,dh as serializeMessage,Yv as startAuthorization,k as string,vo as toJSONSchema,L as union,N as unknown,qo as url};
64
- //# sourceMappingURL=normalizeUrl-DoppHGlo.js.map
64
+ //# sourceMappingURL=normalizeUrl-DUUGubD4.js.map