@onyxsecurity/mcp-gateway 2.1.86 → 2.1.88
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/dist/bin/mcp-gateway.js +2 -2
- package/dist/{cli-DgVQp0-y.js → cli-CQM-ozC0.js} +2 -2
- package/dist/{cli-DgVQp0-y.js.map → cli-CQM-ozC0.js.map} +1 -1
- package/dist/{env-eBI3h67H.js → env-LzliFLsi.js} +1 -1
- package/dist/{env-C2921_jo.js → env-Zfu004Nj.js} +2 -2
- package/dist/{env-C2921_jo.js.map → env-Zfu004Nj.js.map} +1 -1
- package/dist/{helpers-BVKN1UT2.js → helpers-BX4uk4hE.js} +2 -2
- package/dist/{helpers-BVKN1UT2.js.map → helpers-BX4uk4hE.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/{logger-ByZ6uasw.js → logger-5s5elGiI.js} +2 -2
- package/dist/{logger-ByZ6uasw.js.map → logger-5s5elGiI.js.map} +1 -1
- package/dist/{logger-BQVgeHFC.js → logger-XFZyocLt.js} +1 -1
- package/dist/{main-CPSafkhy.js → main-j8QYeC6r.js} +2 -2
- package/dist/{main-CPSafkhy.js.map → main-j8QYeC6r.js.map} +1 -1
- package/dist/{oauthProvidersClient-DIALal8-.js → oauthProvidersClient-BiAeUlGt.js} +2 -2
- package/dist/{oauthProvidersClient-DIALal8-.js.map → oauthProvidersClient-BiAeUlGt.js.map} +1 -1
- package/dist/oauthProvidersClient-BzmoQCTp.js +1 -0
- package/dist/{providers-BF-QH52O.js → providers-Cn62XXpN.js} +2 -2
- package/dist/{providers-BF-QH52O.js.map → providers-Cn62XXpN.js.map} +1 -1
- package/dist/{proxyFetch-BL46N-Gu.js → proxyFetch-B8GqIfOa.js} +2 -2
- package/dist/{proxyFetch-BL46N-Gu.js.map → proxyFetch-B8GqIfOa.js.map} +1 -1
- package/dist/{transportDetection-B-gdKgOq.js → transportDetection-BxIxm1gk.js} +2 -2
- package/dist/{transportDetection-B-gdKgOq.js.map → transportDetection-BxIxm1gk.js.map} +1 -1
- package/dist/{upstreamNegotiation-BsSueLqQ.js → upstreamNegotiation-CO-zQc38.js} +2 -2
- package/dist/{upstreamNegotiation-BsSueLqQ.js.map → upstreamNegotiation-CO-zQc38.js.map} +1 -1
- package/package.json +1 -1
- package/dist/oauthProvidersClient-BpPCwZ_f.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{proxiedFetch as e}from"./proxyFetch-BL46N-Gu.js";import{SESSION_ID as t,config as n}from"./env-C2921_jo.js";import{extractTraceIdFromHeaders as r,gatewayCorrelationId as i,logger as a,runWithTraceContextAsync as o}from"./logger-ByZ6uasw.js";import{AnnotationsSchema as s,AudioContentSchema as c,BaseMetadataSchema as l,BaseRequestParamsSchema as u,BlobResourceContentsSchema as d,BooleanSchemaSchema as f,CLIENT_CAPABILITIES_META_KEY as p,CLIENT_INFO_META_KEY as m,CallToolRequestParamsSchema as h,CallToolRequestSchema as g,CallToolResultSchema as _,CancelTaskRequestSchema as v,CancelTaskResultSchema as y,CancelledNotificationParamsSchema as b,CancelledNotificationSchema as x,ClientCapabilitiesSchema as S,ClientNotificationSchema as C,ClientRequestSchema as ee,ClientResultSchema as te,ClientTasksCapabilitySchema as ne,CompatibilityCallToolResultSchema as w,CompleteRequestParamsSchema as re,CompleteRequestSchema as T,CompleteResultSchema as ie,ContentBlockSchema as ae,CreateMessageRequestParamsSchema as oe,CreateMessageRequestSchema as se,CreateMessageResultSchema as E,CreateMessageResultWithToolsSchema as ce,CreateTaskResultSchema as D,CursorSchema as O,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as le,DiscoverRequestSchema as ue,DiscoverResultSchema as de,ElicitRequestFormParamsSchema as fe,ElicitRequestParamsSchema as pe,ElicitRequestSchema as me,ElicitRequestURLParamsSchema as he,ElicitResultSchema as ge,ElicitationCompleteNotificationParamsSchema as _e,ElicitationCompleteNotificationSchema as ve,EmbeddedResourceSchema as ye,EmptyResultSchema as be,EnumSchemaSchema as xe,GetPromptRequestParamsSchema as Se,GetPromptRequestSchema as Ce,GetPromptResultSchema as we,GetTaskPayloadRequestSchema as Te,GetTaskPayloadResultSchema as Ee,GetTaskRequestSchema as De,GetTaskResultSchema as Oe,IconSchema as ke,IconsSchema as Ae,IdJagTokenExchangeResponseSchema as je,ImageContentSchema as Me,ImplementationSchema as Ne,InitializeRequestParamsSchema as Pe,InitializeRequestSchema as Fe,InitializeResultSchema as Ie,InitializedNotificationSchema as Le,JSONArraySchema as Re,JSONObjectSchema as ze,JSONRPCErrorResponseSchema as Be,JSONRPCMessageSchema as Ve,JSONRPCNotificationSchema as He,JSONRPCRequestSchema as Ue,JSONRPCResponseSchema as We,JSONRPCResultResponseSchema as Ge,JSONValueSchema as Ke,LATEST_PROTOCOL_VERSION as qe,LOG_LEVEL_META_KEY as Je,LegacyTitledEnumSchemaSchema as Ye,ListChangedOptionsBaseSchema as Xe,ListPromptsRequestSchema as Ze,ListPromptsResultSchema as Qe,ListResourceTemplatesRequestSchema as $e,ListResourceTemplatesResultSchema as et,ListResourcesRequestSchema as tt,ListResourcesResultSchema as nt,ListRootsRequestSchema as k,ListRootsResultSchema as rt,ListTasksRequestSchema as it,ListTasksResultSchema as at,ListToolsRequestSchema as ot,ListToolsResultSchema as st,LoggingLevelSchema as ct,LoggingMessageNotificationParamsSchema as lt,LoggingMessageNotificationSchema as ut,ModelHintSchema as dt,ModelPreferencesSchema as ft,MultiSelectEnumSchemaSchema as pt,NotificationSchema as mt,NotificationsParamsSchema as ht,NumberSchemaSchema as gt,OAuthClientInformationFullSchema as _t,OAuthClientInformationSchema as vt,OAuthClientMetadataSchema as yt,OAuthClientRegistrationErrorSchema as bt,OAuthErrorResponseSchema as xt,OAuthMetadataSchema as St,OAuthProtectedResourceMetadataSchema as Ct,OAuthTokenRevocationRequestSchema as wt,OAuthTokensSchema as Tt,OpenIdProviderDiscoveryMetadataSchema as Et,OpenIdProviderMetadataSchema as Dt,PROTOCOL_VERSION_META_KEY as Ot,PaginatedRequestParamsSchema as kt,PaginatedRequestSchema as At,PaginatedResultSchema as jt,PingRequestSchema as Mt,PrimitiveSchemaDefinitionSchema as A,ProgressNotificationParamsSchema as j,ProgressNotificationSchema as Nt,ProgressSchema as Pt,ProgressTokenSchema as Ft,PromptArgumentSchema as It,PromptListChangedNotificationSchema as Lt,PromptMessageSchema as Rt,PromptReferenceSchema as zt,PromptSchema as Bt,ReadResourceRequestParamsSchema as Vt,ReadResourceRequestSchema as Ht,ReadResourceResultSchema as Ut,RelatedTaskMetadataSchema as Wt,RequestIdSchema as Gt,RequestMetaSchema as Kt,RequestSchema as qt,ResourceContentsSchema as Jt,ResourceLinkSchema as Yt,ResourceListChangedNotificationSchema as Xt,ResourceRequestParamsSchema as M,ResourceSchema as Zt,ResourceTemplateReferenceSchema as Qt,ResourceTemplateSchema as $t,ResourceUpdatedNotificationParamsSchema as en,ResourceUpdatedNotificationSchema as tn,ResultMetaObjectSchema as nn,ResultSchema as rn,RoleSchema as an,RootSchema as on,RootsListChangedNotificationSchema as sn,SERVER_INFO_META_KEY as cn,SUBSCRIPTION_ID_META_KEY as ln,SUPPORTED_PROTOCOL_VERSIONS as un,SamplingContentSchema as dn,SamplingMessageContentBlockSchema as fn,SamplingMessageSchema as pn,ServerCapabilitiesSchema as mn,ServerNotificationSchema as hn,ServerRequestSchema as gn,ServerResultSchema as _n,ServerTasksCapabilitySchema as vn,SetLevelRequestParamsSchema as yn,SetLevelRequestSchema as bn,SingleSelectEnumSchemaSchema as xn,StringSchemaSchema as Sn,SubscribeRequestParamsSchema as Cn,SubscribeRequestSchema as wn,SubscriptionFilterSchema as Tn,SubscriptionsAcknowledgedNotificationParamsSchema as En,SubscriptionsAcknowledgedNotificationSchema as Dn,SubscriptionsListenRequestParamsSchema as On,SubscriptionsListenRequestSchema as kn,SubscriptionsListenResultMetaSchema as An,SubscriptionsListenResultSchema as jn,TaskAugmentedRequestParamsSchema as Mn,TaskCreationParamsSchema as Nn,TaskMetadataSchema as Pn,TaskSchema as Fn,TaskStatusNotificationParamsSchema as In,TaskStatusNotificationSchema as Ln,TaskStatusSchema as Rn,TextContentSchema as zn,TextResourceContentsSchema as Bn,TitledMultiSelectEnumSchemaSchema as Vn,TitledSingleSelectEnumSchemaSchema as Hn,ToolAnnotationsSchema as Un,ToolChoiceSchema as Wn,ToolExecutionSchema as Gn,ToolListChangedNotificationSchema as Kn,ToolResultContentSchema as qn,ToolSchema as Jn,ToolUseContentSchema as Yn,UnsubscribeRequestParamsSchema as Xn,UnsubscribeRequestSchema as Zn,UntitledMultiSelectEnumSchemaSchema as Qn,UntitledSingleSelectEnumSchemaSchema as $n,_enum as N,_null as er,array as P,boolean as F,date as tr,datetime as nr,discriminatedUnion as rr,email as ir,intersection as ar,lazy as or,literal as I,looseObject as L,number as R,object as z,optional as B,preprocess as sr,record as V,safeParse as cr,string as H,toJSONSchema as lr,union as U,unknown as W,url as ur}from"./normalizeUrl-DUUGubD4.js";import dr,{randomUUID as fr}from"crypto";import{homedir as pr,hostname as mr,userInfo as hr}from"node:os";import{join as gr}from"node:path";import{randomUUID as _r}from"node:crypto";import{existsSync as vr,readFileSync as yr}from"node:fs";import{Readable as br}from"stream";import xr from"ps-list";import{deflateSync as Sr}from"node:zlib";import Cr from"node:process";import{Http2ServerRequest as wr,constants as Tr}from"http2";import{URL as Er}from"node:url";import Dr from"node:http";var Or=class{counter=0;events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){let t=(++this.counter).toString().padStart(12,`0`);return`${e}_${Date.now()}_${t}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length<4?``:t.slice(0,-3).join(`_`)}},kr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},Ar=class extends kr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},jr=class extends kr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},Mr=class extends kr{constructor(e,t,n={}){super(`ProtocolEraMismatchError`,e,{feature:`protocol_era`,module:`proxy`,operation:`negotiate`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...n})}},Nr=class extends kr{constructor(e,t,n,r={},i){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r}),i!==void 0&&(this.cause=i)}};const Pr=`[REDACTED]`,Fr=new Set([`api_key`,`api-key`,`apikey`,`authorization`,`bearer`,`credential`,`credentials`,`header`,`headers`,`key`,`pass`,`passwd`,`password`,`pwd`,`secret`,`token`]);var Ir=function(e){return e[e.Awaiting=0]=`Awaiting`,e[e.Inside=1]=`Inside`,e[e.None=2]=`None`,e}(Ir||{});function Lr(e){let t=[],n=!1;for(let r of e){if(n){t.push(Pr),n=!1;continue}if(Br(r)){t.push(`-H`+Pr);continue}let e=zr(r);if(e!==null&&Vr(e))if(r.includes(`=`)){let e=r.indexOf(`=`);t.push(r.slice(0,e+1)+Pr)}else t.push(r),n=!0;else t.push(r)}return t}function Rr(e){let t=``,n=Ir.None;for(let[,r,i]of e.matchAll(/(\s*)(\S+)/g)){if(n===Ir.Awaiting){t+=r+Pr,n=Ir.Inside;continue}if(n===Ir.Inside){if(!i.startsWith(`-`))continue;n=Ir.None}let[e,a]=Hr(i);t+=r+e,n=a}return t}function zr(e){if(!e.startsWith(`-`))return null;let t=e.replace(/^-{1,2}/,``),n=t.indexOf(`=`);return n>=0?t.slice(0,n):t}function Br(e){return e.startsWith(`-H`)&&e.length>2&&!e.startsWith(`--`)&&e[2]!==`=`}function Vr(e){return e===`H`?!0:Fr.has(e.toLowerCase())}function Hr(e){if(Br(e))return[`-H`+Pr,Ir.Inside];let t=zr(e);return t===null||!Vr(t)?[e,Ir.None]:e.includes(`=`)?[e.slice(0,e.indexOf(`=`)+1)+Pr,Ir.Inside]:[e,Ir.Awaiting]}const Ur=n.clientAppName;let Wr=null;const Gr=async()=>(Wr||=await import(`systeminformation`),Wr);async function Kr(e){try{let t=(await xr()).find(t=>t.pid===e);return t?.name?Rr(t.name):`unknown`}catch{return`unknown`}}function qr(e){return typeof e==`string`&&e!==``&&e.includes(`@`)}function Jr(){try{let e=Qr();if(!vr(e))return null;let t=yr(e,`utf-8`),n=!1;for(let e of t.split(`
|
|
1
|
+
import{proxiedFetch as e}from"./proxyFetch-B8GqIfOa.js";import{SESSION_ID as t,config as n}from"./env-Zfu004Nj.js";import{extractTraceIdFromHeaders as r,gatewayCorrelationId as i,logger as a,runWithTraceContextAsync as o}from"./logger-5s5elGiI.js";import{AnnotationsSchema as s,AudioContentSchema as c,BaseMetadataSchema as l,BaseRequestParamsSchema as u,BlobResourceContentsSchema as d,BooleanSchemaSchema as f,CLIENT_CAPABILITIES_META_KEY as p,CLIENT_INFO_META_KEY as m,CallToolRequestParamsSchema as h,CallToolRequestSchema as g,CallToolResultSchema as _,CancelTaskRequestSchema as v,CancelTaskResultSchema as y,CancelledNotificationParamsSchema as b,CancelledNotificationSchema as x,ClientCapabilitiesSchema as S,ClientNotificationSchema as C,ClientRequestSchema as ee,ClientResultSchema as te,ClientTasksCapabilitySchema as ne,CompatibilityCallToolResultSchema as w,CompleteRequestParamsSchema as re,CompleteRequestSchema as T,CompleteResultSchema as ie,ContentBlockSchema as ae,CreateMessageRequestParamsSchema as oe,CreateMessageRequestSchema as se,CreateMessageResultSchema as E,CreateMessageResultWithToolsSchema as ce,CreateTaskResultSchema as D,CursorSchema as O,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as le,DiscoverRequestSchema as ue,DiscoverResultSchema as de,ElicitRequestFormParamsSchema as fe,ElicitRequestParamsSchema as pe,ElicitRequestSchema as me,ElicitRequestURLParamsSchema as he,ElicitResultSchema as ge,ElicitationCompleteNotificationParamsSchema as _e,ElicitationCompleteNotificationSchema as ve,EmbeddedResourceSchema as ye,EmptyResultSchema as be,EnumSchemaSchema as xe,GetPromptRequestParamsSchema as Se,GetPromptRequestSchema as Ce,GetPromptResultSchema as we,GetTaskPayloadRequestSchema as Te,GetTaskPayloadResultSchema as Ee,GetTaskRequestSchema as De,GetTaskResultSchema as Oe,IconSchema as ke,IconsSchema as Ae,IdJagTokenExchangeResponseSchema as je,ImageContentSchema as Me,ImplementationSchema as Ne,InitializeRequestParamsSchema as Pe,InitializeRequestSchema as Fe,InitializeResultSchema as Ie,InitializedNotificationSchema as Le,JSONArraySchema as Re,JSONObjectSchema as ze,JSONRPCErrorResponseSchema as Be,JSONRPCMessageSchema as Ve,JSONRPCNotificationSchema as He,JSONRPCRequestSchema as Ue,JSONRPCResponseSchema as We,JSONRPCResultResponseSchema as Ge,JSONValueSchema as Ke,LATEST_PROTOCOL_VERSION as qe,LOG_LEVEL_META_KEY as Je,LegacyTitledEnumSchemaSchema as Ye,ListChangedOptionsBaseSchema as Xe,ListPromptsRequestSchema as Ze,ListPromptsResultSchema as Qe,ListResourceTemplatesRequestSchema as $e,ListResourceTemplatesResultSchema as et,ListResourcesRequestSchema as tt,ListResourcesResultSchema as nt,ListRootsRequestSchema as k,ListRootsResultSchema as rt,ListTasksRequestSchema as it,ListTasksResultSchema as at,ListToolsRequestSchema as ot,ListToolsResultSchema as st,LoggingLevelSchema as ct,LoggingMessageNotificationParamsSchema as lt,LoggingMessageNotificationSchema as ut,ModelHintSchema as dt,ModelPreferencesSchema as ft,MultiSelectEnumSchemaSchema as pt,NotificationSchema as mt,NotificationsParamsSchema as ht,NumberSchemaSchema as gt,OAuthClientInformationFullSchema as _t,OAuthClientInformationSchema as vt,OAuthClientMetadataSchema as yt,OAuthClientRegistrationErrorSchema as bt,OAuthErrorResponseSchema as xt,OAuthMetadataSchema as St,OAuthProtectedResourceMetadataSchema as Ct,OAuthTokenRevocationRequestSchema as wt,OAuthTokensSchema as Tt,OpenIdProviderDiscoveryMetadataSchema as Et,OpenIdProviderMetadataSchema as Dt,PROTOCOL_VERSION_META_KEY as Ot,PaginatedRequestParamsSchema as kt,PaginatedRequestSchema as At,PaginatedResultSchema as jt,PingRequestSchema as Mt,PrimitiveSchemaDefinitionSchema as A,ProgressNotificationParamsSchema as j,ProgressNotificationSchema as Nt,ProgressSchema as Pt,ProgressTokenSchema as Ft,PromptArgumentSchema as It,PromptListChangedNotificationSchema as Lt,PromptMessageSchema as Rt,PromptReferenceSchema as zt,PromptSchema as Bt,ReadResourceRequestParamsSchema as Vt,ReadResourceRequestSchema as Ht,ReadResourceResultSchema as Ut,RelatedTaskMetadataSchema as Wt,RequestIdSchema as Gt,RequestMetaSchema as Kt,RequestSchema as qt,ResourceContentsSchema as Jt,ResourceLinkSchema as Yt,ResourceListChangedNotificationSchema as Xt,ResourceRequestParamsSchema as M,ResourceSchema as Zt,ResourceTemplateReferenceSchema as Qt,ResourceTemplateSchema as $t,ResourceUpdatedNotificationParamsSchema as en,ResourceUpdatedNotificationSchema as tn,ResultMetaObjectSchema as nn,ResultSchema as rn,RoleSchema as an,RootSchema as on,RootsListChangedNotificationSchema as sn,SERVER_INFO_META_KEY as cn,SUBSCRIPTION_ID_META_KEY as ln,SUPPORTED_PROTOCOL_VERSIONS as un,SamplingContentSchema as dn,SamplingMessageContentBlockSchema as fn,SamplingMessageSchema as pn,ServerCapabilitiesSchema as mn,ServerNotificationSchema as hn,ServerRequestSchema as gn,ServerResultSchema as _n,ServerTasksCapabilitySchema as vn,SetLevelRequestParamsSchema as yn,SetLevelRequestSchema as bn,SingleSelectEnumSchemaSchema as xn,StringSchemaSchema as Sn,SubscribeRequestParamsSchema as Cn,SubscribeRequestSchema as wn,SubscriptionFilterSchema as Tn,SubscriptionsAcknowledgedNotificationParamsSchema as En,SubscriptionsAcknowledgedNotificationSchema as Dn,SubscriptionsListenRequestParamsSchema as On,SubscriptionsListenRequestSchema as kn,SubscriptionsListenResultMetaSchema as An,SubscriptionsListenResultSchema as jn,TaskAugmentedRequestParamsSchema as Mn,TaskCreationParamsSchema as Nn,TaskMetadataSchema as Pn,TaskSchema as Fn,TaskStatusNotificationParamsSchema as In,TaskStatusNotificationSchema as Ln,TaskStatusSchema as Rn,TextContentSchema as zn,TextResourceContentsSchema as Bn,TitledMultiSelectEnumSchemaSchema as Vn,TitledSingleSelectEnumSchemaSchema as Hn,ToolAnnotationsSchema as Un,ToolChoiceSchema as Wn,ToolExecutionSchema as Gn,ToolListChangedNotificationSchema as Kn,ToolResultContentSchema as qn,ToolSchema as Jn,ToolUseContentSchema as Yn,UnsubscribeRequestParamsSchema as Xn,UnsubscribeRequestSchema as Zn,UntitledMultiSelectEnumSchemaSchema as Qn,UntitledSingleSelectEnumSchemaSchema as $n,_enum as N,_null as er,array as P,boolean as F,date as tr,datetime as nr,discriminatedUnion as rr,email as ir,intersection as ar,lazy as or,literal as I,looseObject as L,number as R,object as z,optional as B,preprocess as sr,record as V,safeParse as cr,string as H,toJSONSchema as lr,union as U,unknown as W,url as ur}from"./normalizeUrl-DUUGubD4.js";import dr,{randomUUID as fr}from"crypto";import{homedir as pr,hostname as mr,userInfo as hr}from"node:os";import{join as gr}from"node:path";import{randomUUID as _r}from"node:crypto";import{existsSync as vr,readFileSync as yr}from"node:fs";import{Readable as br}from"stream";import xr from"ps-list";import{deflateSync as Sr}from"node:zlib";import Cr from"node:process";import{Http2ServerRequest as wr,constants as Tr}from"http2";import{URL as Er}from"node:url";import Dr from"node:http";var Or=class{counter=0;events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){let t=(++this.counter).toString().padStart(12,`0`);return`${e}_${Date.now()}_${t}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length<4?``:t.slice(0,-3).join(`_`)}},kr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},Ar=class extends kr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},jr=class extends kr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},Mr=class extends kr{constructor(e,t,n={}){super(`ProtocolEraMismatchError`,e,{feature:`protocol_era`,module:`proxy`,operation:`negotiate`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...n})}},Nr=class extends kr{constructor(e,t,n,r={},i){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r}),i!==void 0&&(this.cause=i)}};const Pr=`[REDACTED]`,Fr=new Set([`api_key`,`api-key`,`apikey`,`authorization`,`bearer`,`credential`,`credentials`,`header`,`headers`,`key`,`pass`,`passwd`,`password`,`pwd`,`secret`,`token`]);var Ir=function(e){return e[e.Awaiting=0]=`Awaiting`,e[e.Inside=1]=`Inside`,e[e.None=2]=`None`,e}(Ir||{});function Lr(e){let t=[],n=!1;for(let r of e){if(n){t.push(Pr),n=!1;continue}if(Br(r)){t.push(`-H`+Pr);continue}let e=zr(r);if(e!==null&&Vr(e))if(r.includes(`=`)){let e=r.indexOf(`=`);t.push(r.slice(0,e+1)+Pr)}else t.push(r),n=!0;else t.push(r)}return t}function Rr(e){let t=``,n=Ir.None;for(let[,r,i]of e.matchAll(/(\s*)(\S+)/g)){if(n===Ir.Awaiting){t+=r+Pr,n=Ir.Inside;continue}if(n===Ir.Inside){if(!i.startsWith(`-`))continue;n=Ir.None}let[e,a]=Hr(i);t+=r+e,n=a}return t}function zr(e){if(!e.startsWith(`-`))return null;let t=e.replace(/^-{1,2}/,``),n=t.indexOf(`=`);return n>=0?t.slice(0,n):t}function Br(e){return e.startsWith(`-H`)&&e.length>2&&!e.startsWith(`--`)&&e[2]!==`=`}function Vr(e){return e===`H`?!0:Fr.has(e.toLowerCase())}function Hr(e){if(Br(e))return[`-H`+Pr,Ir.Inside];let t=zr(e);return t===null||!Vr(t)?[e,Ir.None]:e.includes(`=`)?[e.slice(0,e.indexOf(`=`)+1)+Pr,Ir.Inside]:[e,Ir.Awaiting]}const Ur=n.clientAppName;let Wr=null;const Gr=async()=>(Wr||=await import(`systeminformation`),Wr);async function Kr(e){try{let t=(await xr()).find(t=>t.pid===e);return t?.name?Rr(t.name):`unknown`}catch{return`unknown`}}function qr(e){return typeof e==`string`&&e!==``&&e.includes(`@`)}function Jr(){try{let e=Qr();if(!vr(e))return null;let t=yr(e,`utf-8`),n=!1;for(let e of t.split(`
|
|
2
2
|
`)){let t=e.trim();if(t.startsWith(`#`)||t.startsWith(`;`))continue;if(t.startsWith(`[`)){n=t.toLowerCase()===`[user]`;continue}if(n){let e=t.match(/^email\s*=\s*(.+)/i);if(e)return e[1].replace(/\s+[#;].*$/,``).trim()||null}}return null}catch{return null}}function Yr(){return gr(pr(),`.claude.json`)}function Xr(){return gr(pr(),`.codex`,`auth.json`)}function Zr(){try{return mr()}catch{return`unknown-device`}}function Qr(){return gr(pr(),`.gitconfig`)}const $r=new Map;async function ei(e){let t=$r.get(e);if(t)return t;let n=(async()=>{try{let{list:t}=await(await Gr()).processes(),n=t.find(t=>t.pid===e)?.started;if(n){let e=new Date(n);if(!Number.isNaN(e.getTime()))return e.toISOString()}return}catch{return}})();return $r.set(e,n),n}function ti(){return new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()}const ni=new Set([`-`,`0`,`00000000`,`00000000-0000-0000-0000-000000000000`,`11111111-1111-1111-1111-111111111111`,`Default string`,`None`,`Not Specified`,`System Serial Number`,`To Be Filled By O.E.M.`,`To be filled by O.E.M.`,`uninitialized`]);function ri(e){if(!e)return!1;let t=e.trim();return t===``||ni.has(t)?!1:!t.toLowerCase().includes(`to be filled`)}const ii=[`/etc/machine-id`,`/var/lib/dbus/machine-id`],ai=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function oi(){try{return process.platform===`linux`?ci()??si()?.uid??hi():await li()}catch{return}}function si(){if(process.env.KUBERNETES_SERVICE_HOST)try{let e=yr(`/var/run/secrets/kubernetes.io/serviceaccount/token`,`utf8`).trim().split(`.`);if(e.length!==3)return;let t=JSON.parse(Buffer.from(e[1]??``,`base64url`).toString(`utf8`))[`kubernetes.io`],n=t?.pod?.uid;return!n||!ai.test(n)?void 0:{name:t?.pod?.name,namespace:t?.namespace,uid:n}}catch{return}}function ci(){for(let e of ii){let t=mi(e);if(ri(t))return t}}async function li(){try{let{serial:e}=await(await Gr()).system();return ri(e)?e.trim():void 0}catch{return}}function ui(){try{let e=fi()?.oauthAccount?.emailAddress;if(qr(e))return e;let t=pi();if(qr(t))return t;let n=Jr();return qr(n)?n:void 0}catch{return}}function di(){try{let e=hr();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function fi(){try{let e=Yr();if(!vr(e))return null;let t=yr(e,`utf-8`);return JSON.parse(t)}catch{return null}}function pi(){try{let e=Xr();if(!vr(e))return null;let t=yr(e,`utf-8`),n=JSON.parse(t)?.tokens?.id_token;if(!n)return null;let r=n.split(`.`);if(r.length!==3)return null;let i=Buffer.from(r[1],`base64url`).toString(`utf-8`);return JSON.parse(i).email||null}catch{return null}}function mi(e){try{return yr(e,`utf8`).split(`
|
|
3
3
|
`)[0]?.trim()}catch{return}}function hi(){let e=mi(`/sys/class/dmi/id/product_uuid`);return ri(e)?e:void 0}const gi=()=>{if(!vr(`/.dockerenv`))return null;try{let e=yr(gr(pr(),`.onyx`,`container-context.json`),`utf8`),t=JSON.parse(e);return t.container_id?t:null}catch{return null}},_i=e=>{let t=process.env.ONYX_DOCKER_CONTAINER_ID,n=t?null:gi(),r=t||n?.container_id;return r?{...e,containerRuntime:process.env.ONYX_CONTAINER_RUNTIME||void 0,deviceName:process.env.ONYX_HOST_DEVICE_NAME||n?.host_device_name||e.deviceName,dockerContainerId:r,dockerContainerName:process.env.ONYX_DOCKER_CONTAINER_NAME||n?.container_name||void 0,dockerImage:process.env.ONYX_DOCKER_IMAGE||n?.image||void 0,dockerImageId:process.env.ONYX_DOCKER_IMAGE_ID||n?.image_id||void 0,inDockerContainer:!0,systemSerialNumber:process.env.ONYX_HOST_SERIAL_NUMBER||n?.host_serial_number||e.systemSerialNumber}:e},vi=async()=>{let e=process.pid,t=process.ppid,r=ti();try{let i=Zr(),[a,o,s]=await Promise.all([oi(),Kr(t),ei(t)]),c=ui(),l=di();return _i({clientAppName:Ur||`unknown`,deviceName:i,email:c,gatewayVersion:n.appVersion,parentProcessId:t,parentProcessName:o,parentProcessStartTime:s,processId:e,processStartTime:r,systemSerialNumber:a,username:l})}catch{return _i({clientAppName:Ur||`unknown`,deviceName:`unknown-device`,email:void 0,gatewayVersion:n.appVersion,parentProcessId:t,parentProcessName:`unknown`,processId:e,processStartTime:r,systemSerialNumber:void 0,username:void 0})}},yi=`onyx.security`;function bi(e){if(!e)return e;let t;try{t=new URL(e)}catch{return e}if(!t.host||t.pathname===``||t.pathname===`/`)return e;let n=t.hostname.toLowerCase().replace(/\.$/,``);if(n!==yi&&!n.endsWith(`.${yi}`))return e;let r=t.pathname.split(`/`),i=r.findIndex(e=>e.length>0);if(i===-1)return e;r[i]=`[REDACTED]`;let a=r.join(`/`);return`${t.protocol}//${t.host}${a}${t.search}${t.hash}`}function xi(e){let t=Sr(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var Si=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),a.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return a.warn(`Request blocked by security policy`),t}catch(t){if(a.error(`Scanning failed`,{error:t,method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl}),!this.config.scanFailOpen)return a.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};a.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.buildEventMetadata(),method:e.method,originalRequestId:e.originalRequestId,type:e.type};a.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return a.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}buildEventMetadata(){let e=this.config.spawnedServerInfoProvider?.();return{...this.sessionData,eventEndTime:new Date().toISOString(),...e?.pid===void 0?{}:{spawnedServerProcessId:e.pid},...e?.startedAtMs===void 0?{}:{spawnedServerProcessStartTime:new Date(e.startedAtMs).toISOString()}}}getClientInfoBase64(){return xi(this.sessionData)}async sendScanRequest(n){let r=new AbortController,i=setTimeout(()=>r.abort(),this.config.scanTimeoutMs);try{let i=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,a={data:n.data,id:n.id,metadata:n.metadata,method:n.method,sessionId:t,...n.originalRequestId&&{original_request_id:String(n.originalRequestId)},type:n.type},o=await e(i,{body:JSON.stringify(a),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:r.signal});if(!o.ok)throw Error(`Sanitization service returned ${o.status}: ${o.statusText}`);let s=await o.json();if(!s.action||![`allow`,`block`,`modify`].includes(s.action))throw Error(`Invalid scan response format: action="${s.action}"`);return s}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(i)}}};let Ci=null;const wi=async e=>{let t=await vi(),n=e.cliArgs.proxyType,r=n===`stdio`?{...e.cliArgs,args:Lr(e.cliArgs.args)}:e.cliArgs,i={...t,fileContentHash:n===`stdio`?r.fileContentHash:void 0,proxyType:n,remoteCliArgs:n===`remote`?r:void 0,stdioCliArgs:n===`stdio`?r:void 0},o=n===`remote`?{...i,remoteCliArgs:{...r,url:bi(r.url)}}:i;return a.setSessionData(o),Ci=new Si(e,i),Ci},Ti=()=>Ci,Ei=e=>{if(e.maxTotalTimeoutMs<0)throw Error(`maxTotalTimeoutMs must be >= 0 (0 disables the cap), got ${e.maxTotalTimeoutMs}`);let t={resetTimeoutOnProgress:e.resetTimeoutOnProgress,timeout:e.timeoutMs};return e.maxTotalTimeoutMs>0&&(t.maxTotalTimeout=e.maxTotalTimeoutMs),t},Di=new class{counts=new Map;lastLogTime=Date.now();logIntervalMs=6e4;increment(e){this.counts.set(e,(this.counts.get(e)||0)+1),this.maybeLog()}logAndReset(){if(this.counts.size===0)return;let e=(Array.from(this.counts.values()).reduce((e,t)=>e+t,0));a.info(`Requests intercepted`,{byMethod:Object.fromEntries(this.counts),eventType:`mcp_requests_intercepted`,totalCount:e}),this.counts.clear(),this.lastLogTime=Date.now()}maybeLog(){Date.now()-this.lastLogTime>=this.logIntervalMs&&this.logAndReset()}},Oi=()=>{Di.logAndReset()},ki=e=>{if(e.length>1&&e[1]&&typeof e[1]==`object`&&`mcpReq`in e[1])return e[1].mcpReq?.id?.toString()},G=(e,t,n,r)=>async(...i)=>{Di.increment(e);let o=Ti(),s=e,c=i[0],l=fr(),u=ki(i)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(a.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(a.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?a.warn(n):a.info(n),r.modified_data}if(n){let o=`${e} ${t} by security policy`;i===`warn`?a.warn(o):a.info(o),n(r.modified_data);return}return r.modified_data}a.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(a.error(`Unexpected error during ${e} processing`,{error:t}),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},f;try{f=await d(`request`,c,e=>{i[0]=e})}catch(n){if(n instanceof Error&&n.message===`Security scanning service unavailable`)throw a.error(`Security scanning unavailable (fail-closed)`,{error:n.message,handlerName:e,operation:t}),n;a.error(`Unexpected error during request processing, continuing`,{error:n,handlerName:e,operation:t})}if(f!==void 0)return f;if(r&&!await r.isAllowed()){let n=r.getBlockReason();throw a.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new Ar(n,`policy_block`)}try{let e=await n(...i);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){a.error(`Error during response processing, returning original result`,{error:e})}return e}catch(n){if(n instanceof Ar)throw a.info(`Request blocked by access control`,{error:n.message,handlerName:e,operation:t,reason:n.reason}),n;try{await d(`error`,{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}catch(e){a.warn(`Failed to evaluate error`,{evalError:e})}throw a.error(`Handler error in ${e}`,{argsCount:i.length,errorMessage:n instanceof Error?n.message:String(n),operation:t}),n}},Ai=async({authorizer:e,client:t,forwarding:r=n.toolCall,server:i,serverCapabilities:o})=>{let s=Ei(r);o?.logging&&(i.setNotificationHandler(`notifications/message`,G(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(`notifications/message`,G(`notifications/message`,`client-to-server`,async e=>i.notification(e),e))),o?.prompts&&(i.setRequestHandler(`prompts/get`,G(`prompts/get`,`get`,async e=>t.getPrompt(e.params,s),e)),i.setRequestHandler(`prompts/list`,G(`prompts/list`,`list`,async e=>t.listPrompts(e.params,s),e))),o?.resources&&(i.setRequestHandler(`resources/list`,G(`resources/list`,`list`,async e=>t.listResources(e.params,s),e)),i.setRequestHandler(`resources/templates/list`,G(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params,s),e)),i.setRequestHandler(`resources/read`,G(`resources/read`,`read`,async e=>t.readResource(e.params,s),e)),o?.resources.subscribe&&(i.setNotificationHandler(`notifications/resources/updated`,G(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),i.setRequestHandler(`resources/subscribe`,G(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params,s),e)),i.setRequestHandler(`resources/unsubscribe`,G(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params,s),e)))),o?.tools&&(i.setRequestHandler(`tools/call`,G(`tools/call`,`call`,async(e,n)=>{let r=n.mcpReq._meta?.progressToken,i=r===void 0?void 0:e=>{n.mcpReq.notify({method:`notifications/progress`,params:{...e,progressToken:r}}).catch(e=>{a.warn(`Failed to forward progress notification to client`,{error:e})})};return t.callTool(e.params,{...s,onprogress:i})},e)),i.setRequestHandler(`tools/list`,G(`tools/list`,`list`,async e=>t.listTools(e.params,s),e))),o?.completions&&i.setRequestHandler(`completion/complete`,G(`completion/complete`,`complete`,async e=>t.complete(e.params,s),e))};var ji=Object.create,Mi=Object.defineProperty,Ni=Object.getOwnPropertyDescriptor,Pi=Object.getOwnPropertyNames,Fi=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty,K=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Li=(e,t)=>{let n={};for(var r in e)Mi(n,r,{get:e[r],enumerable:!0});return t&&Mi(n,Symbol.toStringTag,{value:`Module`}),n},Ri=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Pi(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ii.call(e,s)&&s!==n&&Mi(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ni(t,s))||r.enumerable});return e},zi=(e,t,n)=>(n=e==null?{}:ji(Fi(e)),Ri(t||!e||!e.__esModule?Mi(n,`default`,{value:e,enumerable:!0}):n,e));const Bi=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),Vi=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Hi=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),Ui=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function Wi(e){return typeof e==`string`&&Vi.has(e.replace(/#$/,``))}function Gi(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(Bi.has(n))return`2020-12`;if(Vi.has(n))return`2019-09`;if(Hi.has(n)||Ui.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}const Ki=Symbol.for(`mcp.sdk.errorBrands`);function qi(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Ki,{value:n,enumerable:!1,configurable:!0})}function Ji(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Ki)){let n=t[Ki];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}(class e extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Ji(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 Ji(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,qi(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}});let q=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}({});var J=class extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Ji(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 Ji(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`,qi(this,new.target)}};(class extends J{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.SdkHttpError`})}constructor(e,t,n){super(e,t,n),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});function Yi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xi(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function Zi(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Qi(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(Yi(i)&&Yi(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Xi(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}const $i=`2026-07-28`,ea=[$i];function ta(e){return e>=$i}function na(e){return e.filter(e=>!ta(e))}function ra(e){return e.filter(e=>ta(e))}function ia(e){let t=e.structuredContent;return t===void 0||!(typeof t!=`object`||!t||Array.isArray(t))||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}const aa=[`task`,`inputRequests`,`requestState`];function oa(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||aa.some(t=>t in e)?e:{...e,content:[]}}function sa(){let e=or(()=>U([H(),R(),F(),er(),V(H(),e),P(e)])),t=V(H(),e),n=U([H(),R().int()]),r=H(),i=z({ttl:R().optional()}),a=z({taskId:H()}),o=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=z({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=z({method:H(),params:s.loose().optional()}),u=z({_meta:o.optional()}),d=z({method:H(),params:u.loose().optional()}),f=L({_meta:o.optional()}),p=U([H(),R().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:H().optional()}),g=d.extend({method:I(`notifications/cancelled`),params:h}),_=z({src:H(),mimeType:H().optional(),sizes:P(H()).optional(),theme:N([`light`,`dark`]).optional()}),v=z({icons:P(_).optional()}),y=z({name:H(),title:H().optional()}),b=y.extend({...y.shape,...v.shape,version:H(),websiteUrl:H().optional(),description:H().optional()}),x=ar(z({applyDefaults:F().optional()}),t),S=sr(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ar(z({form:x.optional(),url:t.optional()}),t.optional())),C=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),ee=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),te=z({experimental:V(H(),t).optional(),sampling:z({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:z({listChanged:F().optional()}).optional(),tasks:C.optional(),extensions:V(H(),t).optional()}),ne=s.extend({protocolVersion:H(),capabilities:te,clientInfo:b}),w=l.extend({method:I(`initialize`),params:ne}),re=z({experimental:V(H(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:z({listChanged:F().optional()}).optional(),resources:z({subscribe:F().optional(),listChanged:F().optional()}).optional(),tools:z({listChanged:F().optional()}).optional(),tasks:ee.optional(),extensions:V(H(),t).optional()}),T=f.extend({protocolVersion:H(),capabilities:re,serverInfo:b,instructions:H().optional()}),ie=d.extend({method:I(`notifications/initialized`),params:u.optional()}),ae=l.extend({method:I(`ping`),params:s.optional()}),oe=z({progress:R(),total:B(R()),message:B(H())}),se=z({...u.shape,...oe.shape,progressToken:n}),E=d.extend({method:I(`notifications/progress`),params:se}),ce=s.extend({cursor:r.optional()}),D=l.extend({params:ce.optional()}),O=f.extend({nextCursor:r.optional()}),le=z({uri:H(),mimeType:B(H()),_meta:V(H(),W()).optional()}),ue=le.extend({text:H()}),de=H().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),fe=le.extend({blob:de}),pe=N([`user`,`assistant`]),me=z({audience:P(pe).optional(),priority:R().min(0).max(1).optional(),lastModified:nr({offset:!0}).optional()}),he=z({...y.shape,...v.shape,uri:H(),description:B(H()),mimeType:B(H()),size:B(R()),annotations:me.optional(),_meta:B(L({}))}),ge=z({...y.shape,...v.shape,uriTemplate:H(),description:B(H()),mimeType:B(H()),annotations:me.optional(),_meta:B(L({}))}),_e=D.extend({method:I(`resources/list`)}),ve=O.extend({resources:P(he)}),ye=D.extend({method:I(`resources/templates/list`)}),be=O.extend({resourceTemplates:P(ge)}),xe=s.extend({uri:H()}),Se=xe,Ce=l.extend({method:I(`resources/read`),params:Se}),we=f.extend({contents:P(U([ue,fe]))}),Te=d.extend({method:I(`notifications/resources/list_changed`),params:u.optional()}),Ee=xe,De=l.extend({method:I(`resources/subscribe`),params:Ee}),Oe=xe,ke=l.extend({method:I(`resources/unsubscribe`),params:Oe}),Ae=u.extend({uri:H()}),je=d.extend({method:I(`notifications/resources/updated`),params:Ae}),Me=z({name:H(),description:B(H()),required:B(F())}),Ne=z({...y.shape,...v.shape,description:B(H()),arguments:B(P(Me)),_meta:B(L({}))}),Pe=D.extend({method:I(`prompts/list`)}),Fe=O.extend({prompts:P(Ne)}),Ie=s.extend({name:H(),arguments:V(H(),H()).optional()}),Le=l.extend({method:I(`prompts/get`),params:Ie}),Re=z({type:I(`text`),text:H(),annotations:me.optional(),_meta:V(H(),W()).optional()}),ze=z({type:I(`image`),data:de,mimeType:H(),annotations:me.optional(),_meta:V(H(),W()).optional()}),Be=z({type:I(`audio`),data:de,mimeType:H(),annotations:me.optional(),_meta:V(H(),W()).optional()}),Ve=z({type:I(`tool_use`),name:H(),id:H(),input:V(H(),W()),_meta:V(H(),W()).optional()}),He=z({type:I(`resource`),resource:U([ue,fe]),annotations:me.optional(),_meta:V(H(),W()).optional()}),Ue=he.extend({type:I(`resource_link`)}),We=U([Re,ze,Be,Ue,He]),Ge=z({role:pe,content:We}),Ke=f.extend({description:H().optional(),messages:P(Ge)}),qe=d.extend({method:I(`notifications/prompts/list_changed`),params:u.optional()}),Je=z({title:H().optional(),readOnlyHint:F().optional(),destructiveHint:F().optional(),idempotentHint:F().optional(),openWorldHint:F().optional()}),Ye=z({taskSupport:N([`required`,`optional`,`forbidden`]).optional()}),Xe=z({...y.shape,...v.shape,description:H().optional(),inputSchema:z({type:I(`object`),properties:V(H(),e).optional(),required:P(H()).optional()}).catchall(W()),outputSchema:z({type:I(`object`),properties:V(H(),e).optional(),required:P(H()).optional()}).catchall(W()).optional(),annotations:Je.optional(),execution:Ye.optional(),_meta:V(H(),W()).optional()}),Ze=D.extend({method:I(`tools/list`)}),Qe=O.extend({tools:P(Xe)}),$e=f.extend({content:P(We),structuredContent:V(H(),W()).optional(),isError:F().optional()}),et=c.extend({name:H(),arguments:V(H(),W()).optional()}),tt=l.extend({method:I(`tools/call`),params:et}),nt=d.extend({method:I(`notifications/tools/list_changed`),params:u.optional()}),k=N([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),rt=s.extend({level:k}),it=l.extend({method:I(`logging/setLevel`),params:rt}),at=u.extend({level:k,logger:H().optional(),data:W()}),ot=d.extend({method:I(`notifications/message`),params:at}),st=z({name:H().optional()}),ct=z({hints:P(st).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),lt=z({mode:N([`auto`,`required`,`none`]).optional()}),ut=z({type:I(`tool_result`),toolUseId:H().describe(`The unique identifier for the corresponding tool call.`),content:P(We),structuredContent:z({}).loose().optional(),isError:F().optional(),_meta:V(H(),W()).optional()}),dt=rr(`type`,[Re,ze,Be]),ft=rr(`type`,[Re,ze,Be,Ve,ut]),pt=z({role:pe,content:U([ft,P(ft)]),_meta:V(H(),W()).optional()}),mt=c.extend({messages:P(pt),modelPreferences:ct.optional(),systemPrompt:H().optional(),includeContext:N([`none`,`thisServer`,`allServers`]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:P(H()).optional(),metadata:t.optional(),tools:P(Xe).optional(),toolChoice:lt.optional()}),ht=l.extend({method:I(`sampling/createMessage`),params:mt}),gt=f.extend({model:H(),stopReason:B(N([`endTurn`,`stopSequence`,`maxTokens`]).or(H())),role:pe,content:dt}),_t=f.extend({model:H(),stopReason:B(N([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(H())),role:pe,content:U([ft,P(ft)])}),vt=z({type:I(`boolean`),title:H().optional(),description:H().optional(),default:F().optional()}),yt=z({type:I(`string`),title:H().optional(),description:H().optional(),minLength:R().optional(),maxLength:R().optional(),format:N([`email`,`uri`,`date`,`date-time`]).optional(),default:H().optional()}),bt=z({type:N([`number`,`integer`]),title:H().optional(),description:H().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),xt=z({type:I(`string`),title:H().optional(),description:H().optional(),enum:P(H()),default:H().optional()}),St=z({type:I(`string`),title:H().optional(),description:H().optional(),oneOf:P(z({const:H(),title:H()})),default:H().optional()}),Ct=z({type:I(`string`),title:H().optional(),description:H().optional(),enum:P(H()),enumNames:P(H()).optional(),default:H().optional()}),wt=U([xt,St]),Tt=z({type:I(`array`),title:H().optional(),description:H().optional(),minItems:R().optional(),maxItems:R().optional(),items:z({type:I(`string`),enum:P(H())}),default:P(H()).optional()}),Et=z({type:I(`array`),title:H().optional(),description:H().optional(),minItems:R().optional(),maxItems:R().optional(),items:z({anyOf:P(z({const:H(),title:H()}))}),default:P(H()).optional()}),Dt=U([Tt,Et]),Ot=U([Ct,wt,Dt]),kt=U([Ot,vt,yt,bt]),At=c.extend({mode:I(`form`).optional(),message:H(),requestedSchema:z({type:I(`object`),properties:V(H(),kt),required:P(H()).optional()}).catchall(W())}),jt=c.extend({mode:I(`url`),message:H(),elicitationId:H(),url:H().url()}),Mt=U([At,jt]),A=l.extend({method:I(`elicitation/create`),params:Mt}),j=u.extend({elicitationId:H()}),Nt=d.extend({method:I(`notifications/elicitation/complete`),params:j}),Pt=f.extend({action:N([`accept`,`decline`,`cancel`]),content:sr(e=>e===null?void 0:e,V(H(),U([H(),R(),F(),P(H())])).optional())}),Ft=z({type:I(`ref/resource`),uri:H()}),It=z({type:I(`ref/prompt`),name:H()}),Lt=s.extend({ref:U([It,Ft]),argument:z({name:H(),value:H()}),context:z({arguments:V(H(),H()).optional()}).optional()}),Rt=l.extend({method:I(`completion/complete`),params:Lt}),zt=f.extend({completion:L({values:P(H()).max(100),total:B(R().int()),hasMore:B(F())})}),Bt=z({uri:H().startsWith(`file://`),name:H().optional(),_meta:V(H(),W()).optional()}),Vt=l.extend({method:I(`roots/list`),params:s.optional()}),Ht=f.extend({roots:P(Bt)}),Ut=d.extend({method:I(`notifications/roots/list_changed`),params:u.optional()}),Wt=L({ttl:R().optional(),pollInterval:R().optional()}),Gt=N([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Kt=z({taskId:H(),status:Gt,ttl:U([R(),er()]),createdAt:H(),lastUpdatedAt:H(),pollInterval:B(R()),statusMessage:B(H())}),qt=f.extend({task:Kt}),Jt=u.merge(Kt),Yt=d.extend({method:I(`notifications/tasks/status`),params:Jt}),Xt=l.extend({method:I(`tasks/get`),params:s.extend({taskId:H()})}),M=f.merge(Kt),Zt=l.extend({method:I(`tasks/result`),params:s.extend({taskId:H()})}),Qt=f.loose(),$t=D.extend({method:I(`tasks/list`)}),en=O.extend({tasks:P(Kt)}),tn=l.extend({method:I(`tasks/cancel`),params:s.extend({taskId:H()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:v,BaseMetadataSchema:y,ImplementationSchema:b,ClientTasksCapabilitySchema:C,ServerTasksCapabilitySchema:ee,ClientCapabilitiesSchema:te,InitializeRequestParamsSchema:ne,InitializeRequestSchema:w,ServerCapabilitiesSchema:re,InitializeResultSchema:T,InitializedNotificationSchema:ie,PingRequestSchema:ae,ProgressSchema:oe,ProgressNotificationParamsSchema:se,ProgressNotificationSchema:E,PaginatedRequestParamsSchema:ce,PaginatedRequestSchema:D,PaginatedResultSchema:O,ResourceContentsSchema:le,TextResourceContentsSchema:ue,BlobResourceContentsSchema:fe,RoleSchema:pe,AnnotationsSchema:me,ResourceSchema:he,ResourceTemplateSchema:ge,ListResourcesRequestSchema:_e,ListResourcesResultSchema:ve,ListResourceTemplatesRequestSchema:ye,ListResourceTemplatesResultSchema:be,ResourceRequestParamsSchema:xe,ReadResourceRequestParamsSchema:Se,ReadResourceRequestSchema:Ce,ReadResourceResultSchema:we,ResourceListChangedNotificationSchema:Te,SubscribeRequestParamsSchema:Ee,SubscribeRequestSchema:De,UnsubscribeRequestParamsSchema:Oe,UnsubscribeRequestSchema:ke,ResourceUpdatedNotificationParamsSchema:Ae,ResourceUpdatedNotificationSchema:je,PromptArgumentSchema:Me,PromptSchema:Ne,ListPromptsRequestSchema:Pe,ListPromptsResultSchema:Fe,GetPromptRequestParamsSchema:Ie,GetPromptRequestSchema:Le,TextContentSchema:Re,ImageContentSchema:ze,AudioContentSchema:Be,ToolUseContentSchema:Ve,EmbeddedResourceSchema:He,ResourceLinkSchema:Ue,ContentBlockSchema:We,PromptMessageSchema:Ge,GetPromptResultSchema:Ke,PromptListChangedNotificationSchema:qe,ToolAnnotationsSchema:Je,ToolExecutionSchema:Ye,ToolSchema:Xe,ListToolsRequestSchema:Ze,ListToolsResultSchema:Qe,CallToolResultSchema:$e,CallToolRequestParamsSchema:et,CallToolRequestSchema:tt,ToolListChangedNotificationSchema:nt,LoggingLevelSchema:k,SetLevelRequestParamsSchema:rt,SetLevelRequestSchema:it,LoggingMessageNotificationParamsSchema:at,LoggingMessageNotificationSchema:ot,ModelHintSchema:st,ModelPreferencesSchema:ct,ToolChoiceSchema:lt,ToolResultContentSchema:ut,SamplingContentSchema:dt,SamplingMessageContentBlockSchema:ft,SamplingMessageSchema:pt,CreateMessageRequestParamsSchema:mt,CreateMessageRequestSchema:ht,CreateMessageResultSchema:gt,CreateMessageResultWithToolsSchema:_t,BooleanSchemaSchema:vt,StringSchemaSchema:yt,NumberSchemaSchema:bt,UntitledSingleSelectEnumSchemaSchema:xt,TitledSingleSelectEnumSchemaSchema:St,LegacyTitledEnumSchemaSchema:Ct,SingleSelectEnumSchemaSchema:wt,UntitledMultiSelectEnumSchemaSchema:Tt,TitledMultiSelectEnumSchemaSchema:Et,MultiSelectEnumSchemaSchema:Dt,EnumSchemaSchema:Ot,PrimitiveSchemaDefinitionSchema:kt,ElicitRequestFormParamsSchema:At,ElicitRequestURLParamsSchema:jt,ElicitRequestParamsSchema:Mt,ElicitRequestSchema:A,ElicitationCompleteNotificationParamsSchema:j,ElicitationCompleteNotificationSchema:Nt,ElicitResultSchema:Pt,ResourceTemplateReferenceSchema:Ft,PromptReferenceSchema:It,CompleteRequestParamsSchema:Lt,CompleteRequestSchema:Rt,CompleteResultSchema:zt,RootSchema:Bt,ListRootsRequestSchema:Vt,ListRootsResultSchema:Ht,RootsListChangedNotificationSchema:Ut,TaskCreationParamsSchema:Wt,TaskStatusSchema:Gt,TaskSchema:Kt,CreateTaskResultSchema:qt,TaskStatusNotificationParamsSchema:Jt,TaskStatusNotificationSchema:Yt,GetTaskRequestSchema:Xt,GetTaskResultSchema:M,GetTaskPayloadRequestSchema:Zt,GetTaskPayloadResultSchema:Qt,ListTasksRequestSchema:$t,ListTasksResultSchema:en,CancelTaskRequestSchema:tn,CancelTaskResultSchema:f.merge(Kt),ClientRequestSchema:U([ae,w,Rt,it,Le,Pe,_e,ye,Ce,De,ke,tt,Ze,Xt,Zt,$t,tn]),ClientNotificationSchema:U([g,E,ie,Ut,Yt]),ClientResultSchema:U([m,gt,_t,Pt,Ht,M,en,qt]),ServerRequestSchema:U([ae,ht,A,Vt,Xt,Zt,$t,tn]),ServerNotificationSchema:U([g,E,ot,je,Te,nt,qe,Yt,Nt]),ServerResultSchema:U([m,T,zt,Ke,Fe,ve,be,we,$e,Qe,M,en,qt]),CallToolResultWireSchema:W().superRefine((e,t)=>{if(!(typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0)){for(let n of aa)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(oa).pipe($e)}}let ca;function la(){return ca??=sa()}function ua(e){return e.type!==`object`}const da=new Set([`const`,`enum`,`default`,`examples`]),fa=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function pa(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function ma(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(pa(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=Wi(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&pa(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:da.has(o)?i[o]=s:fa.has(o)?i[o]=r(s,!0):i[o]=r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}const ha={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},ga={"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},_a={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};let va;function ya(){if(va)return va;let e=la();return va={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}},va}function ba(e){return Object.prototype.hasOwnProperty.call(ha,e)}function xa(e){return Object.prototype.hasOwnProperty.call(ga,e)}function Sa(e){return Object.prototype.hasOwnProperty.call(_a,e)}function Ca(e){return Sa(e)?ya().resultSchemas[e]:void 0}function wa(e){return ba(e)?ya().requestSchemas[e]:void 0}function Ta(e){return xa(e)?ya().notificationSchemas[e]:void 0}function Ea(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Da(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}const Oa={ok:!1,reason:`not-in-era`};function ka(e){return Ea(e)&&Ea(e.outputSchema)&&ua(e.outputSchema)}function Aa(e){return e}const ja={era:`2025-11-25`,hasRequestMethod:ba,hasNotificationMethod:xa,validateRequest:(e,t)=>Da(wa(e),t),validateResult:(e,t)=>Da(Ca(e),t),validateNotification:(e,t)=>Da(Ta(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Oa,validateInputResponse:()=>Oa,samplingResultVariant:((e,t)=>{let n=la();return Da(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=ia(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&ua(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(Ea(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:Aa(e)}}return{kind:`complete`,result:Aa(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>ka(e))?t:{...t,tools:n.map(e=>ka(e)?{...e,outputSchema:ma(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function Ma(){let e=or(()=>U([H(),R(),F(),er(),V(H(),e),P(e)])),t=V(H(),e),n=U([H(),R().int()]),r=H(),i=U([H(),R().int()]),a=N([`user`,`assistant`]),o=N([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=H().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=z({ttl:R().optional()}),l=z({taskId:H()}),u=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=z({_meta:u.optional()}),f=d.extend({task:c.optional()}),h=z({_meta:u.optional()}),g=z({method:H(),params:h.loose().optional()}),_=z({src:H(),mimeType:H().optional(),sizes:P(H()).optional(),theme:N([`light`,`dark`]).optional()}),v=z({icons:P(_).optional()}),y=z({name:H(),title:H().optional()}),b=y.extend({...y.shape,...v.shape,version:H(),websiteUrl:H().optional(),description:H().optional()}),x=ar(z({applyDefaults:F().optional()}),t),S=sr(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ar(z({form:x.optional(),url:t.optional()}),t.optional())),C=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),ee=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),te=z({experimental:V(H(),t).optional(),sampling:z({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:z({listChanged:F().optional()}).optional(),tasks:C.optional(),extensions:V(H(),t).optional()}),ne=z({experimental:V(H(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:z({listChanged:F().optional()}).optional(),resources:z({subscribe:F().optional(),listChanged:F().optional()}).optional(),tools:z({listChanged:F().optional()}).optional(),tasks:ee.optional(),extensions:V(H(),t).optional()}),w=z({progress:R(),total:B(R()),message:B(H())}),re=z({...h.shape,...w.shape,progressToken:n}),T=g.extend({method:I(`notifications/progress`),params:re}),ie=h.extend({level:o,logger:H().optional(),data:W()}),ae=g.extend({method:I(`notifications/message`),params:ie}),oe=z({uri:H(),mimeType:B(H()),_meta:V(H(),W()).optional()}),se=oe.extend({text:H()}),E=oe.extend({blob:s}),ce=z({audience:P(a).optional(),priority:R().min(0).max(1).optional(),lastModified:nr({offset:!0}).optional()}),D=z({...y.shape,...v.shape,uri:H(),description:B(H()),mimeType:B(H()),size:B(R()),annotations:ce.optional(),_meta:B(L({}))}),O=z({...y.shape,...v.shape,uriTemplate:H(),description:B(H()),mimeType:B(H()),annotations:ce.optional(),_meta:B(L({}))}),le=g.extend({method:I(`notifications/resources/list_changed`),params:h.optional()}),ue=h.extend({uri:H()}),de=g.extend({method:I(`notifications/resources/updated`),params:ue}),fe=z({name:H(),description:B(H()),required:B(F())}),pe=z({...y.shape,...v.shape,description:B(H()),arguments:B(P(fe)),_meta:B(L({}))}),me=g.extend({method:I(`notifications/prompts/list_changed`),params:h.optional()}),he=z({type:I(`text`),text:H(),annotations:ce.optional(),_meta:V(H(),W()).optional()}),ge=z({type:I(`image`),data:s,mimeType:H(),annotations:ce.optional(),_meta:V(H(),W()).optional()}),_e=z({type:I(`audio`),data:s,mimeType:H(),annotations:ce.optional(),_meta:V(H(),W()).optional()}),ve=z({type:I(`tool_use`),name:H(),id:H(),input:V(H(),W()),_meta:V(H(),W()).optional()}),ye=z({type:I(`resource`),resource:U([se,E]),annotations:ce.optional(),_meta:V(H(),W()).optional()}),be=D.extend({type:I(`resource_link`)}),xe=U([he,ge,_e,be,ye]),Se=z({role:a,content:xe}),Ce=z({title:H().optional(),readOnlyHint:F().optional(),destructiveHint:F().optional(),idempotentHint:F().optional(),openWorldHint:F().optional()}),we=g.extend({method:I(`notifications/tools/list_changed`),params:h.optional()}),Te=z({name:H().optional()}),Ee=z({hints:P(Te).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),De=z({mode:N([`auto`,`required`,`none`]).optional()}),Oe=z({type:I(`boolean`),title:H().optional(),description:H().optional(),default:F().optional()}),ke=z({type:I(`string`),title:H().optional(),description:H().optional(),minLength:R().optional(),maxLength:R().optional(),format:N([`email`,`uri`,`date`,`date-time`]).optional(),default:H().optional()}),Ae=z({type:N([`number`,`integer`]),title:H().optional(),description:H().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),je=z({type:I(`string`),title:H().optional(),description:H().optional(),enum:P(H()),default:H().optional()}),Me=z({type:I(`string`),title:H().optional(),description:H().optional(),oneOf:P(z({const:H(),title:H()})),default:H().optional()}),Ne=z({type:I(`string`),title:H().optional(),description:H().optional(),enum:P(H()),enumNames:P(H()).optional(),default:H().optional()}),Pe=U([je,Me]),Fe=z({type:I(`array`),title:H().optional(),description:H().optional(),minItems:R().optional(),maxItems:R().optional(),items:z({type:I(`string`),enum:P(H())}),default:P(H()).optional()}),Ie=z({type:I(`array`),title:H().optional(),description:H().optional(),minItems:R().optional(),maxItems:R().optional(),items:z({anyOf:P(z({const:H(),title:H()}))}),default:P(H()).optional()}),Le=U([Fe,Ie]),Re=U([Ne,Pe,Le]),ze=U([Re,Oe,ke,Ae]),Be=f.extend({mode:I(`form`).optional(),message:H(),requestedSchema:z({type:I(`object`),properties:V(H(),ze),required:P(H()).optional()}).catchall(W())}),Ve=z({type:I(`ref/resource`),uri:H()}),He=z({type:I(`ref/prompt`),name:H()}),Ue=z({uri:H().startsWith(`file://`),name:H().optional(),_meta:V(H(),W()).optional()}),We=te.shape,Ge=z({experimental:We.experimental,sampling:We.sampling,elicitation:We.elicitation,roots:We.roots,extensions:We.extensions}),Ke=ne.shape,qe=z({experimental:Ke.experimental,logging:Ke.logging,completions:Ke.completions,prompts:Ke.prompts,resources:Ke.resources,tools:Ke.tools,extensions:Ke.extensions}),Ye=L({progressToken:n.optional(),[Ot]:H(),[m]:b.optional(),[p]:Ge,[Je]:o.optional()}),Xe=z({...y.shape,...v.shape,description:H().optional(),inputSchema:L({$schema:H().optional(),type:I(`object`)}),outputSchema:L({$schema:H().optional()}).optional(),annotations:Ce.optional(),_meta:V(H(),W()).optional()}),Ze=z({type:I(`tool_result`),toolUseId:H(),content:P(xe),structuredContent:W().optional(),isError:F().optional(),_meta:V(H(),W()).optional()}),Qe=U([he,ge,_e,ve,Ze]),$e=z({role:a,content:U([Qe,P(Qe)]),_meta:V(H(),W()).optional()}),et=H(),tt=L({[cn]:b.optional().catch(void 0)}),nt=tt.optional();function k(e){return L({_meta:nt,resultType:et.default(`complete`),...e})}let rt=k({}),it=k({nextCursor:r.optional()}),at=k({content:P(xe),structuredContent:W().optional(),isError:F().optional()}),ot=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),tools:P(Xe),nextCursor:r.optional()}),st=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),prompts:P(pe),nextCursor:r.optional()}),ct=k({description:H().optional(),messages:P(Se)}),lt=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),resources:P(D),nextCursor:r.optional()}),ut=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),resourceTemplates:P(O),nextCursor:r.optional()}),dt=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),contents:P(U([se,E]))}),ft=k({completion:z({values:P(H()).max(100),total:R().int().optional(),hasMore:F().optional()}).loose()}),pt=k({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`])}),mt=k({ttlMs:R().int().min(0).catch(0),cacheScope:N([`public`,`private`]).catch(`private`),supportedVersions:P(H()),capabilities:qe,instructions:H().optional()}),ht=z({messages:P($e),modelPreferences:Ee.optional(),systemPrompt:H().optional(),includeContext:N([`none`,`thisServer`,`allServers`]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:P(H()).optional(),metadata:t.optional(),tools:P(Xe).optional(),toolChoice:De.optional()}),gt=z({method:I(`sampling/createMessage`),params:ht}),_t=z({method:I(`roots/list`),params:z({_meta:V(H(),W()).optional()}).optional()}),vt=z({...$e.shape,model:H(),stopReason:H().optional()}),yt=z({roots:P(Ue)}),bt=z({action:N([`accept`,`decline`,`cancel`]),content:V(H(),U([H(),R(),F(),P(H())])).optional()}),xt=z({mode:I(`url`),message:H(),url:H().url()}),St=U([Be,xt]),Ct=z({method:I(`elicitation/create`),params:St}),wt=U([gt,_t,Ct]),Tt=U([vt,yt,bt]),Et=V(H(),wt),Dt=V(H(),Tt),kt=k({inputRequests:Et.optional(),requestState:H().optional()}),At={inputResponses:Dt.optional(),requestState:H().optional()},jt=z({_meta:Ye,...At}),Mt=L({progressToken:n.optional()});function A(e,t){return z({method:I(e),params:z({_meta:Ye,...t})})}function j(e,t){return z({method:I(e),params:z({_meta:Mt.optional(),...t}).optional()})}let Nt={name:H(),arguments:V(H(),W()).optional(),...At},Pt={cursor:r.optional()},Ft=A(`tools/call`,Nt),It=A(`tools/list`,Pt),Lt=A(`prompts/list`,Pt),Rt=A(`prompts/get`,{name:H(),arguments:V(H(),H()).optional(),...At}),zt=A(`resources/list`,Pt),Bt=A(`resources/templates/list`,Pt),Vt=A(`resources/read`,{uri:H(),...At}),Ht={ref:U([He,Ve]),argument:z({name:H(),value:H()}),context:z({arguments:V(H(),H()).optional()}).optional()},Ut=A(`completion/complete`,Ht),Wt=A(`server/discover`,{}),Gt=z({toolsListChanged:F().optional(),promptsListChanged:F().optional(),resourcesListChanged:F().optional(),resourceSubscriptions:P(H()).optional()}),Kt={notifications:Gt},qt=A(`subscriptions/listen`,Kt),Jt=tt.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=L({_meta:Jt,resultType:et.default(`complete`)}),Xt={"tools/call":j(`tools/call`,Nt),"tools/list":j(`tools/list`,Pt),"prompts/get":j(`prompts/get`,{name:H(),arguments:V(H(),H()).optional()}),"prompts/list":j(`prompts/list`,Pt),"resources/list":j(`resources/list`,Pt),"resources/templates/list":j(`resources/templates/list`,Pt),"resources/read":j(`resources/read`,{uri:H()}),"completion/complete":j(`completion/complete`,Ht),"server/discover":j(`server/discover`,{}),"subscriptions/listen":j(`subscriptions/listen`,Kt)};function M(e){return L({_meta:nt,...e})}let Zt={"tools/call":M({content:P(xe),structuredContent:W().optional(),isError:F().optional()}),"tools/list":M({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),tools:P(Xe),nextCursor:r.optional()}),"prompts/get":M({description:H().optional(),messages:P(Se)}),"prompts/list":M({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),prompts:P(pe),nextCursor:r.optional()}),"resources/list":M({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),resources:P(D),nextCursor:r.optional()}),"resources/templates/list":M({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),resourceTemplates:P(O),nextCursor:r.optional()}),"resources/read":M({ttlMs:R().int().min(0),cacheScope:N([`public`,`private`]),contents:P(U([se,E]))}),"completion/complete":M({completion:z({values:P(H()).max(100),total:R().int().optional(),hasMore:F().optional()}).loose()}),"server/discover":M({ttlMs:R().int().min(0).catch(0),cacheScope:N([`public`,`private`]).catch(`private`),supportedVersions:P(H()),capabilities:qe,instructions:H().optional()}),"subscriptions/listen":M({})},Qt=L({"io.modelcontextprotocol/subscriptionId":i.optional()}),$t=z({method:I(`notifications/subscriptions/acknowledged`),params:z({_meta:Qt.optional(),notifications:Gt})}),en=z({_meta:Qt.optional(),requestId:i,reason:H().optional()}),tn=z({method:I(`notifications/cancelled`),params:en}),nn={"notifications/cancelled":tn,"notifications/progress":T,"notifications/message":ae,"notifications/resources/updated":de,"notifications/resources/list_changed":le,"notifications/tools/list_changed":we,"notifications/prompts/list_changed":me,"notifications/subscriptions/acknowledged":$t},rn=e=>z({jsonrpc:I(`2.0`),id:U([H(),R().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:h,NotificationSchema:g,IconSchema:_,IconsSchema:v,BaseMetadataSchema:y,ImplementationSchema:b,ClientTasksCapabilitySchema:C,ServerTasksCapabilitySchema:ee,ClientCapabilitiesSchema:te,ServerCapabilitiesSchema:ne,ProgressSchema:w,ProgressNotificationParamsSchema:re,ProgressNotificationSchema:T,LoggingMessageNotificationParamsSchema:ie,LoggingMessageNotificationSchema:ae,ResourceContentsSchema:oe,TextResourceContentsSchema:se,BlobResourceContentsSchema:E,AnnotationsSchema:ce,ResourceSchema:D,ResourceTemplateSchema:O,ResourceListChangedNotificationSchema:le,ResourceUpdatedNotificationParamsSchema:ue,ResourceUpdatedNotificationSchema:de,PromptArgumentSchema:fe,PromptSchema:pe,PromptListChangedNotificationSchema:me,TextContentSchema:he,ImageContentSchema:ge,AudioContentSchema:_e,ToolUseContentSchema:ve,EmbeddedResourceSchema:ye,ResourceLinkSchema:be,ContentBlockSchema:xe,PromptMessageSchema:Se,ToolAnnotationsSchema:Ce,ToolListChangedNotificationSchema:we,ModelHintSchema:Te,ModelPreferencesSchema:Ee,ToolChoiceSchema:De,BooleanSchemaSchema:Oe,StringSchemaSchema:ke,NumberSchemaSchema:Ae,UntitledSingleSelectEnumSchemaSchema:je,TitledSingleSelectEnumSchemaSchema:Me,LegacyTitledEnumSchemaSchema:Ne,SingleSelectEnumSchemaSchema:Pe,UntitledMultiSelectEnumSchemaSchema:Fe,TitledMultiSelectEnumSchemaSchema:Ie,MultiSelectEnumSchemaSchema:Le,EnumSchemaSchema:Re,PrimitiveSchemaDefinitionSchema:ze,ElicitRequestFormParamsSchema:Be,ResourceTemplateReferenceSchema:Ve,PromptReferenceSchema:He,RootSchema:Ue,ClientCapabilities2026Schema:Ge,ServerCapabilities2026Schema:qe,RequestMetaEnvelopeSchema:Ye,ToolSchema:Xe,ToolResultContentSchema:Ze,SamplingMessageContentBlockSchema:Qe,SamplingMessageSchema:$e,ResultTypeSchema:et,ResultMetaSchema:tt,ResultSchema:rt,PaginatedResultSchema:it,CallToolResultSchema:at,ListToolsResultSchema:ot,ListPromptsResultSchema:st,GetPromptResultSchema:ct,ListResourcesResultSchema:lt,ListResourceTemplatesResultSchema:ut,ReadResourceResultSchema:dt,CompleteResultSchema:ft,CacheableResultSchema:pt,DiscoverResultSchema:mt,CreateMessageRequestParamsSchema:ht,CreateMessageRequestSchema:gt,ListRootsRequestSchema:_t,CreateMessageResultSchema:vt,ListRootsResultSchema:yt,ElicitResultSchema:bt,ElicitRequestURLParamsSchema:xt,ElicitRequestParamsSchema:St,ElicitRequestSchema:Ct,InputRequestSchema:wt,InputResponseSchema:Tt,InputRequestsSchema:Et,InputResponsesSchema:Dt,InputRequiredResultSchema:kt,InputResponseRequestParamsSchema:jt,CallToolRequestSchema:Ft,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Zt,NotificationMetaSchema:Qt,SubscriptionsAcknowledgedNotificationSchema:$t,CancelledNotificationParamsSchema:en,CancelledNotificationSchema:tn,notificationSchemas2026:nn,JSONRPCResultResponseSchema:rn(rt),CallToolResultResponseSchema:rn(U([at,kt])),ListToolsResultResponseSchema:rn(ot),ListPromptsResultResponseSchema:rn(st),GetPromptResultResponseSchema:rn(U([ct,kt])),ListResourcesResultResponseSchema:rn(lt),ListResourceTemplatesResultResponseSchema:rn(ut),ReadResourceResultResponseSchema:rn(U([dt,kt])),CompleteResultResponseSchema:rn(ft),DiscoverResultResponseSchema:rn(mt)}}let Na;function Pa(){return Na??=Ma()}const Fa=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function Ia(e){return Fa.includes(e)}const La=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function Ra(e,t){if(t===void 0)return e;let n=e[La];if(n===void 0)return{...e,[La]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[La]:r}}function za(e){return e[La]}function Ba(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Va(e){return e===`public`||e===`private`}function Ha(e,t){if(e.ttlMs!==void 0&&!Ba(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!Va(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let Y=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}({});var X=class e extends Error{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Ji(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 Ji(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,qi(this,new.target)}static fromError(t,n,r){if(t===Y.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Wa(e.elicitations,n)}if(t===Y.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Ga({supported:e.supported,requested:e.requested},n)}if(t===Y.InvalidParams||t===Y.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===Y.ResourceNotFound||Object.keys(e).length===1))return new Ua(e.uri,n)}if(t===Y.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new Ka({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},Ua=class extends X{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(Y.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Wa=class extends X{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Y.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Ga=class extends X{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Y.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Ka=class extends X{static{Object.defineProperty(this,`mcpBrand`,{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(Y.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}};const qa=[`tools/call`,`prompts/get`,`resources/read`];function Ja(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||qa.includes(e))return t;throw new X(Y.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Ya(e,t){let n=za(t);if(t.resultType!==`complete`||!Ia(e))return n===void 0?t:eo(t);let r=t,i=Ba(r.ttlMs)?r.ttlMs:Qa(n),a=Va(r.cacheScope)?r.cacheScope:$a(n),o={...r,ttlMs:i,cacheScope:a};return delete o[La],o}function Xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Za(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[cn]:t}}:!Xa(n)||n[cn]!==void 0?e:{...e,_meta:{...n,[cn]:t}}}function Qa(e){return e!==void 0&&Ba(e.ttlMs)?e.ttlMs:0}function $a(e){return e!==void 0&&Va(e.cacheScope)?e.cacheScope:`private`}function eo(e){let t={...e};return delete t[La],t}const to=[`elicitation/create`,`sampling/createMessage`,`roots/list`];let no;function ro(){if(no)return no;let e=Pa();return no={request:{"elicitation/create":z({method:I(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":z({method:I(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":z({method:I(`roots/list`),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},no}function io(e){return to.includes(e)}function ao(e){return io(e)?ro().request[e]:void 0}function oo(e){return io(e)?ro().response[e]:void 0}const so={"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},co={"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 lo(e){return Object.prototype.hasOwnProperty.call(so,e)}function uo(e){return Object.prototype.hasOwnProperty.call(co,e)}function fo(e){return Object.prototype.hasOwnProperty.call(so,e)}function po(e){return lo(e)?Pa().dispatchRequestSchemas[e]:void 0}function mo(e){return fo(e)?Pa().dispatchResultSchemas[e]:void 0}function ho(e){return uo(e)?Pa().notificationSchemas2026[e]:void 0}function go(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _o(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}const vo={ok:!1,reason:`not-in-era`},yo=[Ot,p];function bo(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>go(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!go(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(go(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}const xo={era:`2026-07-28`,hasRequestMethod:lo,hasNotificationMethod:uo,hasInputRequestMethod:e=>ao(e)!==void 0,validateRequest:(e,t)=>_o(po(e),t),validateResult:(e,t)=>_o(mo(e),t),validateNotification:(e,t)=>_o(ho(e),t),validateInputRequest:(e,t)=>_o(ao(e),t),validateInputResponse:(e,t)=>_o(oo(e),t),samplingResultVariant:()=>vo,outboundEnvelope(e){return{[Ot]:e.protocolVersion,[m]:e.clientInfo,[p]:e.clientCapabilities,...e.logLevel!==void 0&&{[Je]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of yo)n in e||t.push({key:n,problem:`missing`});let n=Pa().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;if(n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`))continue;t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>ia(e),inputRequestSchema:ao,decodeResult(e,t){if(!go(t))return{kind:`invalid`,error:new J(q.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new J(q.InvalidResult,`Invalid result for ${e}: missing required resultType — 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 n!=`string`)return{kind:`invalid`,error:new J(q.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=go(n)?n:{},i=t.requestState;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new J(q.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:r,...typeof i==`string`&&{requestState:i}}}if(n!==`complete`)return{kind:`invalid`,error:new J(q.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=Co(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new J(q.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return Za(Ya(e,Ja(e,bo(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,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=Pa().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}};let So;function Co(){if(So)return So;let e=Pa();return So={"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},So}const wo=`2026-07-28`;function To(e){return e!==void 0&&ta(e)?xo:ja}function Eo(e){return e.revision===void 0?e.era===`modern`?xo.era:ja.era:To(e.revision).era}function Do(e){return ko.some(t=>t.hasRequestMethod(e))}function Oo(e){return ko.some(t=>t.hasNotificationMethod(e))}const ko=[ja,xo];function Ao(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jo(e){if(!Ao(e))return;let t=e._meta;return Ao(t)?t:void 0}function Mo(e){let t=jo(e);return t!==void 0&&Ot in t}function No(e){let t=jo(e)?.[Ot];return typeof t==`string`?t:void 0}function Po(e){return To(wo).validateEnvelopeMeta(e)}var Fo=Li({AnnotationsSchema:()=>s,AudioContentSchema:()=>c,BaseMetadataSchema:()=>l,BaseRequestParamsSchema:()=>u,BlobResourceContentsSchema:()=>d,BooleanSchemaSchema:()=>f,CallToolRequestParamsSchema:()=>h,CallToolRequestSchema:()=>g,CallToolResultSchema:()=>_,CancelTaskRequestSchema:()=>v,CancelTaskResultSchema:()=>y,CancelledNotificationParamsSchema:()=>b,CancelledNotificationSchema:()=>x,ClientCapabilitiesSchema:()=>S,ClientNotificationSchema:()=>C,ClientRequestSchema:()=>ee,ClientResultSchema:()=>te,ClientTasksCapabilitySchema:()=>ne,CompatibilityCallToolResultSchema:()=>w,CompleteRequestParamsSchema:()=>re,CompleteRequestSchema:()=>T,CompleteResultSchema:()=>ie,ContentBlockSchema:()=>ae,CreateMessageRequestParamsSchema:()=>oe,CreateMessageRequestSchema:()=>se,CreateMessageResultSchema:()=>E,CreateMessageResultWithToolsSchema:()=>ce,CreateTaskResultSchema:()=>D,CursorSchema:()=>O,DiscoverRequestSchema:()=>ue,DiscoverResultSchema:()=>de,ElicitRequestFormParamsSchema:()=>fe,ElicitRequestParamsSchema:()=>pe,ElicitRequestSchema:()=>me,ElicitRequestURLParamsSchema:()=>he,ElicitResultSchema:()=>ge,ElicitationCompleteNotificationParamsSchema:()=>_e,ElicitationCompleteNotificationSchema:()=>ve,EmbeddedResourceSchema:()=>ye,EmptyResultSchema:()=>be,EnumSchemaSchema:()=>xe,GetPromptRequestParamsSchema:()=>Se,GetPromptRequestSchema:()=>Ce,GetPromptResultSchema:()=>we,GetTaskPayloadRequestSchema:()=>Te,GetTaskPayloadResultSchema:()=>Ee,GetTaskRequestSchema:()=>De,GetTaskResultSchema:()=>Oe,IconSchema:()=>ke,IconsSchema:()=>Ae,ImageContentSchema:()=>Me,ImplementationSchema:()=>Ne,InitializeRequestParamsSchema:()=>Pe,InitializeRequestSchema:()=>Fe,InitializeResultSchema:()=>Ie,InitializedNotificationSchema:()=>Le,JSONArraySchema:()=>Re,JSONObjectSchema:()=>ze,JSONRPCErrorResponseSchema:()=>Be,JSONRPCMessageSchema:()=>Ve,JSONRPCNotificationSchema:()=>He,JSONRPCRequestSchema:()=>Ue,JSONRPCResponseSchema:()=>We,JSONRPCResultResponseSchema:()=>Ge,JSONValueSchema:()=>Ke,LegacyTitledEnumSchemaSchema:()=>Ye,ListChangedOptionsBaseSchema:()=>Xe,ListPromptsRequestSchema:()=>Ze,ListPromptsResultSchema:()=>Qe,ListResourceTemplatesRequestSchema:()=>$e,ListResourceTemplatesResultSchema:()=>et,ListResourcesRequestSchema:()=>tt,ListResourcesResultSchema:()=>nt,ListRootsRequestSchema:()=>k,ListRootsResultSchema:()=>rt,ListTasksRequestSchema:()=>it,ListTasksResultSchema:()=>at,ListToolsRequestSchema:()=>ot,ListToolsResultSchema:()=>st,LoggingLevelSchema:()=>ct,LoggingMessageNotificationParamsSchema:()=>lt,LoggingMessageNotificationSchema:()=>ut,ModelHintSchema:()=>dt,ModelPreferencesSchema:()=>ft,MultiSelectEnumSchemaSchema:()=>pt,NotificationSchema:()=>mt,NotificationsParamsSchema:()=>ht,NumberSchemaSchema:()=>gt,PaginatedRequestParamsSchema:()=>kt,PaginatedRequestSchema:()=>At,PaginatedResultSchema:()=>jt,PingRequestSchema:()=>Mt,PrimitiveSchemaDefinitionSchema:()=>A,ProgressNotificationParamsSchema:()=>j,ProgressNotificationSchema:()=>Nt,ProgressSchema:()=>Pt,ProgressTokenSchema:()=>Ft,PromptArgumentSchema:()=>It,PromptListChangedNotificationSchema:()=>Lt,PromptMessageSchema:()=>Rt,PromptReferenceSchema:()=>zt,PromptSchema:()=>Bt,ReadResourceRequestParamsSchema:()=>Vt,ReadResourceRequestSchema:()=>Ht,ReadResourceResultSchema:()=>Ut,RelatedTaskMetadataSchema:()=>Wt,RequestIdSchema:()=>Gt,RequestMetaSchema:()=>Kt,RequestSchema:()=>qt,ResourceContentsSchema:()=>Jt,ResourceLinkSchema:()=>Yt,ResourceListChangedNotificationSchema:()=>Xt,ResourceRequestParamsSchema:()=>M,ResourceSchema:()=>Zt,ResourceTemplateReferenceSchema:()=>Qt,ResourceTemplateSchema:()=>$t,ResourceUpdatedNotificationParamsSchema:()=>en,ResourceUpdatedNotificationSchema:()=>tn,ResultMetaObjectSchema:()=>nn,ResultSchema:()=>rn,RoleSchema:()=>an,RootSchema:()=>on,RootsListChangedNotificationSchema:()=>sn,SamplingContentSchema:()=>dn,SamplingMessageContentBlockSchema:()=>fn,SamplingMessageSchema:()=>pn,ServerCapabilitiesSchema:()=>mn,ServerNotificationSchema:()=>hn,ServerRequestSchema:()=>gn,ServerResultSchema:()=>_n,ServerTasksCapabilitySchema:()=>vn,SetLevelRequestParamsSchema:()=>yn,SetLevelRequestSchema:()=>bn,SingleSelectEnumSchemaSchema:()=>xn,StringSchemaSchema:()=>Sn,SubscribeRequestParamsSchema:()=>Cn,SubscribeRequestSchema:()=>wn,SubscriptionFilterSchema:()=>Tn,SubscriptionsAcknowledgedNotificationParamsSchema:()=>En,SubscriptionsAcknowledgedNotificationSchema:()=>Dn,SubscriptionsListenRequestParamsSchema:()=>On,SubscriptionsListenRequestSchema:()=>kn,SubscriptionsListenResultMetaSchema:()=>An,SubscriptionsListenResultSchema:()=>jn,TaskAugmentedRequestParamsSchema:()=>Mn,TaskCreationParamsSchema:()=>Nn,TaskMetadataSchema:()=>Pn,TaskSchema:()=>Fn,TaskStatusNotificationParamsSchema:()=>In,TaskStatusNotificationSchema:()=>Ln,TaskStatusSchema:()=>Rn,TextContentSchema:()=>zn,TextResourceContentsSchema:()=>Bn,TitledMultiSelectEnumSchemaSchema:()=>Vn,TitledSingleSelectEnumSchemaSchema:()=>Hn,ToolAnnotationsSchema:()=>Un,ToolChoiceSchema:()=>Wn,ToolExecutionSchema:()=>Gn,ToolListChangedNotificationSchema:()=>Kn,ToolResultContentSchema:()=>qn,ToolSchema:()=>Jn,ToolUseContentSchema:()=>Yn,UnsubscribeRequestParamsSchema:()=>Xn,UnsubscribeRequestSchema:()=>Zn,UntitledMultiSelectEnumSchemaSchema:()=>Qn,UntitledSingleSelectEnumSchemaSchema:()=>$n});const Z=e=>Ue.safeParse(e).success,Io=e=>He.safeParse(e).success,Lo=e=>Ge.safeParse(e).success,Ro=e=>Be.safeParse(e).success,zo=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`,Bo=e=>Fe.safeParse(e).success;function Vo(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Ho(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Uo=`x-mcp-header`,Wo=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Go=new Set([`string`,`integer`,`boolean`,`number`]);function Ko(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(Uo in o){if(!a||i.length===0)return`${Yo(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[Uo];if(typeof e!=`string`||e.length===0)return`${Yo(i)}: x-mcp-header MUST be a non-empty string`;if(!Wo.test(e))return`${Yo(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!Go.has(r))return`${Yo(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of qo){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&Jo.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}const qo=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],Jo=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function Yo(e){return e.length===0?`<root>`:e.join(`.`)}Y.InvalidRequest,Y.UnsupportedProtocolVersion,Y.InvalidParams,Y.MethodNotFound,Y.InvalidParams,Y.MissingRequiredClientCapability,Y.ParseError,Y.InvalidRequest,Y.MethodNotFound,Y.UnsupportedProtocolVersion,Y.MissingRequiredClientCapability;function Xo(e,t,n,r,i){return{kind:`reject`,rung:e,cell:t,httpStatus:n,code:r.code,message:r.message,...r.data!==void 0&&{data:r.data},settled:i}}function Zo(e){if(!Mo(e))return!1;let t=No(e);if(t===void 0||!ta(t))return!1;let n=jo(e);return n!==void 0&&Po(n).length===0}function Qo(e,t){switch(e.reason){case`http-method`:return Xo(`http-method`,`modern-only-method-not-allowed`,405,new X(-32e3,`Method not allowed.`),!0);case`batch`:return Xo(`jsonrpc-shape`,`modern-only-batch-not-supported`,400,new X(Y.InvalidRequest,`Bad Request: JSON-RPC batches are not supported by this endpoint`),!0);case`response`:return Xo(`jsonrpc-shape`,`modern-only-response-post`,400,new X(Y.InvalidRequest,`Bad Request: JSON-RPC responses cannot be posted to this endpoint`),!0);case`notification`:return;case`initialize`:case`no-claim`:{let n=e.requestedVersion;return Xo(`era-classification`,`modern-only-missing-envelope`,400,n===void 0?new X(Y.UnsupportedProtocolVersion,`Unsupported protocol version: the request did not name a protocol version`,{supported:[...t]}):new Ga({supported:[...t],requested:n}),!0)}}}function $o(e,t){return cr(e,t)}function es(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function ts(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}let ns=!1;const rs=`draft-2020-12`;function os(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:rs});else if(n.vendor===`zod`){if(!(`_zod`in e))throw 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().`);ns||(ns=!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.")),r=lr(e,{target:rs,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&ss(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function ss(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||ss(e)))}return!1}function cs(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function ls(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>cs(e)).join(`, `)}:{success:!0,data:n.value}}function us(e){let t=lr(e,{target:rs,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}const ds=/\\\.\\d\{(\d+)\}/;function fs(e){let t=ds.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>nr({local:e,offset:t,precision:n}))))}function ps(e,t){let n;switch(e){case`email`:n=[ir()];break;case`uri`:n=[ur()];break;case`date`:n=[tr()];break;case`date-time`:n=fs(t);break}return new Set(n.map(e=>us(e)).filter(e=>e!==void 0))}function ms(e,t,n){return n===`zod`?ps(e,t).has(t):!0}function hs(e){let t=os(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _s(e){try{return os(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new X(Y.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}const vs=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function ys(e){return vs.has(e)||e.startsWith(`x-`)}const bs=new Set([`$schema`,...Object.keys(fe.shape.requestedSchema.shape)]),xs={string:es([Sn,$n,Hn,Ye]),number:es([gt]),integer:es([gt]),boolean:es([f]),array:es([Qn,Vn])},Ss=new Set(Sn.shape.format.unwrap().options);function Cs(e,t,n,r){if(!gs(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(xs,e.type)?xs[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||ys(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Ss.has(e.format)?(typeof s!=`string`||!ms(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function ws(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&gs(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Cs(n,`properties.${e}`,t,r)])):bs.has(i)?n[i]=a:ys(i)||r.push(i);if(r.length>0)throw new X(Y.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Ts(e,t){if(!gs(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!$o(A,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Es(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Es(e,t[r],`${n}[${r}]`)):!gs(e)||!gs(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Es(r,t[e],i):ys(e)?[]:[i]})}function Ds(e){if(!ts(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=ws(_s(e.requestedSchema),t),r=$o(fe.shape.requestedSchema,n);if(!r.success)throw new X(Y.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Ts(n,r.error.message)}`);let i=Es(n,r.data);if(i.length>0)throw new X(Y.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new X(Y.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Os(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw 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}}}Object.assign(Os,{elicit(e){try{return{method:`elicitation/create`,params:Ds(e)}}catch(e){throw e instanceof X?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function ks(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function As(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof J?t.reason:new J(q.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof J?t.reason:new J(q.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function js(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}const Ms=`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`.split(`.`),Ns={IdJagTokenExchangeResponseSchema:je,OAuthClientInformationFullSchema:_t,OAuthClientInformationSchema:vt,OAuthClientMetadataSchema:yt,OAuthClientRegistrationErrorSchema:bt,OAuthErrorResponseSchema:xt,OAuthMetadataSchema:St,OAuthProtectedResourceMetadataSchema:Ct,OAuthTokenRevocationRequestSchema:wt,OAuthTokensSchema:Tt,OpenIdProviderDiscoveryMetadataSchema:Et,OpenIdProviderMetadataSchema:Dt},Ps={},Fs={};function Is(e,t){let n=e.slice(0,-6);Ps[n]=t,Fs[n]=e=>t.safeParse(e).success}for(let e of Ms)Is(e,Fo[e]);for(let[e,t]of Object.entries(Ns))Is(e,t);Object.freeze(Ps),Object.freeze(Fs);function Ls(e){switch(e){case`initialize`:case`notifications/initialized`:return To(void 0);case`server/discover`:return To(wo);default:return}}const Rs=[Ot,m,p,Je],zs=[`inputResponses`,`requestState`];function Bs(e,t){let n=e.params;if(!Js(n))return{message:e,lifted:{}};let r=n._meta,i=Js(r)?Rs.filter(e=>e in r):[],a=t===`request`?zs.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&Js(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function Vs(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason===`not-in-era`))return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function Hs(e){return()=>e}const Us=Hs(void 0);function Ws(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:Hs(t)}}}let Gs;function Ks(e,t){Gs(e,t)}var qs=class{_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{Gs=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??un,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new J(q.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,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new J(q.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});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 n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Lo(e)||Ro(e)?this._onresponse(e):Z(e)?this._onrequest(e,t):Io(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},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 e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new J(q.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=Bs(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=Eo(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(Oo(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;i===void 0&&a===void 0||Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=Bs(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=Eo(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(Y.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(Do(n.method)&&!i.hasRequestMethod(n.method)){o(Y.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(Y.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(Y.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:Zs(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?Us:Hs(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),ts(t))return u(e,t,n);let i=Vs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(Y.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:Y.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Lo(e)?n(e):n(X.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),ts(t))return this._requestWithSchemaViaCodec(r,e,t,n);let i=Vs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return To(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ls(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Do(t)&&!e.hasRequestMethod(t))throw new J(q.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof J?e:new J(q.RequestTimeout,String(e))}let m=e.era===wo&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),v=!1,y=e=>{v||(this._progressHandlers.delete(h),m===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof J?e:new J(q.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(v=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(Qs(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;ls(n,o).then(e=>{e.success?d(e.data):f(new J(q.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>y(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let b=r?.timeout??6e4;this._setupTimeout(h,b,r?.maxTotalTimeout,()=>y(new J(q.RequestTimeout,`Request timed out`,{timeout:b})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new J(q.NotConnected,`Not connected`);if(Oo(t.method)&&!e.hasNotificationMethod(t.method))throw new J(q.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 r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.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(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!Do(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new X(Y.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await ls(t.params,{...r.params});if(!a.success)throw new X(Y.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!Oo(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new X(Y.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await ls(t.params,{...r.params});if(!i.success)throw new X(Y.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ys(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Js(a)&&Js(i)?{...a,...i}:i}return n}function Xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zs(e){let t={},n=[];if(!Xs(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!Xs(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function Qs(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}var $s=zi(K((exports=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))(),1);function ec(e){if(e)try{return $s.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function tc(e){return e===`application/json`?!0:ec(e)===`application/json`}var nc=class{_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
|
|
4
4
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return rc(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}};function rc(e){return Ve.parse(JSON.parse(e))}function ic(e){return JSON.stringify(e)+`
|
|
@@ -13,4 +13,4 @@ import{proxiedFetch as e}from"./proxyFetch-BL46N-Gu.js";import{SESSION_ID as t,c
|
|
|
13
13
|
|
|
14
14
|
`))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(e){return this._supportedProtocolVersions.includes(e)&&e>=`2025-11-25`}async writePrimingEvent(e,t,n,r){if(!this._eventStore||!this.supportsEmptySSEData(r))return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a,o=new ReadableStream({start:e=>{i=e},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};return this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,r),new Response(o,{headers:s})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a,o=!1,s,c=new ReadableStream({start:e=>{i=e},cancel:()=>{o=!0,a!==void 0&&clearInterval(a),s!==void 0&&this._streamMapping.get(s)?.controller===i&&this._streamMapping.delete(s)}}),l=new Set;if(s=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(l.add(e),!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}}),this._closed||o){try{i.close()}catch{}return this.createJsonErrorResponse(404,-32001,`Session not found`)}if(this._streamMapping.get(s)?.cleanup(),this._streamMapping.set(s,{controller:i,encoder:r,replayedEventIds:l,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(s);try{i.close()}catch{}}}),s!==this._standaloneSseStreamId&&![...this._requestToStreamMapping.values()].includes(s)){this._streamMapping.delete(s);try{i.close()}catch{}}return this._streamMapping.get(s)?.controller===i&&(a=this.startKeepAlive(i,r)),new Response(c,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
|
|
15
15
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);if(!tc(e.headers.get(`content-type`)))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=e,i;if(t?.parsedBody===void 0)try{i=await e.json()}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else i=t.parsedBody;let a;try{a=Array.isArray(i)?i.map(e=>Ve.parse(e)):[Ve.parse(i)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let o=a.some(e=>Bo(e));if(o){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(a.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!o){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);if(!a.some(e=>Z(e))){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r});return new Response(null,{status:202})}let s=crypto.randomUUID(),c=a.find(e=>Bo(e)),l=c?c.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??le;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(s,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(s)}});for(let e of a)Z(e)&&this._requestToStreamMapping.set(e.id,s);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r})});let u=new TextEncoder,d,f,p=new ReadableStream({start:e=>{d=e},cancel:()=>{f!==void 0&&clearInterval(f),this._streamMapping.get(s)?.controller===d&&this._streamMapping.delete(s)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of a)Z(e)&&(this._streamMapping.set(s,{controller:d,encoder:u,cleanup:()=>{f!==void 0&&clearInterval(f),this._streamMapping.delete(s);try{d.close()}catch{}}}),this._requestToStreamMapping.set(e.id,s));await this.writePrimingEvent(d,u,s,l);for(let e of a){let n,i;Z(e)&&this._eventStore&&this.supportsEmptySSEData(l)&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:r,closeSSEStream:n,closeStandaloneSSEStream:i})}return this._streamMapping.get(s)?.controller===d&&(f=this.startKeepAlive(d,u)),new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((Lo(e)||Ro(e))&&(n=e.id),n===void 0){if(Lo(e)||Ro(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&(t===void 0||!n.replayedEventIds?.has(t))&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e),i=this._streamMapping.get(r)),i?.controller&&i?.encoder&&(t===void 0||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(Lo(e)||Ro(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},Ju=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Yu=e=>e instanceof Ju?e:new Ju(e.message,{cause:e}),Xu=global.Request,Zu=class extends Xu{constructor(e,t){typeof e==`object`&&td in e&&(e=e[td]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Qu=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},$u=Symbol(`wrapBodyStream`),ed=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Zu(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[$u]){let e;a.body=new ReadableStream({async pull(t){try{e||=br.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=br.toWeb(r);return new Zu(t,a)},td=Symbol(`getRequestCache`),nd=Symbol(`requestCache`),rd=Symbol(`incomingKey`),id=Symbol(`urlKey`),ad=Symbol(`headersKey`),od=Symbol(`abortControllerKey`),sd={get method(){return this[rd].method||`GET`},get url(){return this[id]},get headers(){return this[ad]||=Qu(this[rd])},[Symbol(`getAbortController`)](){return this[td](),this[od]},[td](){return this[od]||=new AbortController,this[nd]||=ed(this.method,this[id],this.headers,this[rd],this[od])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(sd,e,{get(){return this[td]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(sd,e,{value:function(){return this[td]()[e]()}})}),Object.defineProperty(sd,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[nd]};return`Request (lightweight) ${n(r,{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(sd,Zu.prototype);var cd=(e,t)=>{let n=Object.create(sd);n[rd]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof wr)throw new Ju(`Absolute URL for :path is not allowed in HTTP/2`);try{n[id]=new URL(r).href}catch(e){throw new Ju(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof wr?e.authority:e.headers.host)||t;if(!i)throw new Ju(`Missing host header`);let a;if(e instanceof wr){if(a=e.scheme,!(a===`http`||a===`https`))throw new Ju(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new Ju(`Invalid host header`);return n[id]=o.href,n},ld=Symbol(`responseCache`),ud=Symbol(`getResponseCache`),dd=Symbol(`cache`),fd=global.Response,pd=class e{#body;#init;[ud](){return delete this[dd],this[ld]||=new fd(this.#body,this.#init)}constructor(t,n){let r;if(this.#body=t,n instanceof e){let e=n[ld];if(e){this.#init=e,this[ud]();return}else this.#init=n.#init,r=new Headers(n.#init.headers)}else this.#init=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[dd]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[dd];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[ud]().headers}get status(){return this[dd]?.[0]??this[ud]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(pd.prototype,e,{get(){return this[ud]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(pd.prototype,e,{value:function(){return this[ud]()[e]()}})}),Object.defineProperty(pd.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){let r={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[ld]};return`Response (lightweight) ${n(r,{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(pd,fd),Object.setPrototypeOf(pd.prototype,fd.prototype);async function md(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function hd(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function gd(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:hd(e.getReader(),t)}var _d=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},vd=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=dr);var yd=Symbol(`outgoingEnded`),bd=Symbol(`incomingDraining`),xd=500,Sd=64*1024*1024,Cd=e=>{let t=e;if(e.destroyed||t[bd])return;if(t[bd]=!0,e instanceof wr){try{e.stream?.close?.(Tr.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},a=setTimeout(i,xd);a.unref?.();let o=e=>{n+=e.length,n>Sd&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},wd=()=>new Response(null,{status:400}),Td=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),Ed=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},Dd=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},Od=async(e,t)=>{let[n,r,i]=e[dd],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=_d(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=_d(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(Dd(t),await gd(r,t)?.catch(e=>Ed(e,t))),t[yd]?.()},kd=e=>typeof e.then==`function`,Ad=async(e,t,n={})=>{if(kd(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(Td);if(dd in e)return Od(e,t);let r=_d(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await md(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&Dd(t),await hd(n,t,o))}else r[vd]||(t.writeHead(e.status,r),t.end());t[yd]?.()},jd=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Zu&&(Object.defineProperty(global,`Request`,{value:Zu}),Object.defineProperty(global,`Response`,{value:pd})),async(r,i)=>{let a,o;try{o=cd(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[$u]=!0,r.on(`end`,()=>{s=!0}),r instanceof wr&&(i[yd]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{Cd(r)})})}),i.on(`finish`,()=>{s||Cd(r)})),i.on(`close`,()=>{o[od]&&(r.errored?o[od].abort(r.errored.toString()):i.writableFinished||o[od].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{Cd(r)})})}),a=e(o,{incoming:r,outgoing:i}),dd in a)return Od(a,i)}catch(e){if(a)return Ed(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Yu(e)),!a)return}else a=o?Td(e):wd()}try{return await Ad(a,i,t)}catch(e){return Ed(e,i)}}},Md=class{_webStandardTransport;_requestListener;_requestContext=new WeakMap;constructor(e={}){this._webStandardTransport=new qu(e),this._requestListener=jd(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}setSupportedProtocolVersions(e){this._webStandardTransport.setSupportedProtocolVersions(e)}async handleRequest(e,t,n){let r=e.auth;await jd(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const Nd=(e,t)=>new Promise((n,r)=>{let i=[],a=0;e.on(`data`,n=>{if(a+=n.length,a>t){r(Error(`request entity too large (limit ${t} bytes)`)),e.destroy();return}i.push(n)}),e.on(`end`,()=>n(Buffer.concat(i).toString(`utf-8`))),e.on(`error`,r)});var Pd=class{onclose;onerror;onmessage;get sessionId(){return this._sessionId}_sessionId;_sseResponse;constructor(e,t){this._endpoint=e,this.res=t,this._sessionId=_r()}async close(){this._sseResponse?.end(),this._sseResponse=void 0,this.onclose?.()}async handleMessage(e,t){let n;try{n=Ve.parse(e)}catch(e){throw this.onerror?.(e),e}this.onmessage?.(n,t)}async handlePostMessage(e,t,n){if(!this._sseResponse){let e=`SSE connection not established`;throw t.writeHead(500).end(e),Error(e)}let r=e.auth,i;try{let t=e.headers[`content-type`]??``;if(t.split(`;`)[0].trim().toLowerCase()!==`application/json`)throw Error(`Unsupported content-type: ${t}`);i=n??await Nd(e,4194304)}catch(e){t.writeHead(400).end(String(e)),this.onerror?.(e);return}try{await this.handleMessage(typeof i==`string`?JSON.parse(i):i,{authInfo:r})}catch{t.writeHead(400).end(`Invalid message: ${i}`);return}t.writeHead(202).end(`Accepted`)}async send(e){if(!this._sseResponse)throw Error(`Not connected`);this._sseResponse.write(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}async start(){if(this._sseResponse)throw Error(`SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this.res.writeHead(200,{"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"Content-Type":`text/event-stream`});let e=new Er(this._endpoint,`http://localhost`);e.searchParams.set(`sessionId`,this._sessionId);let t=e.pathname+e.search+e.hash;this.res.write(`event: endpoint\ndata: ${t}\n\n`),this._sseResponse=this.res,this.res.on(`close`,()=>{this._sseResponse=void 0,this.onclose?.()})}};const Fd=e=>new Promise(t=>{let n=[],r;e.on(`data`,e=>{n.push(e)}).on(`end`,()=>{r=Buffer.concat(n).toString();try{t(JSON.parse(r))}catch(n){a.error(`Error parsing body`,{bodyLength:r.length,bodyPreview:r.substring(0,100),contentType:e.headers[`content-type`],error:n}),t(null)}})}),Id=(e,t)=>JSON.stringify({error:{code:e,message:t},id:null,jsonrpc:`2.0`}),Ld=(e,t)=>{if(e instanceof Response){let n={};return e.headers.forEach((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}),t.writeHead(e.status,e.statusText,n).end(e.statusText),!0}return!1},Rd=async(e,t)=>{t&&await t(e);try{await e.close()}catch(t){a.error(`Error closing server`,{error:t,serverType:typeof e})}},zd=async({activeTransports:e,createServer:t,enableJsonResponse:n,endpoint:r,eventStore:i,onClose:o,onConnect:s,req:c,res:l,stateless:u})=>{if(c.method===`POST`&&new URL(c.url,`http://localhost`).pathname===r){try{let r=Array.isArray(c.headers[`mcp-session-id`])?c.headers[`mcp-session-id`][0]:c.headers[`mcp-session-id`],a,d,f=await Fd(c);if(r){let t=e[r];if(!t)return l.setHeader(`Content-Type`,`application/json`),l.writeHead(404).end(Id(-32001,`Session not found`)),!0;a=t.transport,d=t.server}else if(!r&&Bo(f)){a=new Md({enableJsonResponse:n,eventStore:i||new Or,onsessioninitialized:t=>{!u&&t&&(e[t]={server:d,transport:a})},sessionIdGenerator:u?void 0:_r});let r=!1;a.onclose=async()=>{let t=a.sessionId;r||(r=!0,!u&&t&&e[t]?(await Rd(d,o),delete e[t]):u&&await Rd(d,o))};try{d=await t(c)}catch(e){return Ld(e,l)||l.writeHead(500).end(`Error creating server`),!0}return d.connect(a),s&&await s(d),await a.handleRequest(c,l,f),!0}else if(u&&!r&&!Bo(f)){a=new Md({enableJsonResponse:n,eventStore:i||new Or,onsessioninitialized:()=>{},sessionIdGenerator:void 0});try{d=await t(c)}catch(e){return Ld(e,l)||l.writeHead(500).end(`Error creating server`),!0}return d.connect(a),s&&await s(d),await a.handleRequest(c,l,f),!0}else return l.setHeader(`Content-Type`,`application/json`),l.writeHead(400).end(Id(-32e3,`Bad Request: No valid session ID provided`)),!0;return await a.handleRequest(c,l,f),!0}catch(e){a.error(`Error handling request`,{error:e}),l.setHeader(`Content-Type`,`application/json`),l.writeHead(500).end(Id(-32603,`Internal Server Error`))}return!0}if(c.method===`GET`&&new URL(c.url,`http://localhost`).pathname===r){let t=c.headers[`mcp-session-id`],n=t?e[t]:void 0;if(!t)return l.writeHead(400).end(`No sessionId`),!0;if(!n)return l.writeHead(400).end(`No active transport`),!0;let r=c.headers[`last-event-id`];return r?a.info(`Client reconnecting with Last-Event-ID for session`,{lastEventId:r,sessionId:t}):a.info(`Establishing new SSE stream for session`,{sessionId:t}),await n.transport.handleRequest(c,l),!0}if(c.method===`DELETE`&&new URL(c.url,`http://localhost`).pathname===r){a.info(`Received delete request`);let t=c.headers[`mcp-session-id`];if(!t)return l.writeHead(400).end(`Invalid or missing sessionId`),!0;a.info(`Received delete request for session`,{sessionId:t});let n=e[t];if(!n)return l.writeHead(400).end(`No active transport`),!0;try{await n.transport.handleRequest(c,l),await Rd(n.server,o)}catch(e){a.error(`Error handling delete request`,{error:e}),l.writeHead(500).end(`Error handling delete request`)}return!0}return!1},Bd=async({activeTransports:e,createServer:t,endpoint:n,onClose:r,onConnect:i,req:o,res:s})=>{if(o.method===`GET`&&new URL(o.url,`http://localhost`).pathname===n){let n=new Pd(`/messages`,s),c;try{c=await t(o)}catch(e){return Ld(e,s)||s.writeHead(500).end(`Error creating server`),!0}e[n.sessionId]=n;let l=!1,u=!1;s.on(`close`,async()=>{l=!0,!u&&(u=!0,await Rd(c,r),delete e[n.sessionId])});try{await c.connect(n),await n.send({jsonrpc:`2.0`,method:`sse/connection`,params:{message:`SSE Connection established`}}),i&&await i(c)}catch(e){l||(a.error(`Error connecting to server`,{error:e}),s.writeHead(500).end(`Error connecting to server`))}return!0}if(o.method===`POST`&&o.url?.startsWith(`/messages`)){let t=new URL(o.url,`https://example.com`).searchParams.get(`sessionId`);if(!t)return s.writeHead(400).end(`No sessionId`),!0;let n=e[t];return n?(await n.handlePostMessage(o,s),!0):(s.writeHead(400).end(`No active transport`),!0)}return!1},Vd=async({createServer:e,enableJsonResponse:t,eventStore:n,host:s=`::`,onClose:c,onConnect:l,onUnhandledRequest:u,port:d,sseEndpoint:f=`/sse`,stateless:p,streamEndpoint:m=`/mcp`})=>{let h={},g={},_=Dr.createServer(async(s,d)=>{let _=r(s.headers)??i;await o(_,async()=>{if(s.headers.origin)try{let e=new URL(s.headers.origin);d.setHeader(`Access-Control-Allow-Origin`,e.origin),d.setHeader(`Access-Control-Allow-Credentials`,`true`),d.setHeader(`Access-Control-Allow-Methods`,`GET, POST, OPTIONS`),d.setHeader(`Access-Control-Allow-Headers`,`*`),d.setHeader(`Access-Control-Expose-Headers`,`mcp-session-id`)}catch(e){a.error(`Error parsing origin`,{error:e})}if(s.method===`OPTIONS`){d.writeHead(204),d.end();return}if(s.method===`GET`&&s.url===`/ping`){d.writeHead(200).end(`pong`);return}f&&await Bd({activeTransports:h,createServer:e,endpoint:f,onClose:c,onConnect:l,req:s,res:d})||m&&await zd({activeTransports:g,createServer:e,enableJsonResponse:t,endpoint:m,eventStore:n,onClose:c,onConnect:l,req:s,res:d,stateless:p})||(u?await u(s,d):d.writeHead(404).end())})});return await new Promise(e=>{_.listen(d,s,()=>{e(void 0)})}),{close:async()=>{for(let e of Object.values(h))await e.close();for(let e of Object.values(g))await e.transport.close();return new Promise((e,t)=>{_.close(n=>{if(n){t(n);return}e()})})}}};var Hd=class{_readBuffer;_started=!1;_closed=!1;constructor(e=Cr.stdin,t=Cr.stdout,n){this._stdin=e,this._stdout=t,this._readBuffer=new nc({maxBufferSize:n?.maxBufferSize})}onclose;onerror;onmessage;_ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this.onerror?.(e),this.close().catch(()=>{})};async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror),this._stdout.on(`error`,this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdout.off(`error`,this._onstdouterror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(Error(`StdioServerTransport is closed`)):new Promise((t,n)=>{let r=ic(e),i=!1,a=e=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),n(e))},o=()=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),t())};if(this._stdout.once(`error`,a),this._stdout.write(r)){if(i)return;i=!0,this._stdout.off(`error`,a),t()}else i||this._stdout.once(`drain`,o)})}};const Ud=3e3;var Wd=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(e,t,n){this._wire=e,this._onInstanceClose=t,this._outboundIntercept=n}async start(){}async send(e,t){if(Lo(e)||Ro(e)){let{id:t}=e;t!==void 0&&this._settle(t)}if(!this._closed&&this._outboundIntercept?.(e)!==`handled`)return this._wire.send(e,t)}setProtocolVersion=e=>{this._wire.setProtocolVersion?.(e)};deliver(e,t){if(!this._closed){if(Z(e))this._pendingRequests.add(e.id);else if(Io(e)&&e.method===`notifications/cancelled`){let t=e.params?.requestId;t!==void 0&&this._settle(t)}this.onmessage?.(e,t)}}async whenRequestsAnswered(e){return this._closed||this._pendingRequests.size===0?!0:await new Promise(t=>{let n=()=>{clearTimeout(r),t(!0)},r=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter(e=>e!==n),t(!1)},e);this._drainWaiters.push(n)})}async close(){if(!this._closed){this._closed=!0,this._pendingRequests.clear(),this._releaseDrainWaiters();try{this._onInstanceClose()}finally{this.onclose?.()}}}_settle(e){this._pendingRequests.delete(e),this._pendingRequests.size===0&&this._releaseDrainWaiters()}_releaseDrainWaiters(){let e=this._drainWaiters;this._drainWaiters=[];for(let t of e)t()}};function Gd(e){let t=e.params;if(e.method===`initialize`&&!Zo(t)){let e=typeof t==`object`&&t&&typeof t.protocolVersion==`string`?t.protocolVersion:void 0;return{kind:`legacy`,reason:`initialize`,...e!==void 0&&{requestedVersion:e}}}if(!Mo(t))return{kind:`legacy`,reason:`no-claim`};let n=jo(t),r=(n===void 0?[]:Po(n))[0];if(r!==void 0)return{kind:`invalid-envelope`,issue:r};let i=No(t);return i===void 0||!ea.includes(i)?{kind:`unsupported-revision`,requested:i??`unknown`}:{kind:`modern`,revision:i,classification:{era:`modern`,revision:i}}}function Kd(e,t={}){let n=t.legacy??`serve`,r=t.transport??new Hd,i={phase:`opening`},a,o=!1,s=()=>o||i.phase===`closed`,c=e=>{try{t.onerror?.(e)}catch{}},l=(e,t,n,i)=>r.send({jsonrpc:`2.0`,id:e,error:{code:t,message:n,...i!==void 0&&{data:i}}}).catch(e=>c(qd(e))),u=new Cu(t.maxSubscriptions??yu),d=e=>{if(!Io(e))return;let t=u.routeOutbound(e);if(t!==`passthrough`){for(let e of t)r.send({jsonrpc:`2.0`,...e}).catch(e=>c(qd(e)));return`handled`}},f=async e=>{if(Z(e)&&e.method===`subscriptions/listen`){let t=jo(e.params),n=Mo(e.params)?(t===void 0?[]:Po(t))[0]:{key:`_meta`,problem:`the per-request envelope is required on protocol revision 2026-07-28`},i=No(e.params),a;if(n!==void 0)a={jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${n.key}: ${n.problem}`}};else if(i===void 0||!ea.includes(i)){let t=new Ga({supported:[...ea],requested:i??`unknown`});a={jsonrpc:`2.0`,id:e.id,error:{code:t.code,message:t.message,data:t.data}}}else a=u.serve(e);return await r.send(`error`in a?a:{jsonrpc:`2.0`,method:a.method,params:a.params}).catch(e=>c(qd(e))),!0}if(Io(e)&&e.method===`notifications/cancelled`){let t=e.params?.requestId;if(t!==void 0&&u.cancel(t))return!0}return!1},p=(e,t,n)=>{let r=Qo({kind:`legacy`,reason:t,...n!==void 0&&{requestedVersion:n}},ea);return r===void 0?Promise.resolve():(c(Error(`Rejected 2025-era request on a modern-only stdio connection (${r.cell}): ${r.message}`)),l(e.id,r.code,r.message,r.data))},m=e=>{o||e===a||S()},h=async(t,n)=>{let i=await e({era:t}),a=i instanceof Lu?i.server:i;t===`modern`&&(Ks(a,n),Nu(a,ea),u.setServerCapabilities(a.getCapabilities(),Pu(a)));let o=new Wd(r,()=>m(o),t===`modern`?d:void 0);return await i.connect(o),{product:i,channel:o}},g=e=>e.product.close().catch(e=>c(qd(e))),_=async e=>{a=e.channel;try{await e.channel.whenRequestsAnswered(Ud)||c(Error(`Discarded the probe instance with requests still unanswered after ${Ud}ms; continuing with the fallback`)),await e.product.close()}catch(e){c(qd(e))}finally{a=void 0}},v=async e=>{if(i.phase===`closed`)return;if(i.phase===`pinned`){if(i.era===`modern`&&Z(e)&&e.method===`initialize`&&!Zo(e.params)){await p(e,`initialize`,e.params!==null&&typeof e.params==`object`&&typeof e.params.protocolVersion==`string`?e.params.protocolVersion:void 0);return}if(i.era===`modern`&&await f(e))return;i.instance.channel.deliver(e);return}if(!Z(e)&&!Io(e)){c(Error(`Discarded a JSON-RPC response received before the connection negotiated an era`));return}let t=Gd(e);switch(t.kind){case`invalid-envelope`:{let n=`Invalid _meta envelope for protocol revision 2026-07-28: ${t.issue.key}: ${t.issue.problem}`;Z(e)?await l(e.id,Y.InvalidParams,n,{envelope:t.issue}):c(Error(`Discarded a notification with a malformed envelope: ${n}`));return}case`unsupported-revision`:if(Z(e)){let n=new Ga({supported:[...ea],requested:t.requested});c(n),await l(e.id,n.code,n.message,n.data)}else c(Error(`Discarded a notification claiming unsupported protocol revision ${t.requested}`));return;case`modern`:if(Z(e)&&e.method===`server/discover`){if(i.phase===`probe`){i.instance.channel.deliver(e,{classification:t.classification});return}let n=await h(`modern`,t.revision);if(s()){await g(n);return}i={phase:`probe`,instance:n},n.channel.deliver(e,{classification:t.classification});return}if(i.phase===`probe`){if(Io(e)){i.instance.channel.deliver(e,{classification:t.classification});return}i={phase:`pinned`,era:`modern`,instance:i.instance}}else{let e=await h(`modern`,t.revision);if(s()){await g(e);return}i={phase:`pinned`,era:`modern`,instance:e}}if(await f(e))return;i.instance.channel.deliver(e,{classification:t.classification});return;case`legacy`:{if(n===`reject`){Z(e)&&await p(e,t.reason,t.requestedVersion);return}if(i.phase===`probe`){if(await _(i.instance),s())return;i={phase:`opening`}}let r=await h(`legacy`);if(s()){await g(r);return}i={phase:`pinned`,era:`legacy`,instance:r},i.instance.channel.deliver(e);return}}},y=[],b=!1,x=async()=>{if(!b){b=!0;try{for(;y.length>0;){let e=y.shift();try{await v(e)}catch(t){Z(e)&&await l(e.id,Y.InternalError,`Internal server error`),c(qd(t))}}}finally{b=!1}}},S=async()=>{if(o||i.phase===`closed`)return;o=!0;let e=i;i={phase:`closed`};for(let e of u.teardownAll())await r.send(e).catch(e=>c(qd(e)));(e.phase===`probe`||e.phase===`pinned`)&&await e.instance.product.close().catch(e=>c(qd(e))),await r.close().catch(e=>c(qd(e)))};r.onmessage=e=>{y.push(e),x()},r.onerror=e=>{c(e),(i.phase===`probe`||i.phase===`pinned`)&&i.instance.channel.onerror?.(e)},r.onclose=()=>{if(o||i.phase===`closed`)return;o=!0;let e=i;i={phase:`closed`},(e.phase===`probe`||e.phase===`pinned`)&&e.instance.product.close().catch(e=>c(qd(e)))};let C=r.start().catch(e=>{throw c(qd(e)),e});return C.catch(()=>{}),{close:async()=>{await C.catch(()=>{}),await S()}}}function qd(e){return e instanceof Error?e:Error(String(e))}const Jd=()=>n.supportNewMcpProtocol?{mode:`auto`}:void 0;export{Ar as AccessControlBlockError,jr as ConfigurationError,Or as InMemoryEventStore,Mr as ProtocolEraMismatchError,Nr as ProxyConnectionError,Fu as Server,Hd as StdioServerTransport,xi as compressClientInfo,vi as getSessionData,wi as initializeTrafficMirror,ri as isUsableSerial,Oi as logRequestCounts,Ai as proxyServer,Lr as redactCliArgs,Kd as serveStdio,Vd as startHTTPServer,Jd as upstreamVersionNegotiation};
|
|
16
|
-
//# sourceMappingURL=upstreamNegotiation-
|
|
16
|
+
//# sourceMappingURL=upstreamNegotiation-CO-zQc38.js.map
|