emceepee 0.3.5 → 0.3.6

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/emceepee.js CHANGED
@@ -46,12 +46,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
46
46
  `:`[${W[B]}\r
47
47
  ]`;continue}if($+=W[B],W[B]==="\\")J=!0;else if(G&&W[B]==="]")G=!1;else if(!G&&W[B]==="[")G=!0}try{new RegExp($)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return $}function tQ(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((W,$)=>({...W,[$]:u(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",$]})??M0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:u(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Y;if(Q.keyType?._def.typeName===P.ZodString&&Q.keyType._def.checks?.length){let{type:W,...$}=rQ(Q.keyType._def,X);return{...Y,propertyNames:$}}else if(Q.keyType?._def.typeName===P.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===P.ZodBranded&&Q.keyType._def.type._def.typeName===P.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:W,...$}=oQ(Q.keyType._def,X);return{...Y,propertyNames:$}}return Y}function s3(Q,X){if(X.mapStrategy==="record")return tQ(Q,X);let Y=u(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||M0(X),W=u(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||M0(X);return{type:"array",maxItems:125,items:{type:"array",items:[Y,W],minItems:2,maxItems:2}}}function e3(Q){let X=Q.values,W=Object.keys(Q.values).filter((J)=>{return typeof X[X[J]]!=="number"}).map((J)=>X[J]),$=Array.from(new Set(W.map((J)=>typeof J)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:W}}function QB(Q){return Q.target==="openAi"?void 0:{not:M0({...Q,currentPath:[...Q.currentPath,"not"]})}}function XB(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var e8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function WB(Q,X){if(X.target==="openApi3")return YB(Q,X);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((W)=>(W._def.typeName in e8)&&(!W._def.checks||!W._def.checks.length))){let W=Y.reduce(($,J)=>{let G=e8[J._def.typeName];return G&&!$.includes(G)?[...$,G]:$},[]);return{type:W.length>1?W:W[0]}}else if(Y.every((W)=>W._def.typeName==="ZodLiteral"&&!W.description)){let W=Y.reduce(($,J)=>{let G=typeof J._def.value;switch(G){case"string":case"number":case"boolean":return[...$,G];case"bigint":return[...$,"integer"];case"object":if(J._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(W.length===Y.length){let $=W.filter((J,G,H)=>H.indexOf(J)===G);return{type:$.length>1?$:$[0],enum:Y.reduce((J,G)=>{return J.includes(G._def.value)?J:[...J,G._def.value]},[])}}}else if(Y.every((W)=>W._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((W,$)=>[...W,...$._def.values.filter((J)=>!W.includes(J))],[])};return YB(Q,X)}var YB=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((W,$)=>u(W._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((W)=>!!W&&(!X.strictUnions||typeof W==="object"&&Object.keys(W).length>0));return Y.length?{anyOf:Y}:void 0};function $B(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:e8[Q.innerType._def.typeName],nullable:!0};return{type:[e8[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let W=u(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if(W&&"$ref"in W)return{allOf:[W],nullable:!0};return W&&{...W,nullable:!0}}let Y=u(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function JB(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let W of Q.checks)switch(W.kind){case"int":Y.type="integer",N5(Y,"type",W.message,X);break;case"min":if(X.target==="jsonSchema7")if(W.inclusive)s(Y,"minimum",W.value,W.message,X);else s(Y,"exclusiveMinimum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMinimum=!0;s(Y,"minimum",W.value,W.message,X)}break;case"max":if(X.target==="jsonSchema7")if(W.inclusive)s(Y,"maximum",W.value,W.message,X);else s(Y,"exclusiveMaximum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMaximum=!0;s(Y,"maximum",W.value,W.message,X)}break;case"multipleOf":s(Y,"multipleOf",W.value,W.message,X);break}return Y}function GB(Q,X){let Y=X.target==="openAi",W={type:"object",properties:{}},$=[],J=Q.shape();for(let H in J){let B=J[H];if(B===void 0||B._def===void 0)continue;let z=sw(B);if(z&&Y){if(B._def.typeName==="ZodOptional")B=B._def.innerType;if(!B.isNullable())B=B.nullable();z=!1}let K=u(B._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(K===void 0)continue;if(W.properties[H]=K,!z)$.push(H)}if($.length)W.required=$;let G=aw(Q,X);if(G!==void 0)W.additionalProperties=G;return W}function aw(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return u(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function sw(Q){try{return Q.isOptional()}catch{return!0}}var HB=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return u(Q.innerType._def,X);let Y=u(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:M0(X)},Y]}:M0(X)};var BB=(Q,X)=>{if(X.pipeStrategy==="input")return u(Q.in._def,X);else if(X.pipeStrategy==="output")return u(Q.out._def,X);let Y=u(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),W=u(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,W].filter(($)=>$!==void 0)}};function zB(Q,X){return u(Q.type._def,X)}function KB(Q,X){let W={type:"array",uniqueItems:!0,items:u(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)s(W,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)s(W,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return W}function VB(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,W)=>u(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[]),additionalItems:u(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,W)=>u(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[])}}function FB(Q){return{not:M0(Q)}}function AB(Q){return M0(Q)}var qB=(Q,X)=>{return u(Q.innerType._def,X)};var DB=(Q,X,Y)=>{switch(X){case P.ZodString:return rQ(Q,Y);case P.ZodNumber:return JB(Q,Y);case P.ZodObject:return GB(Q,Y);case P.ZodBigInt:return c3(Q,Y);case P.ZodBoolean:return p3();case P.ZodDate:return w5(Q,Y);case P.ZodUndefined:return FB(Y);case P.ZodNull:return XB(Y);case P.ZodArray:return m3(Q,Y);case P.ZodUnion:case P.ZodDiscriminatedUnion:return WB(Q,Y);case P.ZodIntersection:return r3(Q,Y);case P.ZodTuple:return VB(Q,Y);case P.ZodRecord:return tQ(Q,Y);case P.ZodLiteral:return t3(Q,Y);case P.ZodEnum:return o3(Q);case P.ZodNativeEnum:return e3(Q);case P.ZodNullable:return $B(Q,Y);case P.ZodOptional:return HB(Q,Y);case P.ZodMap:return s3(Q,Y);case P.ZodSet:return KB(Q,Y);case P.ZodLazy:return()=>Q.getter()._def;case P.ZodPromise:return zB(Q,Y);case P.ZodNaN:case P.ZodNever:return QB(Y);case P.ZodEffects:return n3(Q,Y);case P.ZodAny:return M0(Y);case P.ZodUnknown:return AB(Y);case P.ZodDefault:return i3(Q,Y);case P.ZodBranded:return oQ(Q,Y);case P.ZodReadonly:return qB(Q,Y);case P.ZodCatch:return d3(Q,Y);case P.ZodPipeline:return BB(Q,Y);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return((W)=>{return})(X)}};function u(Q,X,Y=!1){let W=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,W,Y);if(H!==h3)return H}if(W&&!Y){let H=ew(W,X);if(H!==void 0)return H}let $={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,$);let J=DB(Q,Q.typeName,X),G=typeof J==="function"?u(J(),X):J;if(G)Qb(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return $.jsonSchema=G,H}return $.jsonSchema=G,G}var ew=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:nQ(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,W)=>X.currentPath[W]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),M0(X);return X.$refStrategy==="seen"?M0(X):void 0}}},Qb=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var Z5=(Q,X)=>{let Y=l3(X),W=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((B,[z,K])=>({...B,[z]:u(K._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,z]},!0)??M0(Y)}),{}):void 0,$=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,J=u(Q._def,$===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,$]},!1)??M0(Y),G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)J.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!W)W={};if(!W[Y.openAiAnyTypeName])W[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let H=$===void 0?W?{...J,[Y.definitionPath]:W}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,$].join("/"),[Y.definitionPath]:{...W,[$]:J}};if(Y.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function Xb(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function R5(Q,X){if(s0(Q))return UQ(Q,{target:Xb(X?.target),io:X?.pipeStrategy??"input"});return Z5(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function E5(Q){let Y=c1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=NQ(Y);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function S5(Q,X){let Y=c0(Q,X);if(!Y.success)throw Y.error;return Y.data}var Yb=60000;class Q4{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(TQ,(X)=>{this._oncancel(X)}),this.setNotificationHandler(vQ,(X)=>{this._onprogress(X)}),this.setRequestHandler(kQ,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(_Q,async(X,Y)=>{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(yQ,async(X,Y)=>{let W=async()=>{let $=X.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue($,Y.sessionId)){if(G.type==="response"||G.type==="error"){let H=G.message,B=H.id,z=this._requestResolvers.get(B);if(z)if(this._requestResolvers.delete(B),G.type==="response")z(H);else{let K=H,V=new S(K.error.code,K.error.message,K.error.data);z(V)}else{let K=G.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${B}`))}continue}await this._transport?.send(G.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask($,Y.sessionId);if(!J)throw new S(k.InvalidParams,`Task not found: ${$}`);if(!N6(J.status))return await this._waitForTaskUpdate($,Y.signal),await W();if(N6(J.status)){let G=await this._taskStore.getTaskResult($,Y.sessionId);return this._clearTaskQueue($),{...G,_meta:{...G._meta,[j6]:{taskId:$}}}}return await W()};return await W()}),this.setRequestHandler(fQ,async(X,Y)=>{try{let{tasks:W,nextCursor:$}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:W,nextCursor:$,_meta:{}}}catch(W){throw new S(k.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(hQ,async(X,Y)=>{try{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new S(k.InvalidParams,`Task not found: ${X.params.taskId}`);if(N6(W.status))throw new S(k.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new S(k.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...$}}catch(W){if(W instanceof S)throw W;throw new S(k.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,W,$=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:$,onTimeout:W})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),S.fromError(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=($)=>{Y?.($),this._onerror($)};let W=this._transport?.onmessage;this._transport.onmessage=($,J)=>{if(W?.($,J),a6($)||Z3($))this._onresponse($);else if(m8($))this._onrequest($,J);else if(P3($))this._onnotification($);else this._onerror(Error(`Unknown message type: ${JSON.stringify($)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let X=S.fromError(k.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,$=Q.params?._meta?.[j6]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:k.MethodNotFound,message:"Method not found"}};if($&&this._taskMessageQueue)this._enqueueTaskMessage($,{type:"error",message:z,timestamp:Date.now()},W?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else W?.send(z).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let G=N3(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,B={signal:J.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{let K={relatedRequestId:Q.id};if($)K.relatedTask={taskId:$};await this.notification(z,K)},sendRequest:async(z,K,V)=>{let q={...V,relatedRequestId:Q.id};if($&&!q.relatedTask)q.relatedTask={taskId:$};let F=q.relatedTask?.taskId??$;if(F&&H)await H.updateTaskStatus(F,"input_required");return await this.request(z,K,q)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:$,taskStore:H,taskRequestedTtl:G?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,B)).then(async(z)=>{if(J.signal.aborted)return;let K={result:z,jsonrpc:"2.0",id:Q.id};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"response",message:K,timestamp:Date.now()},W?.sessionId);else await W?.send(K)},async(z)=>{if(J.signal.aborted)return;let K={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:k.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"error",message:K,timestamp:Date.now()},W?.sessionId);else await W?.send(K)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,W=Number(X),$=this._progressHandlers.get(W);if(!$){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&J&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(H){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),J(H);return}$(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),a6(Q))Y(Q);else{let J=new S(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let W=this._responseHandlers.get(X);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let $=!1;if(a6(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let G=J.task;if(typeof G.taskId==="string")$=!0,this._taskProgressTokens.set(G.taskId,X)}}if(!$)this._progressHandlers.delete(X);if(a6(Q))W(Q);else{let J=S.fromError(Q.error.code,Q.error.message,Q.error.data);W(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:W}=Y??{};if(!W){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}return}let $;try{let J=await this.request(Q,Q6,Y);if(J.task)$=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new S(k.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:$},Y);if(yield{type:"taskStatus",task:G},N6(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};else if(G.status==="failed")yield{type:"error",error:new S(k.InternalError,`Task ${$} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new S(k.InternalError,`Task ${$} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};return}let H=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,H)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J,task:G,relatedTask:H}=Y??{};return new Promise((B,z)=>{let K=(O)=>{z(O)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),G)this.assertTaskCapability(Q.method)}catch(O){K(O);return}Y?.signal?.throwIfAborted();let V=this._requestMessageId++,q={...Q,jsonrpc:"2.0",id:V};if(Y?.onprogress)this._progressHandlers.set(V,Y.onprogress),q.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:V}};if(G)q.params={...q.params,task:G};if(H)q.params={...q.params,_meta:{...q.params?._meta||{},[j6]:H}};let F=(O)=>{this._responseHandlers.delete(V),this._progressHandlers.delete(V),this._cleanupTimeout(V),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:V,reason:String(O)}},{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((w)=>this._onerror(Error(`Failed to send cancellation: ${w}`)));let N=O instanceof S?O:new S(k.RequestTimeout,String(O));z(N)};this._responseHandlers.set(V,(O)=>{if(Y?.signal?.aborted)return;if(O instanceof Error)return z(O);try{let N=c0(X,O.result);if(!N.success)z(N.error);else B(N.data)}catch(N){z(N)}}),Y?.signal?.addEventListener("abort",()=>{F(Y?.signal?.reason)});let A=Y?.timeout??Yb,D=()=>F(S.fromError(k.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(V,A,Y?.maxTotalTimeout,D,Y?.resetTimeoutOnProgress??!1);let L=H?.taskId;if(L){let O=(N)=>{let w=this._responseHandlers.get(V);if(w)w(N);else this._onerror(Error(`Response handler missing for side-channeled request ${V}`))};this._requestResolvers.set(V,O),this._enqueueTaskMessage(L,{type:"request",message:q,timestamp:Date.now()}).catch((N)=>{this._cleanupTimeout(V),z(N)})}else this._transport.send(q,{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((O)=>{this._cleanupTimeout(V),z(O)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},xQ,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},gQ,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},S3,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let G={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[j6]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[j6]:X.relatedTask}}};this._transport?.send(G,X).catch((H)=>this._onerror(H))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[j6]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=E5(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,(W,$)=>{let J=S5(Q,W);return Promise.resolve(X(J,$))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=E5(Q);this._notificationHandlers.set(Y,(W)=>{let $=S5(Q,W);return Promise.resolve(X($))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,W)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let W of Y)if(W.type==="request"&&m8(W.message)){let $=W.message.id,J=this._requestResolvers.get($);if(J)J(new S(k.InternalError,"Task cancelled or completed")),this._requestResolvers.delete($);else this._onerror(Error(`Resolver missing for request ${$} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)Y=W.pollInterval}catch{}return new Promise((W,$)=>{if(X.aborted){$(new S(k.InvalidRequest,"Request cancelled"));return}let J=setTimeout(W,Y);X.addEventListener("abort",()=>{clearTimeout(J),$(new S(k.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await Y.createTask(W,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(W)=>{let $=await Y.getTask(W,X);if(!$)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return $},storeTaskResult:async(W,$,J)=>{await Y.storeTaskResult(W,$,J,X);let G=await Y.getTask(W,X);if(G){let H=n8.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),N6(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Y.getTaskResult(W,X)},updateTaskStatus:async(W,$,J)=>{let G=await Y.getTask(W,X);if(!G)throw new S(k.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(N6(G.status))throw new S(k.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${$}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus(W,$,J,X);let H=await Y.getTask(W,X);if(H){let B=n8.parse({method:"notifications/tasks/status",params:H});if(await this.notification(B),N6(H.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Y.listTasks(W,X)}}}}function LB(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function aQ(Q,X){let Y={...Q};for(let W in X){let $=W,J=X[$];if(J===void 0)continue;let G=Y[$];if(LB(G)&&LB(J))Y[$]={...G,...J};else Y[$]=J}return Y}var rL=O9(TF(),1),tL=O9(oL(),1);function wf(){let Q=new rL.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return tL.default(Q),Q}class i4{constructor(Q){this._ajv=Q??wf()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class UJ{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function DY(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function LY(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class jJ extends Q4{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(t8.options.map((Y,W)=>[Y,W])),this.isMessageIgnored=(Y,W)=>{let $=this._loggingLevels.get(W);return $?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get($):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new i4,this.setRequestHandler(W5,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(CQ,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(O5,async(Y,W)=>{let $=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,G=t8.safeParse(J);if(G.success)this._loggingLevels.set($,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new UJ(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=aQ(this._capabilities,Q)}setRequestHandler(Q,X){let W=c1(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let $;if(s0(W)){let G=W;$=G._zod?.def?.value??G.value}else{let G=W;$=G._def?.value??G.value}if(typeof $!=="string")throw Error("Schema method literal must be a string");if($==="tools/call"){let G=async(H,B)=>{let z=c0(m9,H);if(!z.success){let F=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid tools/call request: ${F}`)}let{params:K}=z.data,V=await Promise.resolve(X(H,B));if(K.task){let F=c0(Q6,V);if(!F.success){let A=F.error instanceof Error?F.error.message:String(F.error);throw new S(k.InvalidParams,`Invalid task creation result: ${A}`)}return F.data}let q=c0(M6,V);if(!q.success){let F=q.error instanceof Error?q.error.message:String(q.error);throw new S(k.InvalidParams,`Invalid tools/call result: ${F}`)}return q.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){LY(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;DY(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:EQ.includes(X)?X:U6,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},e1)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],W=Array.isArray(Y.content)?Y.content:[Y.content],$=W.some((B)=>B.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,G=J?Array.isArray(J.content)?J.content:[J.content]:[],H=G.some((B)=>B.type==="tool_use");if($){if(W.some((B)=>B.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let B=new Set(G.filter((K)=>K.type==="tool_use").map((K)=>K.id)),z=new Set(W.filter((K)=>K.type==="tool_result").map((K)=>K.toolUseId));if(B.size!==z.size||![...B].every((K)=>z.has(K)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},U5,X);return this.request({method:"sampling/createMessage",params:Q},s8,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},c9,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},$=await this.request({method:"elicitation/create",params:W},c9,X);if($.action==="accept"&&$.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)($.content);if(!G.valid)throw new S(k.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(J){if(J instanceof S)throw J;throw new S(k.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return $}}}createElicitationCompletionNotifier(Q,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},M5,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var sL=Symbol.for("mcp.completable");function MJ(Q){return!!Q&&typeof Q==="object"&&sL in Q}function eL(Q){return Q[sL]?.complete}var aL;(function(Q){Q.Completable="McpCompletable"})(aL||(aL={}));var bf=/^[A-Za-z0-9._-]{1,128}$/;function Pf(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!bf.test(Q)){let Y=Q.split("").filter((W)=>!/[A-Za-z0-9._-]/.test(W)).filter((W,$,J)=>J.indexOf(W)===$);return X.push(`Tool name contains invalid characters: ${Y.map((W)=>`"${W}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function Zf(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let Y of X)console.warn(` - ${Y}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function NJ(Q){let X=Pf(Q);return Zf(Q,X.warnings),X.isValid}class wJ{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,Y){let W={taskSupport:"required",...X.execution};if(W.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,W,X._meta,Y)}}class PJ{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new jJ(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new wJ(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(x6(dQ)),this.server.assertCanSetRequestHandler(x6(m9)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(dQ,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let W=g9(X.inputSchema);return W?R5(W,{strictUnions:!0,pipeStrategy:"input"}):Rf})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let W=g9(X.outputSchema);if(W)Y.outputSchema=R5(W,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(m9,async(Q,X)=>{try{let Y=this._registeredTools[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Tool ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Tool ${Q.params.name} disabled`);let W=!!Q.params.task,$=Y.execution?.taskSupport,J="createTask"in Y.handler;if(($==="required"||$==="optional")&&!J)throw new S(k.InternalError,`Tool ${Q.params.name} has taskSupport '${$}' but was not registered with registerToolTask`);if($==="required"&&!W)throw new S(k.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if($==="optional"&&!W&&J)return await this.handleAutomaticTaskPolling(Y,Q,X);let G=await this.validateToolInput(Y,Q.params.arguments,Q.params.name),H=await this.executeToolHandler(Y,G,X);if(W)return H;return await this.validateToolOutput(Y,H,Q.params.name),H}catch(Y){if(Y instanceof S){if(Y.code===k.UrlElicitationRequired)throw Y}return this.createToolError(Y instanceof Error?Y.message:String(Y))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,Y){if(!Q.inputSchema)return;let $=g9(Q.inputSchema)??Q.inputSchema,J=await jQ($,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=MQ(G);throw new S(k.InvalidParams,`Input validation error: Invalid arguments for tool ${Y}: ${H}`)}return J.data}async validateToolOutput(Q,X,Y){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new S(k.InvalidParams,`Output validation error: Tool ${Y} has an output schema but no structured content was provided`);let W=g9(Q.outputSchema),$=await jQ(W,X.structuredContent);if(!$.success){let J="error"in $?$.error:"Unknown error",G=MQ(J);throw new S(k.InvalidParams,`Output validation error: Invalid structured content for tool ${Y}: ${G}`)}}async executeToolHandler(Q,X,Y){let W=Q.handler;if("createTask"in W){if(!Y.taskStore)throw Error("No task store provided.");let J={...Y,taskStore:Y.taskStore};if(Q.inputSchema)return await Promise.resolve(W.createTask(X,J));else return await Promise.resolve(W.createTask(J))}if(Q.inputSchema)return await Promise.resolve(W(X,Y));else return await Promise.resolve(W(Y))}async handleAutomaticTaskPolling(Q,X,Y){if(!Y.taskStore)throw Error("No task store provided for task-capable tool.");let W=await this.validateToolInput(Q,X.params.arguments,X.params.name),$=Q.handler,J={...Y,taskStore:Y.taskStore},G=W?await Promise.resolve($.createTask(W,J)):await Promise.resolve($.createTask(J)),H=G.task.taskId,B=G.task,z=B.pollInterval??5000;while(B.status!=="completed"&&B.status!=="failed"&&B.status!=="cancelled"){await new Promise((V)=>setTimeout(V,z));let K=await Y.taskStore.getTask(H);if(!K)throw new S(k.InternalError,`Task ${H} not found during polling`);B=K}return await Y.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(x6(iQ)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(iQ,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return x3(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return y3(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new S(k.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let Y=this._registeredPrompts[X.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${X.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${X.name} disabled`);if(!Y.argsSchema)return n4;let $=c1(Y.argsSchema)?.[Q.params.argument.name];if(!MJ($))return n4;let J=eL($);if(!J)return n4;let G=await J(Q.params.argument.value,Q.params.context);return XO(G)}async handleResourceCompletion(Q,X){let Y=Object.values(this._registeredResourceTemplates).find((J)=>J.resourceTemplate.uriTemplate.toString()===X.uri);if(!Y){if(this._registeredResources[X.uri])return n4;throw new S(k.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let W=Y.resourceTemplate.completeCallback(Q.params.argument.name);if(!W)return n4;let $=await W(Q.params.argument.value,Q.params.context);return XO($)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(x6(uQ)),this.server.assertCanSetRequestHandler(x6(lQ)),this.server.assertCanSetRequestHandler(x6(mQ)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(uQ,async(Q,X)=>{let Y=Object.entries(this._registeredResources).filter(([$,J])=>J.enabled).map(([$,J])=>({uri:$,name:J.name,...J.metadata})),W=[];for(let $ of Object.values(this._registeredResourceTemplates)){if(!$.resourceTemplate.listCallback)continue;let J=await $.resourceTemplate.listCallback(X);for(let G of J.resources)W.push({...$.metadata,...G})}return{resources:[...Y,...W]}}),this.server.setRequestHandler(lQ,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(mQ,async(Q,X)=>{let Y=new URL(Q.params.uri),W=this._registeredResources[Y.toString()];if(W){if(!W.enabled)throw new S(k.InvalidParams,`Resource ${Y} disabled`);return W.readCallback(Y,X)}for(let $ of Object.values(this._registeredResourceTemplates)){let J=$.resourceTemplate.uriTemplate.match(Y.toString());if(J)return $.readCallback(Y,J,X)}throw new S(k.InvalidParams,`Resource ${Y} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(x6(cQ)),this.server.assertCanSetRequestHandler(x6(pQ)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(cQ,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?Sf(X.argsSchema):void 0}})})),this.server.setRequestHandler(pQ,async(Q,X)=>{let Y=this._registeredPrompts[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${Q.params.name} disabled`);if(Y.argsSchema){let W=g9(Y.argsSchema),$=await jQ(W,Q.params.arguments);if(!$.success){let H="error"in $?$.error:"Unknown error",B=MQ(H);throw new S(k.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${B}`)}let J=$.data,G=Y.callback;return await Promise.resolve(G(J,X))}else{let W=Y.callback;return await Promise.resolve(W(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...Y){let W;if(typeof Y[0]==="object")W=Y.shift();let $=Y[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let J=this._createRegisteredResource(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let J=this._createRegisteredResourceTemplate(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}}registerResource(Q,X,Y,W){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let $=this._createRegisteredResource(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let $=this._createRegisteredResourceTemplate(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}}_createRegisteredResource(Q,X,Y,W,$){let J={name:Q,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({uri:null}),update:(G)=>{if(typeof G.uri<"u"&&G.uri!==Y){if(delete this._registeredResources[Y],G.uri)this._registeredResources[G.uri]=J}if(typeof G.name<"u")J.name=G.name;if(typeof G.title<"u")J.title=G.title;if(typeof G.metadata<"u")J.metadata=G.metadata;if(typeof G.callback<"u")J.readCallback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendResourceListChanged()}};return this._registeredResources[Y]=J,J}_createRegisteredResourceTemplate(Q,X,Y,W,$){let J={resourceTemplate:Y,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(B)=>{if(typeof B.name<"u"&&B.name!==Q){if(delete this._registeredResourceTemplates[Q],B.name)this._registeredResourceTemplates[B.name]=J}if(typeof B.title<"u")J.title=B.title;if(typeof B.template<"u")J.resourceTemplate=B.template;if(typeof B.metadata<"u")J.metadata=B.metadata;if(typeof B.callback<"u")J.readCallback=B.callback;if(typeof B.enabled<"u")J.enabled=B.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=J;let G=Y.uriTemplate.variableNames;if(Array.isArray(G)&&G.some((B)=>!!Y.completeCallback(B)))this.setCompletionRequestHandler();return J}_createRegisteredPrompt(Q,X,Y,W,$){let J={title:X,description:Y,argsSchema:W===void 0?void 0:t6(W),callback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(G)=>{if(typeof G.name<"u"&&G.name!==Q){if(delete this._registeredPrompts[Q],G.name)this._registeredPrompts[G.name]=J}if(typeof G.title<"u")J.title=G.title;if(typeof G.description<"u")J.description=G.description;if(typeof G.argsSchema<"u")J.argsSchema=t6(G.argsSchema);if(typeof G.callback<"u")J.callback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=J,W){if(Object.values(W).some((H)=>{let B=H instanceof B1?H._def?.innerType:H;return MJ(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,W,$,J,G,H,B){NJ(Q);let z={title:X,description:Y,inputSchema:QO(W),outputSchema:QO($),annotations:J,execution:G,_meta:H,handler:B,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(K)=>{if(typeof K.name<"u"&&K.name!==Q){if(typeof K.name==="string")NJ(K.name);if(delete this._registeredTools[Q],K.name)this._registeredTools[K.name]=z}if(typeof K.title<"u")z.title=K.title;if(typeof K.description<"u")z.description=K.description;if(typeof K.paramsSchema<"u")z.inputSchema=t6(K.paramsSchema);if(typeof K.outputSchema<"u")z.outputSchema=t6(K.outputSchema);if(typeof K.callback<"u")z.handler=K.callback;if(typeof K.annotations<"u")z.annotations=K.annotations;if(typeof K._meta<"u")z._meta=K._meta;if(typeof K.enabled<"u")z.enabled=K.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=z,this.setToolRequestHandlers(),this.sendToolListChanged(),z}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let Y,W,$,J;if(typeof X[0]==="string")Y=X.shift();if(X.length>1){let H=X[0];if(bJ(H)){if(W=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!bJ(X[0]))J=X.shift()}else if(typeof H==="object"&&H!==null)J=X.shift()}let G=X[0];return this._createRegisteredTool(Q,void 0,Y,W,$,J,{taskSupport:"forbidden"},void 0,G)}registerTool(Q,X,Y){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:W,description:$,inputSchema:J,outputSchema:G,annotations:H,_meta:B}=X;return this._createRegisteredTool(Q,W,$,J,G,H,{taskSupport:"forbidden"},B,Y)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let Y;if(typeof X[0]==="string")Y=X.shift();let W;if(X.length>1)W=X.shift();let $=X[0],J=this._createRegisteredPrompt(Q,void 0,Y,W,$);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}registerPrompt(Q,X,Y){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:W,description:$,argsSchema:J}=X,G=this._createRegisteredPrompt(Q,W,$,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Rf={type:"object",properties:{}};function YO(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function Ef(Q){return"_def"in Q||"_zod"in Q||YO(Q)}function bJ(Q){if(typeof Q!=="object"||Q===null)return!1;if(Ef(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(YO)}function QO(Q){if(!Q)return;if(bJ(Q))return t6(Q);return Q}function Sf(Q){let X=c1(Q);if(!X)return[];return Object.entries(X).map(([Y,W])=>{let $=pH(W),J=dH(W);return{name:Y,description:$,required:!J}})}function x6(Q){let Y=c1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=NQ(Y);if(typeof W==="string")return W;throw Error("Schema method literal must be a string")}function XO(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var n4={completion:{values:[],hasMore:!1}};import WO from"node:process";class o4{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
48
48
  `);if(Q===-1)return null;let X=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),If(X)}clear(){this._buffer=void 0}}function If(Q){return u9.parse(JSON.parse(Q))}function OY(Q){return JSON.stringify(Q)+`
49
- `}class ZJ{constructor(Q=WO.stdin,X=WO.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new o4,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}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)}processReadBuffer(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(Q){return new Promise((X)=>{let Y=OY(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}import{readFileSync as Gh}from"fs";import UY from"node:crypto";var JO="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jY=32;var Tf=16,GO=10,$O=281474976710655;var D9;(function(Q){Q.Base32IncorrectEncoding="B32_ENC_INVALID",Q.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",Q.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",Q.EncodeTimeNegative="ENC_TIME_NEG",Q.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",Q.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",Q.PRNGDetectFailure="PRNG_DETECT",Q.ULIDInvalid="ULID_INVALID",Q.Unexpected="UNEXPECTED",Q.UUIDInvalid="UUID_INVALID"})(D9||(D9={}));class V8 extends Error{constructor(Q,X){super(`${X} (${Q})`);this.name="ULIDError",this.code=Q}}function Cf(Q){let X=Math.floor(Q()*jY)%jY;return JO.charAt(X)}function kf(Q){let X=vf(),Y=X&&(X.crypto||X.msCrypto)||(typeof UY<"u"?UY:null);if(typeof Y?.getRandomValues==="function")return()=>{let W=new Uint8Array(1);return Y.getRandomValues(W),W[0]/256};else if(typeof Y?.randomBytes==="function")return()=>Y.randomBytes(1).readUInt8()/256;else if(UY?.randomBytes)return()=>UY.randomBytes(1).readUInt8()/256;throw new V8(D9.PRNGDetectFailure,"Failed to find a reliable PRNG")}function vf(){if(yf())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function _f(Q,X){let Y="";for(;Q>0;Q--)Y=Cf(X)+Y;return Y}function xf(Q,X=GO){if(isNaN(Q))throw new V8(D9.EncodeTimeValueMalformed,`Time must be a number: ${Q}`);else if(Q>$O)throw new V8(D9.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${$O}: ${Q}`);else if(Q<0)throw new V8(D9.EncodeTimeNegative,`Time must be positive: ${Q}`);else if(Number.isInteger(Q)===!1)throw new V8(D9.EncodeTimeValueMalformed,`Time must be an integer: ${Q}`);let Y,W="";for(let $=X;$>0;$--)Y=Q%jY,W=JO.charAt(Y)+W,Q=(Q-Y)/jY;return W}function yf(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function f1(Q,X){let Y=X||kf(),W=!Q||isNaN(Q)?Date.now():Q;return xf(W,GO)+_f(Tf,Y)}function RJ(Q){return Q.type==="http"}function EJ(Q){return Q.type==="stdio"}class SJ{configs=new Map;logger;constructor(Q={}){this.logger=Q.logger}addConfig(Q,X,Y){let W=this.configs.has(Q);return this.configs.set(Q,{name:Q,type:"http",url:X,addedAt:new Date,addedBy:Y}),this.logger?.info(W?"server_config_updated":"server_config_added",{server:Q,type:"http",url:X,addedBy:Y}),!W}addStdioConfig(Q,X,Y,W,$){let J=this.configs.has(Q);return this.configs.set(Q,{name:Q,type:"stdio",command:X,args:Y,env:W?.env,cwd:W?.cwd,restartConfig:W?.restartConfig,addedAt:new Date,addedBy:$}),this.logger?.info(J?"server_config_updated":"server_config_added",{server:Q,type:"stdio",command:X,args:Y,addedBy:$}),!J}getConfig(Q){return this.configs.get(Q)}listConfigs(){return Array.from(this.configs.values())}removeConfig(Q){let X=this.configs.delete(Q);if(X)this.logger?.info("server_config_removed",{server:Q});return X}hasConfig(Q){return this.configs.has(Q)}get size(){return this.configs.size}clear(){this.configs.clear(),this.logger?.info("server_configs_cleared",{})}}var ff={maxEvents:1000,retentionMs:1800000,cleanupIntervalMs:300000};class IJ{events=[];config;logger;lastDeliveredId=null;waiters=[];cleanupIntervalHandle=null;constructor(Q={},X){this.config={...ff,...Q},this.logger=X,this.startCleanupInterval()}addEvent(Q,X,Y){let W=f1(),$={id:W,type:Q,server:X,data:Y,createdAt:new Date,sentViaSSE:!1};this.events.push($);while(this.events.length>this.config.maxEvents)this.events.shift();return this.logger?.debug("event_added",{id:W,type:Q,server:X}),this.wakeWaiters($),W}hasNewEvents(){if(this.lastDeliveredId===null)return this.events.length>0;let Q=this.events.findIndex((X)=>X.id===this.lastDeliveredId);if(Q===-1)return this.events.length>0;return Q<this.events.length-1}getNewEvents(){if(this.events.length===0)return[];let Q=0;if(this.lastDeliveredId!==null){let Y=this.events.findIndex((W)=>W.id===this.lastDeliveredId);if(Y!==-1)Q=Y+1}let X=this.events.slice(Q);if(X.length>0){let Y=X[X.length-1];if(Y)this.lastDeliveredId=Y.id}return X}getEventsAfter(Q){if(Q===null)return[...this.events];let X=this.events.findIndex((Y)=>Y.id===Q);if(X===-1)return[...this.events];return this.events.slice(X+1)}markSent(Q){let X=this.events.find((Y)=>Y.id===Q);if(X)X.sentViaSSE=!0}waitForActivity(Q){return new Promise((X)=>{let Y=setTimeout(()=>{let W=this.waiters.findIndex(($)=>$.timeoutHandle===Y);if(W!==-1)this.waiters.splice(W,1);X(null)},Q);this.waiters.push({resolve:X,timeoutHandle:Y})})}wakeWaiters(Q){let X=this.waiters;this.waiters=[];for(let Y of X)clearTimeout(Y.timeoutHandle),Y.resolve(Q)}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runCleanup()},this.config.cleanupIntervalMs)}runCleanup(){let Q=Date.now()-this.config.retentionMs,X=0;while(this.events.length>0){let Y=this.events[0];if(Y&&Y.createdAt.getTime()<Q)this.events.shift(),X++;else break}if(X>0)this.logger?.debug("events_cleaned",{removed:X,remaining:this.events.length})}shutdown(){if(this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of this.waiters)clearTimeout(Q.timeoutHandle),Q.resolve(null);this.waiters=[]}}var gf={defaultTtlMs:600000,completedRetentionMs:300000,cleanupIntervalMs:60000};class TJ{tasks=new Map;eventSystem;config;cleanupIntervalHandle=null;constructor(Q,X={}){this.eventSystem=Q,this.config={...gf,...X},this.startCleanupInterval()}createTask(Q,X,Y,W){let $=f1(),J=new Date,G={taskId:$,server:Q,toolName:X,args:Y,status:"working",createdAt:J,lastUpdatedAt:J,ttl:W??this.config.defaultTtlMs};return this.tasks.set($,G),this.eventSystem.addEvent("task_created",Q,{taskId:$,toolName:X,args:Y}),G}completeTask(Q,X){let Y=this.tasks.get(Q);if(Y?.status!=="working")return;Y.status="completed",Y.result=X,Y.lastUpdatedAt=new Date,this.scheduleTaskCleanup(Y),this.eventSystem.addEvent("task_completed",Y.server,{taskId:Q,toolName:Y.toolName,result:X})}failTask(Q,X){let Y=this.tasks.get(Q);if(Y?.status!=="working")return;Y.status="failed",Y.error=X,Y.lastUpdatedAt=new Date,this.scheduleTaskCleanup(Y),this.eventSystem.addEvent("task_failed",Y.server,{taskId:Q,toolName:Y.toolName,error:X})}cancelTask(Q){let X=this.tasks.get(Q);if(X?.status!=="working")return!1;return X.status="cancelled",X.lastUpdatedAt=new Date,this.scheduleTaskCleanup(X),this.eventSystem.addEvent("task_cancelled",X.server,{taskId:Q,toolName:X.toolName}),!0}getTask(Q){let X=this.tasks.get(Q);if(!X)return;let{_cleanupTimeoutHandle:Y,...W}=X;return W}getTasksForServer(Q){return Array.from(this.tasks.values()).filter((X)=>X.server===Q).map((X)=>({taskId:X.taskId,server:X.server,toolName:X.toolName,args:X.args,status:X.status,result:X.result,error:X.error,createdAt:X.createdAt,lastUpdatedAt:X.lastUpdatedAt,ttl:X.ttl}))}getAllTasks(Q=!1){let X=["completed","failed","cancelled","expired"];return Array.from(this.tasks.values()).filter((Y)=>Q||!X.includes(Y.status)).map((Y)=>({taskId:Y.taskId,server:Y.server,toolName:Y.toolName,args:Y.args,status:Y.status,result:Y.result,error:Y.error,createdAt:Y.createdAt,lastUpdatedAt:Y.lastUpdatedAt,ttl:Y.ttl}))}getWorkingTasksForServer(Q){return Array.from(this.tasks.values()).filter((X)=>X.server===Q&&X.status==="working").map((X)=>({taskId:X.taskId,toolName:X.toolName,status:X.status}))}scheduleTaskCleanup(Q){if(Q._cleanupTimeoutHandle)clearTimeout(Q._cleanupTimeoutHandle);Q._cleanupTimeoutHandle=setTimeout(()=>{this.tasks.delete(Q.taskId)},this.config.completedRetentionMs)}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runCleanup()},this.config.cleanupIntervalMs)}runCleanup(){let Q=Date.now();for(let X of this.tasks.values()){if(X.status!=="working")continue;if(Q-X.createdAt.getTime()>=X.ttl)X.status="expired",X.error=`Task expired after ${String(X.ttl)}ms TTL`,X.lastUpdatedAt=new Date,this.eventSystem.addEvent("task_expired",X.server,{taskId:X.taskId,toolName:X.toolName,ttl:X.ttl}),this.scheduleTaskCleanup(X)}}shutdown(){if(this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of this.tasks.values())if(Q._cleanupTimeoutHandle)clearTimeout(Q._cleanupTimeoutHandle)}}var hf={maxNotificationsPerServer:100,maxLogsPerServer:500};class CJ{buffers=new Map;eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...hf,...X}}addNotification(Q){let X=this.getOrCreateBuffers(Q.server);if(X.notifications.length>=this.config.maxNotificationsPerServer)X.notifications.shift();X.notifications.push(Q),this.eventSystem.addEvent("notification",Q.server,{method:Q.method,params:Q.params,timestamp:Q.timestamp.toISOString()})}addLog(Q){let X=this.getOrCreateBuffers(Q.server);if(X.logs.length>=this.config.maxLogsPerServer)X.logs.shift();X.logs.push(Q)}getAndClearNotifications(){let Q=[];for(let X of this.buffers.values())Q.push(...X.notifications),X.notifications=[];return Q}getAndClearLogs(){let Q=[];for(let X of this.buffers.values())Q.push(...X.logs),X.logs=[];return Q}getNotificationsForServer(Q){let X=this.buffers.get(Q);return X?[...X.notifications]:[]}getLogsForServer(Q){let X=this.buffers.get(Q);return X?[...X.logs]:[]}getNotificationCount(){let Q=0;for(let X of this.buffers.values())Q+=X.notifications.length;return Q}getLogCount(){let Q=0;for(let X of this.buffers.values())Q+=X.logs.length;return Q}clearServer(Q){this.buffers.delete(Q)}getOrCreateBuffers(Q){let X=this.buffers.get(Q);if(!X)X={notifications:[],logs:[]},this.buffers.set(Q,X);return X}}var uf={defaultTimeoutMs:600000};class kJ{samplingRequests=new Map;elicitationRequests=new Map;eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...uf,...X}}addSamplingRequest(Q,X,Y,W){let $=f1(),J=setTimeout(()=>{let H=this.samplingRequests.get($);if(H)this.samplingRequests.delete($),this.eventSystem.addEvent("sampling_expired",Q,{requestId:$,reason:`Timed out after ${String(this.config.defaultTimeoutMs)}ms`}),H.reject(Error(`Sampling request timed out after ${String(this.config.defaultTimeoutMs)}ms`))},this.config.defaultTimeoutMs),G={requestId:$,server:Q,timestamp:new Date,params:X,resolve:Y,reject:W,timeoutHandle:J};return this.samplingRequests.set($,G),this.eventSystem.addEvent("sampling_request",Q,{requestId:$,params:X}),$}addElicitationRequest(Q,X,Y,W){let $=f1(),J=setTimeout(()=>{let H=this.elicitationRequests.get($);if(H)this.elicitationRequests.delete($),this.eventSystem.addEvent("elicitation_expired",Q,{requestId:$,reason:`Timed out after ${String(this.config.defaultTimeoutMs)}ms`}),H.reject(Error(`Elicitation request timed out after ${String(this.config.defaultTimeoutMs)}ms`))},this.config.defaultTimeoutMs),G={requestId:$,server:Q,timestamp:new Date,params:X,resolve:Y,reject:W,timeoutHandle:J};return this.elicitationRequests.set($,G),this.eventSystem.addEvent("elicitation_request",Q,{requestId:$,params:X}),$}respondToSampling(Q,X){let Y=this.samplingRequests.get(Q);if(!Y)throw Error(`Sampling request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.samplingRequests.delete(Q),Y.resolve(X)}cancelSampling(Q,X="User cancelled"){let Y=this.samplingRequests.get(Q);if(!Y)throw Error(`Sampling request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.samplingRequests.delete(Q),this.eventSystem.addEvent("sampling_expired",Y.server,{requestId:Q,reason:X}),Y.reject(Error(X))}respondToElicitation(Q,X){let Y=this.elicitationRequests.get(Q);if(!Y)throw Error(`Elicitation request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.elicitationRequests.delete(Q),Y.resolve(X)}cancelElicitation(Q,X="User cancelled"){let Y=this.elicitationRequests.get(Q);if(!Y)throw Error(`Elicitation request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.elicitationRequests.delete(Q),this.eventSystem.addEvent("elicitation_expired",Y.server,{requestId:Q,reason:X}),Y.reject(Error(X))}getPendingSamplingRequests(){return Array.from(this.samplingRequests.values()).map((Q)=>({requestId:Q.requestId,server:Q.server,timestamp:Q.timestamp,params:Q.params}))}getPendingElicitationRequests(){return Array.from(this.elicitationRequests.values()).map((Q)=>({requestId:Q.requestId,server:Q.server,timestamp:Q.timestamp,params:Q.params}))}getRequestsForServer(Q){return{sampling:this.getPendingSamplingRequests().filter((X)=>X.server===Q),elicitation:this.getPendingElicitationRequests().filter((X)=>X.server===Q)}}hasPendingRequests(){return this.samplingRequests.size>0||this.elicitationRequests.size>0}rejectRequestsForServer(Q,X){for(let[Y,W]of this.samplingRequests)if(W.server===Q)clearTimeout(W.timeoutHandle),this.samplingRequests.delete(Y),this.eventSystem.addEvent("sampling_expired",Q,{requestId:Y,reason:X}),W.reject(Error(X));for(let[Y,W]of this.elicitationRequests)if(W.server===Q)clearTimeout(W.timeoutHandle),this.elicitationRequests.delete(Y),this.eventSystem.addEvent("elicitation_expired",Q,{requestId:Y,reason:X}),W.reject(Error(X))}shutdown(){for(let Q of this.samplingRequests.values())clearTimeout(Q.timeoutHandle),Q.reject(Error("PendingRequestsManager shutting down"));this.samplingRequests.clear();for(let Q of this.elicitationRequests.values())clearTimeout(Q.timeoutHandle),Q.reject(Error("PendingRequestsManager shutting down"));this.elicitationRequests.clear()}}var lf={maxActiveTimers:100,maxDurationMs:86400000,retentionMs:300000};class vJ{timers=new Map;expiredBuffer=[];eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...lf,...X}}createTimer(Q,X,Y=!1){if(this.getActiveTimers().length>=this.config.maxActiveTimers)throw Error(`Maximum active timers (${String(this.config.maxActiveTimers)}) exceeded`);if(Q<=0)throw Error("Duration must be positive");if(Q>this.config.maxDurationMs)throw Error(`Duration exceeds maximum (${String(this.config.maxDurationMs)}ms)`);let $=f1(),J=new Date,G=new Date(J.getTime()+Q),H={id:$,durationMs:Q,message:X,createdAt:J,expiresAt:G,status:"active",interval:Y,fireCount:0};if(Y)H._intervalHandle=setInterval(()=>{this.fireIntervalTimer($)},Q);else H._timeoutHandle=setTimeout(()=>{this.expireTimer($)},Q);return this.timers.set($,H),this.toPublicTimer(H)}getTimer(Q){let X=this.timers.get(Q);if(!X)return;return this.toPublicTimer(X)}deleteTimer(Q){let X=this.timers.get(Q);if(!X)return;if(X._timeoutHandle)clearTimeout(X._timeoutHandle),X._timeoutHandle=void 0;if(X._intervalHandle)clearInterval(X._intervalHandle),X._intervalHandle=void 0;return X.status="deleted",this.scheduleCleanup(X),this.toPublicTimer(X)}getAllTimers(Q=!1){let X=Array.from(this.timers.values());return(Q?X:X.filter((W)=>W.status==="active")).map((W)=>this.toPublicTimer(W))}getActiveTimers(){return Array.from(this.timers.values()).filter((Q)=>Q.status==="active").map((Q)=>this.toPublicTimer(Q))}getAndClearExpired(){let Q=[...this.expiredBuffer];return this.expiredBuffer.length=0,Q}hasExpired(){return this.expiredBuffer.length>0}shutdown(){for(let Q of this.timers.values()){if(Q._timeoutHandle)clearTimeout(Q._timeoutHandle);if(Q._intervalHandle)clearInterval(Q._intervalHandle)}this.timers.clear(),this.expiredBuffer.length=0}expireTimer(Q){let X=this.timers.get(Q);if(!X?.status||X.status!=="active")return;X.status="expired",X._timeoutHandle=void 0,X.fireCount++,this.expiredBuffer.push({id:X.id,message:X.message,expiredAt:new Date().toISOString()}),this.eventSystem.addEvent("timer_expired","emceepee",{timerId:X.id,message:X.message}),this.scheduleCleanup(X)}fireIntervalTimer(Q){let X=this.timers.get(Q);if(!X?.status||X.status!=="active")return;X.fireCount++,X.expiresAt=new Date(Date.now()+X.durationMs),this.expiredBuffer.push({id:X.id,message:X.message,expiredAt:new Date().toISOString()}),this.eventSystem.addEvent("timer_expired","emceepee",{timerId:X.id,message:X.message,fireCount:X.fireCount,interval:!0})}scheduleCleanup(Q){setTimeout(()=>{this.timers.delete(Q.id)},this.config.retentionMs)}toPublicTimer(Q){return{id:Q.id,durationMs:Q.durationMs,message:Q.message,createdAt:Q.createdAt,expiresAt:Q.expiresAt,status:Q.status,interval:Q.interval,fireCount:Q.fireCount}}}class _J{sessionId;createdAt;lastActivityAt;backendConnections=new Map;eventSystem;taskManager;pendingRequests;bufferManager;timerManager;logger;constructor(Q,X={},Y){this.sessionId=Q,this.createdAt=new Date,this.lastActivityAt=new Date,this.logger=Y,this.eventSystem=new IJ(X.eventSystemConfig,Y),this.taskManager=new TJ(this.eventSystem,X.taskConfig),this.pendingRequests=new kJ(this.eventSystem,X.requestConfig),this.bufferManager=new CJ(this.eventSystem,X.bufferConfig),this.timerManager=new vJ(this.eventSystem,X.timerConfig)}touch(){this.lastActivityAt=new Date}getConnection(Q){return this.backendConnections.get(Q)}isConnectedTo(Q){return this.backendConnections.get(Q)?.status==="connected"}listConnectedServers(){return Array.from(this.backendConnections.entries()).filter(([,Q])=>Q.status==="connected").map(([Q])=>Q)}listConnections(){return Array.from(this.backendConnections.entries()).map(([Q,X])=>({name:Q,status:X.status,connectedAt:X.connectedAt,lastError:X.lastError}))}setConnectionStatus(Q,X,Y){let W=this.backendConnections.get(Q);if(W){if(W.status=X,X==="connected")W.connectedAt=new Date,W.lastError=void 0;else if(X==="error"&&Y)W.lastError=Y}}addConnection(Q,X){this.backendConnections.set(Q,{client:X,status:"connecting"})}removeConnection(Q){return this.backendConnections.delete(Q)}async cleanup(){this.logger?.info("session_cleanup_start",{sessionId:this.sessionId}),this.pendingRequests.shutdown(),this.taskManager.shutdown(),this.timerManager.shutdown(),this.eventSystem.shutdown();for(let[Q,X]of this.backendConnections)try{await X.client.disconnect(),this.logger?.debug("session_backend_disconnected",{sessionId:this.sessionId,server:Q})}catch(Y){this.logger?.debug("session_backend_disconnect_error",{sessionId:this.sessionId,server:Q,error:Y instanceof Error?Y.message:String(Y)})}this.backendConnections.clear(),this.logger?.info("session_cleanup_complete",{sessionId:this.sessionId})}}class xJ{constructor(Q){this._client=Q}async*callToolStream(Q,X=M6,Y){let W=this._client,$={...Y,task:Y?.task??(W.isToolTask(Q.name)?{}:void 0)},J=W.requestStream({method:"tools/call",params:Q},X,$),G=W.getToolOutputValidator(Q.name);for await(let H of J){if(H.type==="result"&&G){let B=H.result;if(!B.structuredContent&&!B.isError){yield{type:"error",error:new S(k.InvalidRequest,`Tool ${Q.name} has an output schema but did not return structured content`)};return}if(B.structuredContent)try{let z=G(B.structuredContent);if(!z.valid){yield{type:"error",error:new S(k.InvalidParams,`Structured content does not match the tool's output schema: ${z.errorMessage}`)};return}}catch(z){if(z instanceof S){yield{type:"error",error:z};return}yield{type:"error",error:new S(k.InvalidParams,`Failed to validate structured content: ${z instanceof Error?z.message:String(z)}`)};return}}yield H}}async getTask(Q,X){return this._client.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._client.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._client.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._client.cancelTask({taskId:Q},X)}requestStream(Q,X,Y){return this._client.requestStream(Q,X,Y)}}function MY(Q,X){if(!Q||X===null||typeof X!=="object")return;if(Q.type==="object"&&Q.properties&&typeof Q.properties==="object"){let Y=X,W=Q.properties;for(let $ of Object.keys(W)){let J=W[$];if(Y[$]===void 0&&Object.prototype.hasOwnProperty.call(J,"default"))Y[$]=J.default;if(Y[$]!==void 0)MY(J,Y[$])}}if(Array.isArray(Q.anyOf)){for(let Y of Q.anyOf)if(typeof Y!=="boolean")MY(Y,X)}if(Array.isArray(Q.oneOf)){for(let Y of Q.oneOf)if(typeof Y!=="boolean")MY(Y,X)}}function mf(Q){if(!Q)return{supportsFormMode:!1,supportsUrlMode:!1};let X=Q.form!==void 0,Y=Q.url!==void 0;return{supportsFormMode:X||!X&&!Y,supportsUrlMode:Y}}class F8 extends Q4{constructor(Q,X){super(X);if(this._clientInfo=Q,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=X?.capabilities??{},this._jsonSchemaValidator=X?.jsonSchemaValidator??new i4,X?.listChanged)this._pendingListChangedConfig=X.listChanged}_setupListChangedHandlers(Q){if(Q.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",Q9,Q.tools,async()=>{return(await this.listTools()).tools});if(Q.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",e6,Q.prompts,async()=>{return(await this.listPrompts()).prompts});if(Q.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",s6,Q.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new xJ(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=aQ(this._capabilities,Q)}setRequestHandler(Q,X){let W=c1(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let $;if(s0(W)){let G=W;$=G._zod?.def?.value??G.value}else{let G=W;$=G._def?.value??G.value}if(typeof $!=="string")throw Error("Schema method literal must be a string");let J=$;if(J==="elicitation/create"){let G=async(H,B)=>{let z=c0(Y9,H);if(!z.success){let O=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid elicitation request: ${O}`)}let{params:K}=z.data;K.mode=K.mode??"form";let{supportsFormMode:V,supportsUrlMode:q}=mf(this._capabilities.elicitation);if(K.mode==="form"&&!V)throw new S(k.InvalidParams,"Client does not support form-mode elicitation requests");if(K.mode==="url"&&!q)throw new S(k.InvalidParams,"Client does not support URL-mode elicitation requests");let F=await Promise.resolve(X(H,B));if(K.task){let O=c0(Q6,F);if(!O.success){let N=O.error instanceof Error?O.error.message:String(O.error);throw new S(k.InvalidParams,`Invalid task creation result: ${N}`)}return O.data}let A=c0(c9,F);if(!A.success){let O=A.error instanceof Error?A.error.message:String(A.error);throw new S(k.InvalidParams,`Invalid elicitation result: ${O}`)}let D=A.data,L=K.mode==="form"?K.requestedSchema:void 0;if(K.mode==="form"&&D.action==="accept"&&D.content&&L){if(this._capabilities.elicitation?.form?.applyDefaults)try{MY(L,D.content)}catch{}}return D};return super.setRequestHandler(Q,G)}if(J==="sampling/createMessage"){let G=async(H,B)=>{let z=c0(X9,H);if(!z.success){let F=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid sampling request: ${F}`)}let{params:K}=z.data,V=await Promise.resolve(X(H,B));if(K.task){let F=c0(Q6,V);if(!F.success){let A=F.error instanceof Error?F.error.message:String(F.error);throw new S(k.InvalidParams,`Invalid task creation result: ${A}`)}return F.data}let q=c0(s8,V);if(!q.success){let F=q.error instanceof Error?q.error.message:String(q.error);throw new S(k.InvalidParams,`Invalid sampling result: ${F}`)}return q.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapability(Q,X){if(!this._serverCapabilities?.[Q])throw Error(`Server does not support ${Q} (required for ${X})`)}async connect(Q,X){if(await super.connect(Q),Q.sessionId!==void 0)return;try{let Y=await this.request({method:"initialize",params:{protocolVersion:U6,capabilities:this._capabilities,clientInfo:this._clientInfo}},$5,X);if(Y===void 0)throw Error(`Server sent invalid initialize result: ${Y}`);if(!EQ.includes(Y.protocolVersion))throw Error(`Server's protocol version is not supported: ${Y.protocolVersion}`);if(this._serverCapabilities=Y.capabilities,this._serverVersion=Y.serverInfo,Q.setProtocolVersion)Q.setProtocolVersion(Y.protocolVersion);if(this._instructions=Y.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(Y){throw this.close(),Y}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(Q){switch(Q){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${Q})`);if(Q==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${Q})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${Q})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${Q})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${Q})`);break;case"ping":break}}assertTaskCapability(Q){DY(this._serverCapabilities?.tasks?.requests,Q,"Server")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;LY(this._capabilities.tasks?.requests,Q,"Client")}async ping(Q){return this.request({method:"ping"},e1,Q)}async complete(Q,X){return this.request({method:"completion/complete",params:Q},j5,X)}async setLoggingLevel(Q,X){return this.request({method:"logging/setLevel",params:{level:Q}},e1,X)}async getPrompt(Q,X){return this.request({method:"prompts/get",params:Q},D5,X)}async listPrompts(Q,X){return this.request({method:"prompts/list",params:Q},K5,X)}async listResources(Q,X){return this.request({method:"resources/list",params:Q},G5,X)}async listResourceTemplates(Q,X){return this.request({method:"resources/templates/list",params:Q},H5,X)}async readResource(Q,X){return this.request({method:"resources/read",params:Q},z5,X)}async subscribeResource(Q,X){return this.request({method:"resources/subscribe",params:Q},e1,X)}async unsubscribeResource(Q,X){return this.request({method:"resources/unsubscribe",params:Q},e1,X)}async callTool(Q,X=M6,Y){if(this.isToolTaskRequired(Q.name))throw new S(k.InvalidRequest,`Tool "${Q.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let W=await this.request({method:"tools/call",params:Q},X,Y),$=this.getToolOutputValidator(Q.name);if($){if(!W.structuredContent&&!W.isError)throw new S(k.InvalidRequest,`Tool ${Q.name} has an output schema but did not return structured content`);if(W.structuredContent)try{let J=$(W.structuredContent);if(!J.valid)throw new S(k.InvalidParams,`Structured content does not match the tool's output schema: ${J.errorMessage}`)}catch(J){if(J instanceof S)throw J;throw new S(k.InvalidParams,`Failed to validate structured content: ${J instanceof Error?J.message:String(J)}`)}}return W}isToolTask(Q){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(Q)}isToolTaskRequired(Q){return this._cachedRequiredTaskTools.has(Q)}cacheToolMetadata(Q){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let X of Q){if(X.outputSchema){let W=this._jsonSchemaValidator.getValidator(X.outputSchema);this._cachedToolOutputValidators.set(X.name,W)}let Y=X.execution?.taskSupport;if(Y==="required"||Y==="optional")this._cachedKnownTaskTools.add(X.name);if(Y==="required")this._cachedRequiredTaskTools.add(X.name)}}getToolOutputValidator(Q){return this._cachedToolOutputValidators.get(Q)}async listTools(Q,X){let Y=await this.request({method:"tools/list",params:Q},L5,X);return this.cacheToolMetadata(Y.tools),Y}_setupListChangedHandler(Q,X,Y,W){let $=_3.safeParse(Y);if(!$.success)throw Error(`Invalid ${Q} listChanged options: ${$.error.message}`);if(typeof Y.onChanged!=="function")throw Error(`Invalid ${Q} listChanged options: onChanged must be a function`);let{autoRefresh:J,debounceMs:G}=$.data,{onChanged:H}=Y,B=async()=>{if(!J){H(null,null);return}try{let K=await W();H(null,K)}catch(K){let V=K instanceof Error?K:Error(String(K));H(V,null)}},z=()=>{if(G){let K=this._listChangedDebounceTimers.get(Q);if(K)clearTimeout(K);let V=setTimeout(B,G);this._listChangedDebounceTimers.set(Q,V)}else B()};this.setNotificationHandler(X,z)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function NY(Q){if(!Q)return{};if(Q instanceof Headers)return Object.fromEntries(Q.entries());if(Array.isArray(Q))return Object.fromEntries(Q);return{...Q}}function HO(Q=fetch,X){if(!X)return Q;return async(Y,W)=>{let $={...X,...W,headers:W?.headers?{...NY(X.headers),...NY(W.headers)}:X.headers};return Q(Y,$)}}var yJ;yJ=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((Q)=>Q.webcrypto);async function cf(Q){return(await yJ).getRandomValues(new Uint8Array(Q))}async function pf(Q){let Y=Math.pow(2,8)-Math.pow(2,8)%66,W="";while(W.length<Q){let $=await cf(Q-W.length);for(let J of $)if(J<Y)W+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[J%66]}return W}async function df(Q){return await pf(Q)}async function nf(Q){let X=await(await yJ).subtle.digest("SHA-256",new TextEncoder().encode(Q));return btoa(String.fromCharCode(...new Uint8Array(X))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function fJ(Q){if(!Q)Q=43;if(Q<43||Q>128)throw`Expected a length between 43 and 128. Received ${Q}.`;let X=await df(Q),Y=await nf(X);return{code_verifier:X,code_challenge:Y}}var g0=H3().superRefine((Q,X)=>{if(!URL.canParse(Q))return X.addIssue({code:U3.custom,message:"URL must be parseable",fatal:!0}),YQ}).refine((Q)=>{let X=new URL(Q);return X.protocol!=="javascript:"&&X.protocol!=="data:"&&X.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),zO=T0({resource:U().url(),authorization_servers:E(g0).optional(),jwks_uri:U().url().optional(),scopes_supported:E(U()).optional(),bearer_methods_supported:E(U()).optional(),resource_signing_alg_values_supported:E(U()).optional(),resource_name:U().optional(),resource_documentation:U().optional(),resource_policy_uri:U().url().optional(),resource_tos_uri:U().url().optional(),tls_client_certificate_bound_access_tokens:H0().optional(),authorization_details_types_supported:E(U()).optional(),dpop_signing_alg_values_supported:E(U()).optional(),dpop_bound_access_tokens_required:H0().optional()}),gJ=T0({issuer:U(),authorization_endpoint:g0,token_endpoint:g0,registration_endpoint:g0.optional(),scopes_supported:E(U()).optional(),response_types_supported:E(U()),response_modes_supported:E(U()).optional(),grant_types_supported:E(U()).optional(),token_endpoint_auth_methods_supported:E(U()).optional(),token_endpoint_auth_signing_alg_values_supported:E(U()).optional(),service_documentation:g0.optional(),revocation_endpoint:g0.optional(),revocation_endpoint_auth_methods_supported:E(U()).optional(),revocation_endpoint_auth_signing_alg_values_supported:E(U()).optional(),introspection_endpoint:U().optional(),introspection_endpoint_auth_methods_supported:E(U()).optional(),introspection_endpoint_auth_signing_alg_values_supported:E(U()).optional(),code_challenge_methods_supported:E(U()).optional(),client_id_metadata_document_supported:H0().optional()}),of=T0({issuer:U(),authorization_endpoint:g0,token_endpoint:g0,userinfo_endpoint:g0.optional(),jwks_uri:g0,registration_endpoint:g0.optional(),scopes_supported:E(U()).optional(),response_types_supported:E(U()),response_modes_supported:E(U()).optional(),grant_types_supported:E(U()).optional(),acr_values_supported:E(U()).optional(),subject_types_supported:E(U()),id_token_signing_alg_values_supported:E(U()),id_token_encryption_alg_values_supported:E(U()).optional(),id_token_encryption_enc_values_supported:E(U()).optional(),userinfo_signing_alg_values_supported:E(U()).optional(),userinfo_encryption_alg_values_supported:E(U()).optional(),userinfo_encryption_enc_values_supported:E(U()).optional(),request_object_signing_alg_values_supported:E(U()).optional(),request_object_encryption_alg_values_supported:E(U()).optional(),request_object_encryption_enc_values_supported:E(U()).optional(),token_endpoint_auth_methods_supported:E(U()).optional(),token_endpoint_auth_signing_alg_values_supported:E(U()).optional(),display_values_supported:E(U()).optional(),claim_types_supported:E(U()).optional(),claims_supported:E(U()).optional(),service_documentation:U().optional(),claims_locales_supported:E(U()).optional(),ui_locales_supported:E(U()).optional(),claims_parameter_supported:H0().optional(),request_parameter_supported:H0().optional(),request_uri_parameter_supported:H0().optional(),require_request_uri_registration:H0().optional(),op_policy_uri:g0.optional(),op_tos_uri:g0.optional(),client_id_metadata_document_supported:H0().optional()}),KO=I({...of.shape,...gJ.pick({code_challenge_methods_supported:!0}).shape}),VO=I({access_token:U(),id_token:U().optional(),token_type:U(),expires_in:ZQ.number().optional(),scope:U().optional(),refresh_token:U().optional()}).strip(),FO=I({error:U(),error_description:U().optional(),error_uri:U().optional()}),BO=g0.optional().or(_("").transform(()=>{return})),rf=I({redirect_uris:E(g0),token_endpoint_auth_method:U().optional(),grant_types:E(U()).optional(),response_types:E(U()).optional(),client_name:U().optional(),client_uri:g0.optional(),logo_uri:BO,scope:U().optional(),contacts:E(U()).optional(),tos_uri:BO,policy_uri:U().optional(),jwks_uri:g0.optional(),jwks:z3().optional(),software_id:U().optional(),software_version:U().optional(),software_statement:U().optional()}).strip(),tf=I({client_id:U(),client_secret:U().optional(),client_id_issued_at:J0().optional(),client_secret_expires_at:J0().optional()}).strip(),AO=rf.merge(tf),ho=I({error:U(),error_description:U().optional()}).strip(),uo=I({token:U(),token_type_hint:U().optional()}).strip();function qO(Q){let X=typeof Q==="string"?new URL(Q):new URL(Q.href);return X.hash="",X}function DO({requestedResource:Q,configuredResource:X}){let Y=typeof Q==="string"?new URL(Q):new URL(Q.href),W=typeof X==="string"?new URL(X):new URL(X.href);if(Y.origin!==W.origin)return!1;if(Y.pathname.length<W.pathname.length)return!1;let $=Y.pathname.endsWith("/")?Y.pathname:Y.pathname+"/",J=W.pathname.endsWith("/")?W.pathname:W.pathname+"/";return $.startsWith(J)}class E0 extends Error{constructor(Q,X){super(Q);this.errorUri=X,this.name=this.constructor.name}toResponseObject(){let Q={error:this.errorCode,error_description:this.message};if(this.errorUri)Q.error_uri=this.errorUri;return Q}get errorCode(){return this.constructor.errorCode}}class wY extends E0{}wY.errorCode="invalid_request";class A8 extends E0{}A8.errorCode="invalid_client";class q8 extends E0{}q8.errorCode="invalid_grant";class D8 extends E0{}D8.errorCode="unauthorized_client";class bY extends E0{}bY.errorCode="unsupported_grant_type";class PY extends E0{}PY.errorCode="invalid_scope";class ZY extends E0{}ZY.errorCode="access_denied";class y6 extends E0{}y6.errorCode="server_error";class RY extends E0{}RY.errorCode="temporarily_unavailable";class EY extends E0{}EY.errorCode="unsupported_response_type";class SY extends E0{}SY.errorCode="unsupported_token_type";class IY extends E0{}IY.errorCode="invalid_token";class TY extends E0{}TY.errorCode="method_not_allowed";class CY extends E0{}CY.errorCode="too_many_requests";class L8 extends E0{}L8.errorCode="invalid_client_metadata";class kY extends E0{}kY.errorCode="insufficient_scope";class vY extends E0{}vY.errorCode="invalid_target";var LO={[wY.errorCode]:wY,[A8.errorCode]:A8,[q8.errorCode]:q8,[D8.errorCode]:D8,[bY.errorCode]:bY,[PY.errorCode]:PY,[ZY.errorCode]:ZY,[y6.errorCode]:y6,[RY.errorCode]:RY,[EY.errorCode]:EY,[SY.errorCode]:SY,[IY.errorCode]:IY,[TY.errorCode]:TY,[CY.errorCode]:CY,[L8.errorCode]:L8,[kY.errorCode]:kY,[vY.errorCode]:vY};class f6 extends Error{constructor(Q){super(Q??"Unauthorized")}}function af(Q){return["client_secret_basic","client_secret_post","none"].includes(Q)}var hJ="code",uJ="S256";function sf(Q,X){let Y=Q.client_secret!==void 0;if(X.length===0)return Y?"client_secret_post":"none";if("token_endpoint_auth_method"in Q&&Q.token_endpoint_auth_method&&af(Q.token_endpoint_auth_method)&&X.includes(Q.token_endpoint_auth_method))return Q.token_endpoint_auth_method;if(Y&&X.includes("client_secret_basic"))return"client_secret_basic";if(Y&&X.includes("client_secret_post"))return"client_secret_post";if(X.includes("none"))return"none";return Y?"client_secret_post":"none"}function ef(Q,X,Y,W){let{client_id:$,client_secret:J}=X;switch(Q){case"client_secret_basic":Qg($,J,Y);return;case"client_secret_post":Xg($,J,W);return;case"none":Yg($,W);return;default:throw Error(`Unsupported client authentication method: ${Q}`)}}function Qg(Q,X,Y){if(!X)throw Error("client_secret_basic authentication requires a client_secret");let W=btoa(`${Q}:${X}`);Y.set("Authorization",`Basic ${W}`)}function Xg(Q,X,Y){if(Y.set("client_id",Q),X)Y.set("client_secret",X)}function Yg(Q,X){X.set("client_id",Q)}async function UO(Q){let X=Q instanceof Response?Q.status:void 0,Y=Q instanceof Response?await Q.text():Q;try{let W=FO.parse(JSON.parse(Y)),{error:$,error_description:J,error_uri:G}=W;return new(LO[$]||y6)(J||"",G)}catch(W){let $=`${X?`HTTP ${X}: `:""}Invalid OAuth error response: ${W}. Raw body: ${Y}`;return new y6($)}}async function r4(Q,X){try{return await lJ(Q,X)}catch(Y){if(Y instanceof A8||Y instanceof D8)return await Q.invalidateCredentials?.("all"),await lJ(Q,X);else if(Y instanceof q8)return await Q.invalidateCredentials?.("tokens"),await lJ(Q,X);throw Y}}async function lJ(Q,{serverUrl:X,authorizationCode:Y,scope:W,resourceMetadataUrl:$,fetchFn:J}){let G,H;try{if(G=await Jg(X,{resourceMetadataUrl:$},J),G.authorization_servers&&G.authorization_servers.length>0)H=G.authorization_servers[0]}catch{}if(!H)H=new URL("/",X);let B=await $g(X,Q,G),z=await Kg(H,{fetchFn:J}),K=await Promise.resolve(Q.clientInformation());if(!K){if(Y!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let L=z?.client_id_metadata_document_supported===!0,O=Q.clientMetadataUrl;if(O&&!Wg(O))throw new L8(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if(L&&O)K={client_id:O},await Q.saveClientInformation?.(K);else{if(!Q.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let w=await Dg(H,{metadata:z,clientMetadata:Q.clientMetadata,fetchFn:J});await Q.saveClientInformation(w),K=w}}let V=!Q.redirectUrl;if(Y!==void 0||V){let L=await qg(Q,H,{metadata:z,resource:B,authorizationCode:Y,fetchFn:J});return await Q.saveTokens(L),"AUTHORIZED"}let q=await Q.tokens();if(q?.refresh_token)try{let L=await Ag(H,{metadata:z,clientInformation:K,refreshToken:q.refresh_token,resource:B,addClientAuthentication:Q.addClientAuthentication,fetchFn:J});return await Q.saveTokens(L),"AUTHORIZED"}catch(L){if(!(L instanceof E0)||L instanceof y6);else throw L}let F=Q.state?await Q.state():void 0,{authorizationUrl:A,codeVerifier:D}=await Vg(H,{metadata:z,clientInformation:K,state:F,redirectUrl:Q.redirectUrl,scope:W||G?.scopes_supported?.join(" ")||Q.clientMetadata.scope,resource:B});return await Q.saveCodeVerifier(D),await Q.redirectToAuthorization(A),"REDIRECT"}function Wg(Q){if(!Q)return!1;try{let X=new URL(Q);return X.protocol==="https:"&&X.pathname!=="/"}catch{return!1}}async function $g(Q,X,Y){let W=qO(Q);if(X.validateResourceURL)return await X.validateResourceURL(W,Y?.resource);if(!Y)return;if(!DO({requestedResource:W,configuredResource:Y.resource}))throw Error(`Protected resource ${Y.resource} does not match expected ${W} (or origin)`);return new URL(Y.resource)}function cJ(Q){let X=Q.headers.get("WWW-Authenticate");if(!X)return{};let[Y,W]=X.split(" ");if(Y.toLowerCase()!=="bearer"||!W)return{};let $=mJ(Q,"resource_metadata")||void 0,J;if($)try{J=new URL($)}catch{}let G=mJ(Q,"scope")||void 0,H=mJ(Q,"error")||void 0;return{resourceMetadataUrl:J,scope:G,error:H}}function mJ(Q,X){let Y=Q.headers.get("WWW-Authenticate");if(!Y)return null;let W=new RegExp(`${X}=(?:"([^"]+)"|([^\\s,]+))`),$=Y.match(W);if($)return $[1]||$[2];return null}async function Jg(Q,X,Y=fetch){let W=await Bg(Q,"oauth-protected-resource",Y,{protocolVersion:X?.protocolVersion,metadataUrl:X?.resourceMetadataUrl});if(!W||W.status===404)throw await W?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!W.ok)throw await W.body?.cancel(),Error(`HTTP ${W.status} trying to load well-known OAuth protected resource metadata.`);return zO.parse(await W.json())}async function pJ(Q,X,Y=fetch){try{return await Y(Q,{headers:X})}catch(W){if(W instanceof TypeError)if(X)return pJ(Q,void 0,Y);else return;throw W}}function Gg(Q,X="",Y={}){if(X.endsWith("/"))X=X.slice(0,-1);return Y.prependPathname?`${X}/.well-known/${Q}`:`/.well-known/${Q}${X}`}async function OO(Q,X,Y=fetch){return await pJ(Q,{"MCP-Protocol-Version":X},Y)}function Hg(Q,X){return!Q||Q.status>=400&&Q.status<500&&X!=="/"}async function Bg(Q,X,Y,W){let $=new URL(Q),J=W?.protocolVersion??U6,G;if(W?.metadataUrl)G=new URL(W.metadataUrl);else{let B=Gg(X,$.pathname);G=new URL(B,W?.metadataServerUrl??$),G.search=$.search}let H=await OO(G,J,Y);if(!W?.metadataUrl&&Hg(H,$.pathname)){let B=new URL(`/.well-known/${X}`,$);H=await OO(B,J,Y)}return H}function zg(Q){let X=typeof Q==="string"?new URL(Q):Q,Y=X.pathname!=="/",W=[];if(!Y)return W.push({url:new URL("/.well-known/oauth-authorization-server",X.origin),type:"oauth"}),W.push({url:new URL("/.well-known/openid-configuration",X.origin),type:"oidc"}),W;let $=X.pathname;if($.endsWith("/"))$=$.slice(0,-1);return W.push({url:new URL(`/.well-known/oauth-authorization-server${$}`,X.origin),type:"oauth"}),W.push({url:new URL(`/.well-known/openid-configuration${$}`,X.origin),type:"oidc"}),W.push({url:new URL(`${$}/.well-known/openid-configuration`,X.origin),type:"oidc"}),W}async function Kg(Q,{fetchFn:X=fetch,protocolVersion:Y=U6}={}){let W={"MCP-Protocol-Version":Y,Accept:"application/json"},$=zg(Q);for(let{url:J,type:G}of $){let H=await pJ(J,W,X);if(!H)continue;if(!H.ok){if(await H.body?.cancel(),H.status>=400&&H.status<500)continue;throw Error(`HTTP ${H.status} trying to load ${G==="oauth"?"OAuth":"OpenID provider"} metadata from ${J}`)}if(G==="oauth")return gJ.parse(await H.json());else return KO.parse(await H.json())}return}async function Vg(Q,{metadata:X,clientInformation:Y,redirectUrl:W,scope:$,state:J,resource:G}){let H;if(X){if(H=new URL(X.authorization_endpoint),!X.response_types_supported.includes(hJ))throw Error(`Incompatible auth server: does not support response type ${hJ}`);if(X.code_challenge_methods_supported&&!X.code_challenge_methods_supported.includes(uJ))throw Error(`Incompatible auth server: does not support code challenge method ${uJ}`)}else H=new URL("/authorize",Q);let B=await fJ(),z=B.code_verifier,K=B.code_challenge;if(H.searchParams.set("response_type",hJ),H.searchParams.set("client_id",Y.client_id),H.searchParams.set("code_challenge",K),H.searchParams.set("code_challenge_method",uJ),H.searchParams.set("redirect_uri",String(W)),J)H.searchParams.set("state",J);if($)H.searchParams.set("scope",$);if($?.includes("offline_access"))H.searchParams.append("prompt","consent");if(G)H.searchParams.set("resource",G.href);return{authorizationUrl:H,codeVerifier:z}}function Fg(Q,X,Y){return new URLSearchParams({grant_type:"authorization_code",code:Q,code_verifier:X,redirect_uri:String(Y)})}async function jO(Q,{metadata:X,tokenRequestParams:Y,clientInformation:W,addClientAuthentication:$,resource:J,fetchFn:G}){let H=X?.token_endpoint?new URL(X.token_endpoint):new URL("/token",Q),B=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(J)Y.set("resource",J.href);if($)await $(B,Y,H,X);else if(W){let K=X?.token_endpoint_auth_methods_supported??[],V=sf(W,K);ef(V,W,B,Y)}let z=await(G??fetch)(H,{method:"POST",headers:B,body:Y});if(!z.ok)throw await UO(z);return VO.parse(await z.json())}async function Ag(Q,{metadata:X,clientInformation:Y,refreshToken:W,resource:$,addClientAuthentication:J,fetchFn:G}){let H=new URLSearchParams({grant_type:"refresh_token",refresh_token:W}),B=await jO(Q,{metadata:X,tokenRequestParams:H,clientInformation:Y,addClientAuthentication:J,resource:$,fetchFn:G});return{refresh_token:W,...B}}async function qg(Q,X,{metadata:Y,resource:W,authorizationCode:$,fetchFn:J}={}){let G=Q.clientMetadata.scope,H;if(Q.prepareTokenRequest)H=await Q.prepareTokenRequest(G);if(!H){if(!$)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!Q.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let z=await Q.codeVerifier();H=Fg($,z,Q.redirectUrl)}let B=await Q.clientInformation();return jO(X,{metadata:Y,tokenRequestParams:H,clientInformation:B??void 0,addClientAuthentication:Q.addClientAuthentication,resource:W,fetchFn:J})}async function Dg(Q,{metadata:X,clientMetadata:Y,fetchFn:W}){let $;if(X){if(!X.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");$=new URL(X.registration_endpoint)}else $=new URL("/register",Q);let J=await(W??fetch)($,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!J.ok)throw await UO(J);return AO.parse(await J.json())}class iJ extends Error{constructor(Q,X){super(Q),this.name="ParseError",this.type=X.type,this.field=X.field,this.value=X.value,this.line=X.line}}function dJ(Q){}function MO(Q){if(typeof Q=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:X=dJ,onError:Y=dJ,onRetry:W=dJ,onComment:$}=Q,J="",G=!0,H,B="",z="";function K(D){let L=G?D.replace(/^\xEF\xBB\xBF/,""):D,[O,N]=Lg(`${J}${L}`);for(let w of O)V(w);J=N,G=!1}function V(D){if(D===""){F();return}if(D.startsWith(":")){$&&$(D.slice(D.startsWith(": ")?2:1));return}let L=D.indexOf(":");if(L!==-1){let O=D.slice(0,L),N=D[L+1]===" "?2:1,w=D.slice(L+N);q(O,w,D);return}q(D,"",D)}function q(D,L,O){switch(D){case"event":z=L;break;case"data":B=`${B}${L}
49
+ `}class ZJ{constructor(Q=WO.stdin,X=WO.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new o4,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}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)}processReadBuffer(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(Q){return new Promise((X)=>{let Y=OY(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}import{readFileSync as Gh}from"fs";import UY from"node:crypto";var JO="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jY=32;var Tf=16,GO=10,$O=281474976710655;var D9;(function(Q){Q.Base32IncorrectEncoding="B32_ENC_INVALID",Q.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",Q.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",Q.EncodeTimeNegative="ENC_TIME_NEG",Q.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",Q.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",Q.PRNGDetectFailure="PRNG_DETECT",Q.ULIDInvalid="ULID_INVALID",Q.Unexpected="UNEXPECTED",Q.UUIDInvalid="UUID_INVALID"})(D9||(D9={}));class V8 extends Error{constructor(Q,X){super(`${X} (${Q})`);this.name="ULIDError",this.code=Q}}function Cf(Q){let X=Math.floor(Q()*jY)%jY;return JO.charAt(X)}function kf(Q){let X=vf(),Y=X&&(X.crypto||X.msCrypto)||(typeof UY<"u"?UY:null);if(typeof Y?.getRandomValues==="function")return()=>{let W=new Uint8Array(1);return Y.getRandomValues(W),W[0]/256};else if(typeof Y?.randomBytes==="function")return()=>Y.randomBytes(1).readUInt8()/256;else if(UY?.randomBytes)return()=>UY.randomBytes(1).readUInt8()/256;throw new V8(D9.PRNGDetectFailure,"Failed to find a reliable PRNG")}function vf(){if(yf())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function _f(Q,X){let Y="";for(;Q>0;Q--)Y=Cf(X)+Y;return Y}function xf(Q,X=GO){if(isNaN(Q))throw new V8(D9.EncodeTimeValueMalformed,`Time must be a number: ${Q}`);else if(Q>$O)throw new V8(D9.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${$O}: ${Q}`);else if(Q<0)throw new V8(D9.EncodeTimeNegative,`Time must be positive: ${Q}`);else if(Number.isInteger(Q)===!1)throw new V8(D9.EncodeTimeValueMalformed,`Time must be an integer: ${Q}`);let Y,W="";for(let $=X;$>0;$--)Y=Q%jY,W=JO.charAt(Y)+W,Q=(Q-Y)/jY;return W}function yf(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function f1(Q,X){let Y=X||kf(),W=!Q||isNaN(Q)?Date.now():Q;return xf(W,GO)+_f(Tf,Y)}function RJ(Q){return Q.type==="http"}function EJ(Q){return Q.type==="stdio"}class SJ{configs=new Map;logger;constructor(Q={}){this.logger=Q.logger}addConfig(Q,X,Y,W){let $=this.configs.has(Q);return this.configs.set(Q,{name:Q,type:"http",url:X,headers:Y?.headers,addedAt:new Date,addedBy:W}),this.logger?.info($?"server_config_updated":"server_config_added",{server:Q,type:"http",url:X,hasHeaders:Y?.headers!==void 0,addedBy:W}),!$}addStdioConfig(Q,X,Y,W,$){let J=this.configs.has(Q);return this.configs.set(Q,{name:Q,type:"stdio",command:X,args:Y,env:W?.env,cwd:W?.cwd,restartConfig:W?.restartConfig,addedAt:new Date,addedBy:$}),this.logger?.info(J?"server_config_updated":"server_config_added",{server:Q,type:"stdio",command:X,args:Y,addedBy:$}),!J}getConfig(Q){return this.configs.get(Q)}listConfigs(){return Array.from(this.configs.values())}removeConfig(Q){let X=this.configs.delete(Q);if(X)this.logger?.info("server_config_removed",{server:Q});return X}hasConfig(Q){return this.configs.has(Q)}get size(){return this.configs.size}clear(){this.configs.clear(),this.logger?.info("server_configs_cleared",{})}}var ff={maxEvents:1000,retentionMs:1800000,cleanupIntervalMs:300000};class IJ{events=[];config;logger;lastDeliveredId=null;waiters=[];cleanupIntervalHandle=null;constructor(Q={},X){this.config={...ff,...Q},this.logger=X,this.startCleanupInterval()}addEvent(Q,X,Y){let W=f1(),$={id:W,type:Q,server:X,data:Y,createdAt:new Date,sentViaSSE:!1};this.events.push($);while(this.events.length>this.config.maxEvents)this.events.shift();return this.logger?.debug("event_added",{id:W,type:Q,server:X}),this.wakeWaiters($),W}hasNewEvents(){if(this.lastDeliveredId===null)return this.events.length>0;let Q=this.events.findIndex((X)=>X.id===this.lastDeliveredId);if(Q===-1)return this.events.length>0;return Q<this.events.length-1}getNewEvents(){if(this.events.length===0)return[];let Q=0;if(this.lastDeliveredId!==null){let Y=this.events.findIndex((W)=>W.id===this.lastDeliveredId);if(Y!==-1)Q=Y+1}let X=this.events.slice(Q);if(X.length>0){let Y=X[X.length-1];if(Y)this.lastDeliveredId=Y.id}return X}getEventsAfter(Q){if(Q===null)return[...this.events];let X=this.events.findIndex((Y)=>Y.id===Q);if(X===-1)return[...this.events];return this.events.slice(X+1)}markSent(Q){let X=this.events.find((Y)=>Y.id===Q);if(X)X.sentViaSSE=!0}waitForActivity(Q){return new Promise((X)=>{let Y=setTimeout(()=>{let W=this.waiters.findIndex(($)=>$.timeoutHandle===Y);if(W!==-1)this.waiters.splice(W,1);X(null)},Q);this.waiters.push({resolve:X,timeoutHandle:Y})})}wakeWaiters(Q){let X=this.waiters;this.waiters=[];for(let Y of X)clearTimeout(Y.timeoutHandle),Y.resolve(Q)}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runCleanup()},this.config.cleanupIntervalMs)}runCleanup(){let Q=Date.now()-this.config.retentionMs,X=0;while(this.events.length>0){let Y=this.events[0];if(Y&&Y.createdAt.getTime()<Q)this.events.shift(),X++;else break}if(X>0)this.logger?.debug("events_cleaned",{removed:X,remaining:this.events.length})}shutdown(){if(this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of this.waiters)clearTimeout(Q.timeoutHandle),Q.resolve(null);this.waiters=[]}}var gf={defaultTtlMs:600000,completedRetentionMs:300000,cleanupIntervalMs:60000};class TJ{tasks=new Map;eventSystem;config;cleanupIntervalHandle=null;constructor(Q,X={}){this.eventSystem=Q,this.config={...gf,...X},this.startCleanupInterval()}createTask(Q,X,Y,W){let $=f1(),J=new Date,G={taskId:$,server:Q,toolName:X,args:Y,status:"working",createdAt:J,lastUpdatedAt:J,ttl:W??this.config.defaultTtlMs};return this.tasks.set($,G),this.eventSystem.addEvent("task_created",Q,{taskId:$,toolName:X,args:Y}),G}completeTask(Q,X){let Y=this.tasks.get(Q);if(Y?.status!=="working")return;Y.status="completed",Y.result=X,Y.lastUpdatedAt=new Date,this.scheduleTaskCleanup(Y),this.eventSystem.addEvent("task_completed",Y.server,{taskId:Q,toolName:Y.toolName,result:X})}failTask(Q,X){let Y=this.tasks.get(Q);if(Y?.status!=="working")return;Y.status="failed",Y.error=X,Y.lastUpdatedAt=new Date,this.scheduleTaskCleanup(Y),this.eventSystem.addEvent("task_failed",Y.server,{taskId:Q,toolName:Y.toolName,error:X})}cancelTask(Q){let X=this.tasks.get(Q);if(X?.status!=="working")return!1;return X.status="cancelled",X.lastUpdatedAt=new Date,this.scheduleTaskCleanup(X),this.eventSystem.addEvent("task_cancelled",X.server,{taskId:Q,toolName:X.toolName}),!0}getTask(Q){let X=this.tasks.get(Q);if(!X)return;let{_cleanupTimeoutHandle:Y,...W}=X;return W}getTasksForServer(Q){return Array.from(this.tasks.values()).filter((X)=>X.server===Q).map((X)=>({taskId:X.taskId,server:X.server,toolName:X.toolName,args:X.args,status:X.status,result:X.result,error:X.error,createdAt:X.createdAt,lastUpdatedAt:X.lastUpdatedAt,ttl:X.ttl}))}getAllTasks(Q=!1){let X=["completed","failed","cancelled","expired"];return Array.from(this.tasks.values()).filter((Y)=>Q||!X.includes(Y.status)).map((Y)=>({taskId:Y.taskId,server:Y.server,toolName:Y.toolName,args:Y.args,status:Y.status,result:Y.result,error:Y.error,createdAt:Y.createdAt,lastUpdatedAt:Y.lastUpdatedAt,ttl:Y.ttl}))}getWorkingTasksForServer(Q){return Array.from(this.tasks.values()).filter((X)=>X.server===Q&&X.status==="working").map((X)=>({taskId:X.taskId,toolName:X.toolName,status:X.status}))}scheduleTaskCleanup(Q){if(Q._cleanupTimeoutHandle)clearTimeout(Q._cleanupTimeoutHandle);Q._cleanupTimeoutHandle=setTimeout(()=>{this.tasks.delete(Q.taskId)},this.config.completedRetentionMs)}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runCleanup()},this.config.cleanupIntervalMs)}runCleanup(){let Q=Date.now();for(let X of this.tasks.values()){if(X.status!=="working")continue;if(Q-X.createdAt.getTime()>=X.ttl)X.status="expired",X.error=`Task expired after ${String(X.ttl)}ms TTL`,X.lastUpdatedAt=new Date,this.eventSystem.addEvent("task_expired",X.server,{taskId:X.taskId,toolName:X.toolName,ttl:X.ttl}),this.scheduleTaskCleanup(X)}}shutdown(){if(this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of this.tasks.values())if(Q._cleanupTimeoutHandle)clearTimeout(Q._cleanupTimeoutHandle)}}var hf={maxNotificationsPerServer:100,maxLogsPerServer:500};class CJ{buffers=new Map;eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...hf,...X}}addNotification(Q){let X=this.getOrCreateBuffers(Q.server);if(X.notifications.length>=this.config.maxNotificationsPerServer)X.notifications.shift();X.notifications.push(Q),this.eventSystem.addEvent("notification",Q.server,{method:Q.method,params:Q.params,timestamp:Q.timestamp.toISOString()})}addLog(Q){let X=this.getOrCreateBuffers(Q.server);if(X.logs.length>=this.config.maxLogsPerServer)X.logs.shift();X.logs.push(Q)}getAndClearNotifications(){let Q=[];for(let X of this.buffers.values())Q.push(...X.notifications),X.notifications=[];return Q}getAndClearLogs(){let Q=[];for(let X of this.buffers.values())Q.push(...X.logs),X.logs=[];return Q}getNotificationsForServer(Q){let X=this.buffers.get(Q);return X?[...X.notifications]:[]}getLogsForServer(Q){let X=this.buffers.get(Q);return X?[...X.logs]:[]}getNotificationCount(){let Q=0;for(let X of this.buffers.values())Q+=X.notifications.length;return Q}getLogCount(){let Q=0;for(let X of this.buffers.values())Q+=X.logs.length;return Q}clearServer(Q){this.buffers.delete(Q)}getOrCreateBuffers(Q){let X=this.buffers.get(Q);if(!X)X={notifications:[],logs:[]},this.buffers.set(Q,X);return X}}var uf={defaultTimeoutMs:600000};class kJ{samplingRequests=new Map;elicitationRequests=new Map;eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...uf,...X}}addSamplingRequest(Q,X,Y,W){let $=f1(),J=setTimeout(()=>{let H=this.samplingRequests.get($);if(H)this.samplingRequests.delete($),this.eventSystem.addEvent("sampling_expired",Q,{requestId:$,reason:`Timed out after ${String(this.config.defaultTimeoutMs)}ms`}),H.reject(Error(`Sampling request timed out after ${String(this.config.defaultTimeoutMs)}ms`))},this.config.defaultTimeoutMs),G={requestId:$,server:Q,timestamp:new Date,params:X,resolve:Y,reject:W,timeoutHandle:J};return this.samplingRequests.set($,G),this.eventSystem.addEvent("sampling_request",Q,{requestId:$,params:X}),$}addElicitationRequest(Q,X,Y,W){let $=f1(),J=setTimeout(()=>{let H=this.elicitationRequests.get($);if(H)this.elicitationRequests.delete($),this.eventSystem.addEvent("elicitation_expired",Q,{requestId:$,reason:`Timed out after ${String(this.config.defaultTimeoutMs)}ms`}),H.reject(Error(`Elicitation request timed out after ${String(this.config.defaultTimeoutMs)}ms`))},this.config.defaultTimeoutMs),G={requestId:$,server:Q,timestamp:new Date,params:X,resolve:Y,reject:W,timeoutHandle:J};return this.elicitationRequests.set($,G),this.eventSystem.addEvent("elicitation_request",Q,{requestId:$,params:X}),$}respondToSampling(Q,X){let Y=this.samplingRequests.get(Q);if(!Y)throw Error(`Sampling request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.samplingRequests.delete(Q),Y.resolve(X)}cancelSampling(Q,X="User cancelled"){let Y=this.samplingRequests.get(Q);if(!Y)throw Error(`Sampling request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.samplingRequests.delete(Q),this.eventSystem.addEvent("sampling_expired",Y.server,{requestId:Q,reason:X}),Y.reject(Error(X))}respondToElicitation(Q,X){let Y=this.elicitationRequests.get(Q);if(!Y)throw Error(`Elicitation request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.elicitationRequests.delete(Q),Y.resolve(X)}cancelElicitation(Q,X="User cancelled"){let Y=this.elicitationRequests.get(Q);if(!Y)throw Error(`Elicitation request '${Q}' not found or already completed`);clearTimeout(Y.timeoutHandle),this.elicitationRequests.delete(Q),this.eventSystem.addEvent("elicitation_expired",Y.server,{requestId:Q,reason:X}),Y.reject(Error(X))}getPendingSamplingRequests(){return Array.from(this.samplingRequests.values()).map((Q)=>({requestId:Q.requestId,server:Q.server,timestamp:Q.timestamp,params:Q.params}))}getPendingElicitationRequests(){return Array.from(this.elicitationRequests.values()).map((Q)=>({requestId:Q.requestId,server:Q.server,timestamp:Q.timestamp,params:Q.params}))}getRequestsForServer(Q){return{sampling:this.getPendingSamplingRequests().filter((X)=>X.server===Q),elicitation:this.getPendingElicitationRequests().filter((X)=>X.server===Q)}}hasPendingRequests(){return this.samplingRequests.size>0||this.elicitationRequests.size>0}rejectRequestsForServer(Q,X){for(let[Y,W]of this.samplingRequests)if(W.server===Q)clearTimeout(W.timeoutHandle),this.samplingRequests.delete(Y),this.eventSystem.addEvent("sampling_expired",Q,{requestId:Y,reason:X}),W.reject(Error(X));for(let[Y,W]of this.elicitationRequests)if(W.server===Q)clearTimeout(W.timeoutHandle),this.elicitationRequests.delete(Y),this.eventSystem.addEvent("elicitation_expired",Q,{requestId:Y,reason:X}),W.reject(Error(X))}shutdown(){for(let Q of this.samplingRequests.values())clearTimeout(Q.timeoutHandle),Q.reject(Error("PendingRequestsManager shutting down"));this.samplingRequests.clear();for(let Q of this.elicitationRequests.values())clearTimeout(Q.timeoutHandle),Q.reject(Error("PendingRequestsManager shutting down"));this.elicitationRequests.clear()}}var lf={maxActiveTimers:100,maxDurationMs:86400000,retentionMs:300000};class vJ{timers=new Map;expiredBuffer=[];eventSystem;config;constructor(Q,X={}){this.eventSystem=Q,this.config={...lf,...X}}createTimer(Q,X,Y=!1){if(this.getActiveTimers().length>=this.config.maxActiveTimers)throw Error(`Maximum active timers (${String(this.config.maxActiveTimers)}) exceeded`);if(Q<=0)throw Error("Duration must be positive");if(Q>this.config.maxDurationMs)throw Error(`Duration exceeds maximum (${String(this.config.maxDurationMs)}ms)`);let $=f1(),J=new Date,G=new Date(J.getTime()+Q),H={id:$,durationMs:Q,message:X,createdAt:J,expiresAt:G,status:"active",interval:Y,fireCount:0};if(Y)H._intervalHandle=setInterval(()=>{this.fireIntervalTimer($)},Q);else H._timeoutHandle=setTimeout(()=>{this.expireTimer($)},Q);return this.timers.set($,H),this.toPublicTimer(H)}getTimer(Q){let X=this.timers.get(Q);if(!X)return;return this.toPublicTimer(X)}deleteTimer(Q){let X=this.timers.get(Q);if(!X)return;if(X._timeoutHandle)clearTimeout(X._timeoutHandle),X._timeoutHandle=void 0;if(X._intervalHandle)clearInterval(X._intervalHandle),X._intervalHandle=void 0;return X.status="deleted",this.scheduleCleanup(X),this.toPublicTimer(X)}getAllTimers(Q=!1){let X=Array.from(this.timers.values());return(Q?X:X.filter((W)=>W.status==="active")).map((W)=>this.toPublicTimer(W))}getActiveTimers(){return Array.from(this.timers.values()).filter((Q)=>Q.status==="active").map((Q)=>this.toPublicTimer(Q))}getAndClearExpired(){let Q=[...this.expiredBuffer];return this.expiredBuffer.length=0,Q}hasExpired(){return this.expiredBuffer.length>0}shutdown(){for(let Q of this.timers.values()){if(Q._timeoutHandle)clearTimeout(Q._timeoutHandle);if(Q._intervalHandle)clearInterval(Q._intervalHandle)}this.timers.clear(),this.expiredBuffer.length=0}expireTimer(Q){let X=this.timers.get(Q);if(!X?.status||X.status!=="active")return;X.status="expired",X._timeoutHandle=void 0,X.fireCount++,this.expiredBuffer.push({id:X.id,message:X.message,expiredAt:new Date().toISOString()}),this.eventSystem.addEvent("timer_expired","emceepee",{timerId:X.id,message:X.message}),this.scheduleCleanup(X)}fireIntervalTimer(Q){let X=this.timers.get(Q);if(!X?.status||X.status!=="active")return;X.fireCount++,X.expiresAt=new Date(Date.now()+X.durationMs),this.expiredBuffer.push({id:X.id,message:X.message,expiredAt:new Date().toISOString()}),this.eventSystem.addEvent("timer_expired","emceepee",{timerId:X.id,message:X.message,fireCount:X.fireCount,interval:!0})}scheduleCleanup(Q){setTimeout(()=>{this.timers.delete(Q.id)},this.config.retentionMs)}toPublicTimer(Q){return{id:Q.id,durationMs:Q.durationMs,message:Q.message,createdAt:Q.createdAt,expiresAt:Q.expiresAt,status:Q.status,interval:Q.interval,fireCount:Q.fireCount}}}class _J{sessionId;createdAt;lastActivityAt;backendConnections=new Map;eventSystem;taskManager;pendingRequests;bufferManager;timerManager;logger;constructor(Q,X={},Y){this.sessionId=Q,this.createdAt=new Date,this.lastActivityAt=new Date,this.logger=Y,this.eventSystem=new IJ(X.eventSystemConfig,Y),this.taskManager=new TJ(this.eventSystem,X.taskConfig),this.pendingRequests=new kJ(this.eventSystem,X.requestConfig),this.bufferManager=new CJ(this.eventSystem,X.bufferConfig),this.timerManager=new vJ(this.eventSystem,X.timerConfig)}touch(){this.lastActivityAt=new Date}getConnection(Q){return this.backendConnections.get(Q)}isConnectedTo(Q){return this.backendConnections.get(Q)?.status==="connected"}listConnectedServers(){return Array.from(this.backendConnections.entries()).filter(([,Q])=>Q.status==="connected").map(([Q])=>Q)}listConnections(){return Array.from(this.backendConnections.entries()).map(([Q,X])=>({name:Q,status:X.status,connectedAt:X.connectedAt,lastError:X.lastError}))}setConnectionStatus(Q,X,Y){let W=this.backendConnections.get(Q);if(W){if(W.status=X,X==="connected")W.connectedAt=new Date,W.lastError=void 0;else if(X==="error"&&Y)W.lastError=Y}}addConnection(Q,X){this.backendConnections.set(Q,{client:X,status:"connecting"})}removeConnection(Q){return this.backendConnections.delete(Q)}async cleanup(){this.logger?.info("session_cleanup_start",{sessionId:this.sessionId}),this.pendingRequests.shutdown(),this.taskManager.shutdown(),this.timerManager.shutdown(),this.eventSystem.shutdown();for(let[Q,X]of this.backendConnections)try{await X.client.disconnect(),this.logger?.debug("session_backend_disconnected",{sessionId:this.sessionId,server:Q})}catch(Y){this.logger?.debug("session_backend_disconnect_error",{sessionId:this.sessionId,server:Q,error:Y instanceof Error?Y.message:String(Y)})}this.backendConnections.clear(),this.logger?.info("session_cleanup_complete",{sessionId:this.sessionId})}}class xJ{constructor(Q){this._client=Q}async*callToolStream(Q,X=M6,Y){let W=this._client,$={...Y,task:Y?.task??(W.isToolTask(Q.name)?{}:void 0)},J=W.requestStream({method:"tools/call",params:Q},X,$),G=W.getToolOutputValidator(Q.name);for await(let H of J){if(H.type==="result"&&G){let B=H.result;if(!B.structuredContent&&!B.isError){yield{type:"error",error:new S(k.InvalidRequest,`Tool ${Q.name} has an output schema but did not return structured content`)};return}if(B.structuredContent)try{let z=G(B.structuredContent);if(!z.valid){yield{type:"error",error:new S(k.InvalidParams,`Structured content does not match the tool's output schema: ${z.errorMessage}`)};return}}catch(z){if(z instanceof S){yield{type:"error",error:z};return}yield{type:"error",error:new S(k.InvalidParams,`Failed to validate structured content: ${z instanceof Error?z.message:String(z)}`)};return}}yield H}}async getTask(Q,X){return this._client.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._client.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._client.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._client.cancelTask({taskId:Q},X)}requestStream(Q,X,Y){return this._client.requestStream(Q,X,Y)}}function MY(Q,X){if(!Q||X===null||typeof X!=="object")return;if(Q.type==="object"&&Q.properties&&typeof Q.properties==="object"){let Y=X,W=Q.properties;for(let $ of Object.keys(W)){let J=W[$];if(Y[$]===void 0&&Object.prototype.hasOwnProperty.call(J,"default"))Y[$]=J.default;if(Y[$]!==void 0)MY(J,Y[$])}}if(Array.isArray(Q.anyOf)){for(let Y of Q.anyOf)if(typeof Y!=="boolean")MY(Y,X)}if(Array.isArray(Q.oneOf)){for(let Y of Q.oneOf)if(typeof Y!=="boolean")MY(Y,X)}}function mf(Q){if(!Q)return{supportsFormMode:!1,supportsUrlMode:!1};let X=Q.form!==void 0,Y=Q.url!==void 0;return{supportsFormMode:X||!X&&!Y,supportsUrlMode:Y}}class F8 extends Q4{constructor(Q,X){super(X);if(this._clientInfo=Q,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=X?.capabilities??{},this._jsonSchemaValidator=X?.jsonSchemaValidator??new i4,X?.listChanged)this._pendingListChangedConfig=X.listChanged}_setupListChangedHandlers(Q){if(Q.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",Q9,Q.tools,async()=>{return(await this.listTools()).tools});if(Q.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",e6,Q.prompts,async()=>{return(await this.listPrompts()).prompts});if(Q.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",s6,Q.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new xJ(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=aQ(this._capabilities,Q)}setRequestHandler(Q,X){let W=c1(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let $;if(s0(W)){let G=W;$=G._zod?.def?.value??G.value}else{let G=W;$=G._def?.value??G.value}if(typeof $!=="string")throw Error("Schema method literal must be a string");let J=$;if(J==="elicitation/create"){let G=async(H,B)=>{let z=c0(Y9,H);if(!z.success){let O=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid elicitation request: ${O}`)}let{params:K}=z.data;K.mode=K.mode??"form";let{supportsFormMode:V,supportsUrlMode:q}=mf(this._capabilities.elicitation);if(K.mode==="form"&&!V)throw new S(k.InvalidParams,"Client does not support form-mode elicitation requests");if(K.mode==="url"&&!q)throw new S(k.InvalidParams,"Client does not support URL-mode elicitation requests");let F=await Promise.resolve(X(H,B));if(K.task){let O=c0(Q6,F);if(!O.success){let N=O.error instanceof Error?O.error.message:String(O.error);throw new S(k.InvalidParams,`Invalid task creation result: ${N}`)}return O.data}let A=c0(c9,F);if(!A.success){let O=A.error instanceof Error?A.error.message:String(A.error);throw new S(k.InvalidParams,`Invalid elicitation result: ${O}`)}let D=A.data,L=K.mode==="form"?K.requestedSchema:void 0;if(K.mode==="form"&&D.action==="accept"&&D.content&&L){if(this._capabilities.elicitation?.form?.applyDefaults)try{MY(L,D.content)}catch{}}return D};return super.setRequestHandler(Q,G)}if(J==="sampling/createMessage"){let G=async(H,B)=>{let z=c0(X9,H);if(!z.success){let F=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid sampling request: ${F}`)}let{params:K}=z.data,V=await Promise.resolve(X(H,B));if(K.task){let F=c0(Q6,V);if(!F.success){let A=F.error instanceof Error?F.error.message:String(F.error);throw new S(k.InvalidParams,`Invalid task creation result: ${A}`)}return F.data}let q=c0(s8,V);if(!q.success){let F=q.error instanceof Error?q.error.message:String(q.error);throw new S(k.InvalidParams,`Invalid sampling result: ${F}`)}return q.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapability(Q,X){if(!this._serverCapabilities?.[Q])throw Error(`Server does not support ${Q} (required for ${X})`)}async connect(Q,X){if(await super.connect(Q),Q.sessionId!==void 0)return;try{let Y=await this.request({method:"initialize",params:{protocolVersion:U6,capabilities:this._capabilities,clientInfo:this._clientInfo}},$5,X);if(Y===void 0)throw Error(`Server sent invalid initialize result: ${Y}`);if(!EQ.includes(Y.protocolVersion))throw Error(`Server's protocol version is not supported: ${Y.protocolVersion}`);if(this._serverCapabilities=Y.capabilities,this._serverVersion=Y.serverInfo,Q.setProtocolVersion)Q.setProtocolVersion(Y.protocolVersion);if(this._instructions=Y.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(Y){throw this.close(),Y}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(Q){switch(Q){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${Q})`);if(Q==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${Q})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${Q})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${Q})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${Q})`);break;case"ping":break}}assertTaskCapability(Q){DY(this._serverCapabilities?.tasks?.requests,Q,"Server")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;LY(this._capabilities.tasks?.requests,Q,"Client")}async ping(Q){return this.request({method:"ping"},e1,Q)}async complete(Q,X){return this.request({method:"completion/complete",params:Q},j5,X)}async setLoggingLevel(Q,X){return this.request({method:"logging/setLevel",params:{level:Q}},e1,X)}async getPrompt(Q,X){return this.request({method:"prompts/get",params:Q},D5,X)}async listPrompts(Q,X){return this.request({method:"prompts/list",params:Q},K5,X)}async listResources(Q,X){return this.request({method:"resources/list",params:Q},G5,X)}async listResourceTemplates(Q,X){return this.request({method:"resources/templates/list",params:Q},H5,X)}async readResource(Q,X){return this.request({method:"resources/read",params:Q},z5,X)}async subscribeResource(Q,X){return this.request({method:"resources/subscribe",params:Q},e1,X)}async unsubscribeResource(Q,X){return this.request({method:"resources/unsubscribe",params:Q},e1,X)}async callTool(Q,X=M6,Y){if(this.isToolTaskRequired(Q.name))throw new S(k.InvalidRequest,`Tool "${Q.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let W=await this.request({method:"tools/call",params:Q},X,Y),$=this.getToolOutputValidator(Q.name);if($){if(!W.structuredContent&&!W.isError)throw new S(k.InvalidRequest,`Tool ${Q.name} has an output schema but did not return structured content`);if(W.structuredContent)try{let J=$(W.structuredContent);if(!J.valid)throw new S(k.InvalidParams,`Structured content does not match the tool's output schema: ${J.errorMessage}`)}catch(J){if(J instanceof S)throw J;throw new S(k.InvalidParams,`Failed to validate structured content: ${J instanceof Error?J.message:String(J)}`)}}return W}isToolTask(Q){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(Q)}isToolTaskRequired(Q){return this._cachedRequiredTaskTools.has(Q)}cacheToolMetadata(Q){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let X of Q){if(X.outputSchema){let W=this._jsonSchemaValidator.getValidator(X.outputSchema);this._cachedToolOutputValidators.set(X.name,W)}let Y=X.execution?.taskSupport;if(Y==="required"||Y==="optional")this._cachedKnownTaskTools.add(X.name);if(Y==="required")this._cachedRequiredTaskTools.add(X.name)}}getToolOutputValidator(Q){return this._cachedToolOutputValidators.get(Q)}async listTools(Q,X){let Y=await this.request({method:"tools/list",params:Q},L5,X);return this.cacheToolMetadata(Y.tools),Y}_setupListChangedHandler(Q,X,Y,W){let $=_3.safeParse(Y);if(!$.success)throw Error(`Invalid ${Q} listChanged options: ${$.error.message}`);if(typeof Y.onChanged!=="function")throw Error(`Invalid ${Q} listChanged options: onChanged must be a function`);let{autoRefresh:J,debounceMs:G}=$.data,{onChanged:H}=Y,B=async()=>{if(!J){H(null,null);return}try{let K=await W();H(null,K)}catch(K){let V=K instanceof Error?K:Error(String(K));H(V,null)}},z=()=>{if(G){let K=this._listChangedDebounceTimers.get(Q);if(K)clearTimeout(K);let V=setTimeout(B,G);this._listChangedDebounceTimers.set(Q,V)}else B()};this.setNotificationHandler(X,z)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function NY(Q){if(!Q)return{};if(Q instanceof Headers)return Object.fromEntries(Q.entries());if(Array.isArray(Q))return Object.fromEntries(Q);return{...Q}}function HO(Q=fetch,X){if(!X)return Q;return async(Y,W)=>{let $={...X,...W,headers:W?.headers?{...NY(X.headers),...NY(W.headers)}:X.headers};return Q(Y,$)}}var yJ;yJ=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((Q)=>Q.webcrypto);async function cf(Q){return(await yJ).getRandomValues(new Uint8Array(Q))}async function pf(Q){let Y=Math.pow(2,8)-Math.pow(2,8)%66,W="";while(W.length<Q){let $=await cf(Q-W.length);for(let J of $)if(J<Y)W+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[J%66]}return W}async function df(Q){return await pf(Q)}async function nf(Q){let X=await(await yJ).subtle.digest("SHA-256",new TextEncoder().encode(Q));return btoa(String.fromCharCode(...new Uint8Array(X))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function fJ(Q){if(!Q)Q=43;if(Q<43||Q>128)throw`Expected a length between 43 and 128. Received ${Q}.`;let X=await df(Q),Y=await nf(X);return{code_verifier:X,code_challenge:Y}}var g0=H3().superRefine((Q,X)=>{if(!URL.canParse(Q))return X.addIssue({code:U3.custom,message:"URL must be parseable",fatal:!0}),YQ}).refine((Q)=>{let X=new URL(Q);return X.protocol!=="javascript:"&&X.protocol!=="data:"&&X.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),zO=T0({resource:U().url(),authorization_servers:E(g0).optional(),jwks_uri:U().url().optional(),scopes_supported:E(U()).optional(),bearer_methods_supported:E(U()).optional(),resource_signing_alg_values_supported:E(U()).optional(),resource_name:U().optional(),resource_documentation:U().optional(),resource_policy_uri:U().url().optional(),resource_tos_uri:U().url().optional(),tls_client_certificate_bound_access_tokens:H0().optional(),authorization_details_types_supported:E(U()).optional(),dpop_signing_alg_values_supported:E(U()).optional(),dpop_bound_access_tokens_required:H0().optional()}),gJ=T0({issuer:U(),authorization_endpoint:g0,token_endpoint:g0,registration_endpoint:g0.optional(),scopes_supported:E(U()).optional(),response_types_supported:E(U()),response_modes_supported:E(U()).optional(),grant_types_supported:E(U()).optional(),token_endpoint_auth_methods_supported:E(U()).optional(),token_endpoint_auth_signing_alg_values_supported:E(U()).optional(),service_documentation:g0.optional(),revocation_endpoint:g0.optional(),revocation_endpoint_auth_methods_supported:E(U()).optional(),revocation_endpoint_auth_signing_alg_values_supported:E(U()).optional(),introspection_endpoint:U().optional(),introspection_endpoint_auth_methods_supported:E(U()).optional(),introspection_endpoint_auth_signing_alg_values_supported:E(U()).optional(),code_challenge_methods_supported:E(U()).optional(),client_id_metadata_document_supported:H0().optional()}),of=T0({issuer:U(),authorization_endpoint:g0,token_endpoint:g0,userinfo_endpoint:g0.optional(),jwks_uri:g0,registration_endpoint:g0.optional(),scopes_supported:E(U()).optional(),response_types_supported:E(U()),response_modes_supported:E(U()).optional(),grant_types_supported:E(U()).optional(),acr_values_supported:E(U()).optional(),subject_types_supported:E(U()),id_token_signing_alg_values_supported:E(U()),id_token_encryption_alg_values_supported:E(U()).optional(),id_token_encryption_enc_values_supported:E(U()).optional(),userinfo_signing_alg_values_supported:E(U()).optional(),userinfo_encryption_alg_values_supported:E(U()).optional(),userinfo_encryption_enc_values_supported:E(U()).optional(),request_object_signing_alg_values_supported:E(U()).optional(),request_object_encryption_alg_values_supported:E(U()).optional(),request_object_encryption_enc_values_supported:E(U()).optional(),token_endpoint_auth_methods_supported:E(U()).optional(),token_endpoint_auth_signing_alg_values_supported:E(U()).optional(),display_values_supported:E(U()).optional(),claim_types_supported:E(U()).optional(),claims_supported:E(U()).optional(),service_documentation:U().optional(),claims_locales_supported:E(U()).optional(),ui_locales_supported:E(U()).optional(),claims_parameter_supported:H0().optional(),request_parameter_supported:H0().optional(),request_uri_parameter_supported:H0().optional(),require_request_uri_registration:H0().optional(),op_policy_uri:g0.optional(),op_tos_uri:g0.optional(),client_id_metadata_document_supported:H0().optional()}),KO=I({...of.shape,...gJ.pick({code_challenge_methods_supported:!0}).shape}),VO=I({access_token:U(),id_token:U().optional(),token_type:U(),expires_in:ZQ.number().optional(),scope:U().optional(),refresh_token:U().optional()}).strip(),FO=I({error:U(),error_description:U().optional(),error_uri:U().optional()}),BO=g0.optional().or(_("").transform(()=>{return})),rf=I({redirect_uris:E(g0),token_endpoint_auth_method:U().optional(),grant_types:E(U()).optional(),response_types:E(U()).optional(),client_name:U().optional(),client_uri:g0.optional(),logo_uri:BO,scope:U().optional(),contacts:E(U()).optional(),tos_uri:BO,policy_uri:U().optional(),jwks_uri:g0.optional(),jwks:z3().optional(),software_id:U().optional(),software_version:U().optional(),software_statement:U().optional()}).strip(),tf=I({client_id:U(),client_secret:U().optional(),client_id_issued_at:J0().optional(),client_secret_expires_at:J0().optional()}).strip(),AO=rf.merge(tf),ho=I({error:U(),error_description:U().optional()}).strip(),uo=I({token:U(),token_type_hint:U().optional()}).strip();function qO(Q){let X=typeof Q==="string"?new URL(Q):new URL(Q.href);return X.hash="",X}function DO({requestedResource:Q,configuredResource:X}){let Y=typeof Q==="string"?new URL(Q):new URL(Q.href),W=typeof X==="string"?new URL(X):new URL(X.href);if(Y.origin!==W.origin)return!1;if(Y.pathname.length<W.pathname.length)return!1;let $=Y.pathname.endsWith("/")?Y.pathname:Y.pathname+"/",J=W.pathname.endsWith("/")?W.pathname:W.pathname+"/";return $.startsWith(J)}class E0 extends Error{constructor(Q,X){super(Q);this.errorUri=X,this.name=this.constructor.name}toResponseObject(){let Q={error:this.errorCode,error_description:this.message};if(this.errorUri)Q.error_uri=this.errorUri;return Q}get errorCode(){return this.constructor.errorCode}}class wY extends E0{}wY.errorCode="invalid_request";class A8 extends E0{}A8.errorCode="invalid_client";class q8 extends E0{}q8.errorCode="invalid_grant";class D8 extends E0{}D8.errorCode="unauthorized_client";class bY extends E0{}bY.errorCode="unsupported_grant_type";class PY extends E0{}PY.errorCode="invalid_scope";class ZY extends E0{}ZY.errorCode="access_denied";class y6 extends E0{}y6.errorCode="server_error";class RY extends E0{}RY.errorCode="temporarily_unavailable";class EY extends E0{}EY.errorCode="unsupported_response_type";class SY extends E0{}SY.errorCode="unsupported_token_type";class IY extends E0{}IY.errorCode="invalid_token";class TY extends E0{}TY.errorCode="method_not_allowed";class CY extends E0{}CY.errorCode="too_many_requests";class L8 extends E0{}L8.errorCode="invalid_client_metadata";class kY extends E0{}kY.errorCode="insufficient_scope";class vY extends E0{}vY.errorCode="invalid_target";var LO={[wY.errorCode]:wY,[A8.errorCode]:A8,[q8.errorCode]:q8,[D8.errorCode]:D8,[bY.errorCode]:bY,[PY.errorCode]:PY,[ZY.errorCode]:ZY,[y6.errorCode]:y6,[RY.errorCode]:RY,[EY.errorCode]:EY,[SY.errorCode]:SY,[IY.errorCode]:IY,[TY.errorCode]:TY,[CY.errorCode]:CY,[L8.errorCode]:L8,[kY.errorCode]:kY,[vY.errorCode]:vY};class f6 extends Error{constructor(Q){super(Q??"Unauthorized")}}function af(Q){return["client_secret_basic","client_secret_post","none"].includes(Q)}var hJ="code",uJ="S256";function sf(Q,X){let Y=Q.client_secret!==void 0;if(X.length===0)return Y?"client_secret_post":"none";if("token_endpoint_auth_method"in Q&&Q.token_endpoint_auth_method&&af(Q.token_endpoint_auth_method)&&X.includes(Q.token_endpoint_auth_method))return Q.token_endpoint_auth_method;if(Y&&X.includes("client_secret_basic"))return"client_secret_basic";if(Y&&X.includes("client_secret_post"))return"client_secret_post";if(X.includes("none"))return"none";return Y?"client_secret_post":"none"}function ef(Q,X,Y,W){let{client_id:$,client_secret:J}=X;switch(Q){case"client_secret_basic":Qg($,J,Y);return;case"client_secret_post":Xg($,J,W);return;case"none":Yg($,W);return;default:throw Error(`Unsupported client authentication method: ${Q}`)}}function Qg(Q,X,Y){if(!X)throw Error("client_secret_basic authentication requires a client_secret");let W=btoa(`${Q}:${X}`);Y.set("Authorization",`Basic ${W}`)}function Xg(Q,X,Y){if(Y.set("client_id",Q),X)Y.set("client_secret",X)}function Yg(Q,X){X.set("client_id",Q)}async function UO(Q){let X=Q instanceof Response?Q.status:void 0,Y=Q instanceof Response?await Q.text():Q;try{let W=FO.parse(JSON.parse(Y)),{error:$,error_description:J,error_uri:G}=W;return new(LO[$]||y6)(J||"",G)}catch(W){let $=`${X?`HTTP ${X}: `:""}Invalid OAuth error response: ${W}. Raw body: ${Y}`;return new y6($)}}async function r4(Q,X){try{return await lJ(Q,X)}catch(Y){if(Y instanceof A8||Y instanceof D8)return await Q.invalidateCredentials?.("all"),await lJ(Q,X);else if(Y instanceof q8)return await Q.invalidateCredentials?.("tokens"),await lJ(Q,X);throw Y}}async function lJ(Q,{serverUrl:X,authorizationCode:Y,scope:W,resourceMetadataUrl:$,fetchFn:J}){let G,H;try{if(G=await Jg(X,{resourceMetadataUrl:$},J),G.authorization_servers&&G.authorization_servers.length>0)H=G.authorization_servers[0]}catch{}if(!H)H=new URL("/",X);let B=await $g(X,Q,G),z=await Kg(H,{fetchFn:J}),K=await Promise.resolve(Q.clientInformation());if(!K){if(Y!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let L=z?.client_id_metadata_document_supported===!0,O=Q.clientMetadataUrl;if(O&&!Wg(O))throw new L8(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if(L&&O)K={client_id:O},await Q.saveClientInformation?.(K);else{if(!Q.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let w=await Dg(H,{metadata:z,clientMetadata:Q.clientMetadata,fetchFn:J});await Q.saveClientInformation(w),K=w}}let V=!Q.redirectUrl;if(Y!==void 0||V){let L=await qg(Q,H,{metadata:z,resource:B,authorizationCode:Y,fetchFn:J});return await Q.saveTokens(L),"AUTHORIZED"}let q=await Q.tokens();if(q?.refresh_token)try{let L=await Ag(H,{metadata:z,clientInformation:K,refreshToken:q.refresh_token,resource:B,addClientAuthentication:Q.addClientAuthentication,fetchFn:J});return await Q.saveTokens(L),"AUTHORIZED"}catch(L){if(!(L instanceof E0)||L instanceof y6);else throw L}let F=Q.state?await Q.state():void 0,{authorizationUrl:A,codeVerifier:D}=await Vg(H,{metadata:z,clientInformation:K,state:F,redirectUrl:Q.redirectUrl,scope:W||G?.scopes_supported?.join(" ")||Q.clientMetadata.scope,resource:B});return await Q.saveCodeVerifier(D),await Q.redirectToAuthorization(A),"REDIRECT"}function Wg(Q){if(!Q)return!1;try{let X=new URL(Q);return X.protocol==="https:"&&X.pathname!=="/"}catch{return!1}}async function $g(Q,X,Y){let W=qO(Q);if(X.validateResourceURL)return await X.validateResourceURL(W,Y?.resource);if(!Y)return;if(!DO({requestedResource:W,configuredResource:Y.resource}))throw Error(`Protected resource ${Y.resource} does not match expected ${W} (or origin)`);return new URL(Y.resource)}function cJ(Q){let X=Q.headers.get("WWW-Authenticate");if(!X)return{};let[Y,W]=X.split(" ");if(Y.toLowerCase()!=="bearer"||!W)return{};let $=mJ(Q,"resource_metadata")||void 0,J;if($)try{J=new URL($)}catch{}let G=mJ(Q,"scope")||void 0,H=mJ(Q,"error")||void 0;return{resourceMetadataUrl:J,scope:G,error:H}}function mJ(Q,X){let Y=Q.headers.get("WWW-Authenticate");if(!Y)return null;let W=new RegExp(`${X}=(?:"([^"]+)"|([^\\s,]+))`),$=Y.match(W);if($)return $[1]||$[2];return null}async function Jg(Q,X,Y=fetch){let W=await Bg(Q,"oauth-protected-resource",Y,{protocolVersion:X?.protocolVersion,metadataUrl:X?.resourceMetadataUrl});if(!W||W.status===404)throw await W?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!W.ok)throw await W.body?.cancel(),Error(`HTTP ${W.status} trying to load well-known OAuth protected resource metadata.`);return zO.parse(await W.json())}async function pJ(Q,X,Y=fetch){try{return await Y(Q,{headers:X})}catch(W){if(W instanceof TypeError)if(X)return pJ(Q,void 0,Y);else return;throw W}}function Gg(Q,X="",Y={}){if(X.endsWith("/"))X=X.slice(0,-1);return Y.prependPathname?`${X}/.well-known/${Q}`:`/.well-known/${Q}${X}`}async function OO(Q,X,Y=fetch){return await pJ(Q,{"MCP-Protocol-Version":X},Y)}function Hg(Q,X){return!Q||Q.status>=400&&Q.status<500&&X!=="/"}async function Bg(Q,X,Y,W){let $=new URL(Q),J=W?.protocolVersion??U6,G;if(W?.metadataUrl)G=new URL(W.metadataUrl);else{let B=Gg(X,$.pathname);G=new URL(B,W?.metadataServerUrl??$),G.search=$.search}let H=await OO(G,J,Y);if(!W?.metadataUrl&&Hg(H,$.pathname)){let B=new URL(`/.well-known/${X}`,$);H=await OO(B,J,Y)}return H}function zg(Q){let X=typeof Q==="string"?new URL(Q):Q,Y=X.pathname!=="/",W=[];if(!Y)return W.push({url:new URL("/.well-known/oauth-authorization-server",X.origin),type:"oauth"}),W.push({url:new URL("/.well-known/openid-configuration",X.origin),type:"oidc"}),W;let $=X.pathname;if($.endsWith("/"))$=$.slice(0,-1);return W.push({url:new URL(`/.well-known/oauth-authorization-server${$}`,X.origin),type:"oauth"}),W.push({url:new URL(`/.well-known/openid-configuration${$}`,X.origin),type:"oidc"}),W.push({url:new URL(`${$}/.well-known/openid-configuration`,X.origin),type:"oidc"}),W}async function Kg(Q,{fetchFn:X=fetch,protocolVersion:Y=U6}={}){let W={"MCP-Protocol-Version":Y,Accept:"application/json"},$=zg(Q);for(let{url:J,type:G}of $){let H=await pJ(J,W,X);if(!H)continue;if(!H.ok){if(await H.body?.cancel(),H.status>=400&&H.status<500)continue;throw Error(`HTTP ${H.status} trying to load ${G==="oauth"?"OAuth":"OpenID provider"} metadata from ${J}`)}if(G==="oauth")return gJ.parse(await H.json());else return KO.parse(await H.json())}return}async function Vg(Q,{metadata:X,clientInformation:Y,redirectUrl:W,scope:$,state:J,resource:G}){let H;if(X){if(H=new URL(X.authorization_endpoint),!X.response_types_supported.includes(hJ))throw Error(`Incompatible auth server: does not support response type ${hJ}`);if(X.code_challenge_methods_supported&&!X.code_challenge_methods_supported.includes(uJ))throw Error(`Incompatible auth server: does not support code challenge method ${uJ}`)}else H=new URL("/authorize",Q);let B=await fJ(),z=B.code_verifier,K=B.code_challenge;if(H.searchParams.set("response_type",hJ),H.searchParams.set("client_id",Y.client_id),H.searchParams.set("code_challenge",K),H.searchParams.set("code_challenge_method",uJ),H.searchParams.set("redirect_uri",String(W)),J)H.searchParams.set("state",J);if($)H.searchParams.set("scope",$);if($?.includes("offline_access"))H.searchParams.append("prompt","consent");if(G)H.searchParams.set("resource",G.href);return{authorizationUrl:H,codeVerifier:z}}function Fg(Q,X,Y){return new URLSearchParams({grant_type:"authorization_code",code:Q,code_verifier:X,redirect_uri:String(Y)})}async function jO(Q,{metadata:X,tokenRequestParams:Y,clientInformation:W,addClientAuthentication:$,resource:J,fetchFn:G}){let H=X?.token_endpoint?new URL(X.token_endpoint):new URL("/token",Q),B=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(J)Y.set("resource",J.href);if($)await $(B,Y,H,X);else if(W){let K=X?.token_endpoint_auth_methods_supported??[],V=sf(W,K);ef(V,W,B,Y)}let z=await(G??fetch)(H,{method:"POST",headers:B,body:Y});if(!z.ok)throw await UO(z);return VO.parse(await z.json())}async function Ag(Q,{metadata:X,clientInformation:Y,refreshToken:W,resource:$,addClientAuthentication:J,fetchFn:G}){let H=new URLSearchParams({grant_type:"refresh_token",refresh_token:W}),B=await jO(Q,{metadata:X,tokenRequestParams:H,clientInformation:Y,addClientAuthentication:J,resource:$,fetchFn:G});return{refresh_token:W,...B}}async function qg(Q,X,{metadata:Y,resource:W,authorizationCode:$,fetchFn:J}={}){let G=Q.clientMetadata.scope,H;if(Q.prepareTokenRequest)H=await Q.prepareTokenRequest(G);if(!H){if(!$)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!Q.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let z=await Q.codeVerifier();H=Fg($,z,Q.redirectUrl)}let B=await Q.clientInformation();return jO(X,{metadata:Y,tokenRequestParams:H,clientInformation:B??void 0,addClientAuthentication:Q.addClientAuthentication,resource:W,fetchFn:J})}async function Dg(Q,{metadata:X,clientMetadata:Y,fetchFn:W}){let $;if(X){if(!X.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");$=new URL(X.registration_endpoint)}else $=new URL("/register",Q);let J=await(W??fetch)($,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!J.ok)throw await UO(J);return AO.parse(await J.json())}class iJ extends Error{constructor(Q,X){super(Q),this.name="ParseError",this.type=X.type,this.field=X.field,this.value=X.value,this.line=X.line}}function dJ(Q){}function MO(Q){if(typeof Q=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:X=dJ,onError:Y=dJ,onRetry:W=dJ,onComment:$}=Q,J="",G=!0,H,B="",z="";function K(D){let L=G?D.replace(/^\xEF\xBB\xBF/,""):D,[O,N]=Lg(`${J}${L}`);for(let w of O)V(w);J=N,G=!1}function V(D){if(D===""){F();return}if(D.startsWith(":")){$&&$(D.slice(D.startsWith(": ")?2:1));return}let L=D.indexOf(":");if(L!==-1){let O=D.slice(0,L),N=D[L+1]===" "?2:1,w=D.slice(L+N);q(O,w,D);return}q(D,"",D)}function q(D,L,O){switch(D){case"event":z=L;break;case"data":B=`${B}${L}
50
50
  `;break;case"id":H=L.includes("\x00")?void 0:L;break;case"retry":/^\d+$/.test(L)?W(parseInt(L,10)):Y(new iJ(`Invalid \`retry\` value: "${L}"`,{type:"invalid-retry",value:L,line:O}));break;default:Y(new iJ(`Unknown field "${D.length>20?`${D.slice(0,20)}…`:D}"`,{type:"unknown-field",field:D,value:L,line:O}));break}}function F(){B.length>0&&X({id:H,event:z||void 0,data:B.endsWith(`
51
51
  `)?B.slice(0,-1):B}),H=void 0,B="",z=""}function A(D={}){J&&D.consume&&V(J),G=!0,H=void 0,B="",z="",J=""}return{feed:K,reset:A}}function Lg(Q){let X=[],Y="",W=0;for(;W<Q.length;){let $=Q.indexOf("\r",W),J=Q.indexOf(`
52
52
  `,W),G=-1;if($!==-1&&J!==-1?G=Math.min($,J):$!==-1?$===Q.length-1?G=-1:G=$:J!==-1&&(G=J),G===-1){Y=Q.slice(W);break}else{let H=Q.slice(W,G);X.push(H),W=G+1,Q[W-1]==="\r"&&Q[W]===`
53
- `&&W++}}return[X,Y]}class nJ extends TransformStream{constructor({onError:Q,onRetry:X,onComment:Y}={}){let W;super({start($){W=MO({onEvent:(J)=>{$.enqueue(J)},onError(J){Q==="terminate"?$.error(J):typeof Q=="function"&&Q(J)},onRetry:X,onComment:Y})},transform($){W.feed($)}})}}var Og={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class L9 extends Error{constructor(Q,X){super(`Streamable HTTP error: ${X}`);this.code=Q}}class _Y{constructor(Q,X){this._hasCompletedAuthFlow=!1,this._url=Q,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=HO(X?.fetch,X?.requestInit),this._sessionId=X?.sessionId,this._reconnectionOptions=X?.reconnectionOptions??Og}async _authThenStart(){if(!this._authProvider)throw new f6("No auth provider");let Q;try{Q=await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Q!=="AUTHORIZED")throw new f6;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let Q={};if(this._authProvider){let Y=await this._authProvider.tokens();if(Y)Q.Authorization=`Bearer ${Y.access_token}`}if(this._sessionId)Q["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let X=NY(this._requestInit?.headers);return new Headers({...Q,...X})}async _startOrAuthSse(Q){let{resumptionToken:X}=Q;try{let Y=await this._commonHeaders();if(Y.set("Accept","text/event-stream"),X)Y.set("last-event-id",X);let W=await(this._fetch??fetch)(this._url,{method:"GET",headers:Y,signal:this._abortController?.signal});if(!W.ok){if(await W.body?.cancel(),W.status===401&&this._authProvider)return await this._authThenStart();if(W.status===405)return;throw new L9(W.status,`Failed to open SSE stream: ${W.statusText}`)}this._handleSseStream(W.body,Q,!0)}catch(Y){throw this.onerror?.(Y),Y}}_getNextReconnectionDelay(Q){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let X=this._reconnectionOptions.initialReconnectionDelay,Y=this._reconnectionOptions.reconnectionDelayGrowFactor,W=this._reconnectionOptions.maxReconnectionDelay;return Math.min(X*Math.pow(Y,Q),W)}_scheduleReconnection(Q,X=0){let Y=this._reconnectionOptions.maxRetries;if(X>=Y){this.onerror?.(Error(`Maximum reconnection attempts (${Y}) exceeded.`));return}let W=this._getNextReconnectionDelay(X);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(Q).catch(($)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${$ instanceof Error?$.message:String($)}`)),this._scheduleReconnection(Q,X+1)})},W)}_handleSseStream(Q,X,Y){if(!Q)return;let{onresumptiontoken:W,replayMessageId:$}=X,J,G=!1,H=!1;(async()=>{try{let z=Q.pipeThrough(new TextDecoderStream).pipeThrough(new nJ({onRetry:(q)=>{this._serverRetryMs=q}})).getReader();while(!0){let{value:q,done:F}=await z.read();if(F)break;if(q.id)J=q.id,G=!0,W?.(q.id);if(!q.data)continue;if(!q.event||q.event==="message")try{let A=u9.parse(JSON.parse(q.data));if(a6(A)){if(H=!0,$!==void 0)A.id=$}this.onmessage?.(A)}catch(A){this.onerror?.(A)}}if((Y||G)&&!H&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:J,onresumptiontoken:W,replayMessageId:$},0)}catch(z){if(this.onerror?.(Error(`SSE stream disconnected: ${z}`)),(Y||G)&&!H&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:J,onresumptiontoken:W,replayMessageId:$},0)}catch(q){this.onerror?.(Error(`Failed to reconnect: ${q instanceof Error?q.message:String(q)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(Q){if(!this._authProvider)throw new f6("No auth provider");if(await r4(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new f6("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(Q,X){try{let{resumptionToken:Y,onresumptiontoken:W}=X||{};if(Y){this._startOrAuthSse({resumptionToken:Y,replayMessageId:m8(Q)?Q.id:void 0}).catch((V)=>this.onerror?.(V));return}let $=await this._commonHeaders();$.set("content-type","application/json"),$.set("accept","application/json, text/event-stream");let J={...this._requestInit,method:"POST",headers:$,body:JSON.stringify(Q),signal:this._abortController?.signal},G=await(this._fetch??fetch)(this._url,J),H=G.headers.get("mcp-session-id");if(H)this._sessionId=H;if(!G.ok){let V=await G.text().catch(()=>null);if(G.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new L9(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:q,scope:F}=cJ(G);if(this._resourceMetadataUrl=q,this._scope=F,await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new f6;return this._hasCompletedAuthFlow=!0,this.send(Q)}if(G.status===403&&this._authProvider){let{resourceMetadataUrl:q,scope:F,error:A}=cJ(G);if(A==="insufficient_scope"){let D=G.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===D)throw new L9(403,"Server returned 403 after trying upscoping");if(F)this._scope=F;if(q)this._resourceMetadataUrl=q;if(this._lastUpscopingHeader=D??void 0,await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new f6;return this.send(Q)}}throw new L9(G.status,`Error POSTing to endpoint: ${V}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,G.status===202){if(await G.body?.cancel(),E3(Q))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>this.onerror?.(V));return}let z=(Array.isArray(Q)?Q:[Q]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,K=G.headers.get("content-type");if(z)if(K?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:W},!1);else if(K?.includes("application/json")){let V=await G.json(),q=Array.isArray(V)?V.map((F)=>u9.parse(F)):[u9.parse(V)];for(let F of q)this.onmessage?.(F)}else throw await G.body?.cancel(),new L9(-1,`Unexpected content type: ${K}`);else await G.body?.cancel()}catch(Y){throw this.onerror?.(Y),Y}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let Q=await this._commonHeaders(),X={...this._requestInit,method:"DELETE",headers:Q,signal:this._abortController?.signal},Y=await(this._fetch??fetch)(this._url,X);if(await Y.body?.cancel(),!Y.ok&&Y.status!==405)throw new L9(Y.status,`Failed to terminate session: ${Y.statusText}`);this._sessionId=void 0}catch(Q){throw this.onerror?.(Q),Q}}setProtocolVersion(Q){this._protocolVersion=Q}get protocolVersion(){return this._protocolVersion}async resumeStream(Q,X){await this._startOrAuthSse({resumptionToken:Q,onresumptiontoken:X?.onresumptiontoken})}}var Ug=1000,jg=180000,Mg=2,Ng=0.1,NO=120000,wg=0.1,bg=60000,Pg=3;class oJ{name;url;onStatusChange;onNotification;onLog;onSamplingRequest;onElicitationRequest;onReconnecting;onReconnected;onHealthDegraded;onHealthRestored;client=null;transport=null;status="disconnected";errorMessage;capabilities;isClosing=!1;reconnectAttempt=0;reconnectTimeoutHandle=null;nextRetryMs=0;isReconnecting=!1;healthCheckIntervalHandle=null;consecutiveHealthFailures=0;healthStatus="healthy";constructor(Q){this.name=Q.name,this.url=Q.url,this.onStatusChange=Q.onStatusChange,this.onNotification=Q.onNotification,this.onLog=Q.onLog,this.onSamplingRequest=Q.onSamplingRequest,this.onElicitationRequest=Q.onElicitationRequest,this.onReconnecting=Q.onReconnecting,this.onReconnected=Q.onReconnected,this.onHealthDegraded=Q.onHealthDegraded,this.onHealthRestored=Q.onHealthRestored}getTransportType(){return"http"}getUrl(){return this.url}getInfo(){let Q={name:this.name,url:this.url,status:this.status};if(this.errorMessage!==void 0)Q.error=this.errorMessage;if(this.capabilities!==void 0)Q.capabilities=this.capabilities;return Q}getName(){return this.name}getStatus(){return this.status}isConnected(){return this.status==="connected"}getReconnectionState(){if(this.status!=="reconnecting")return null;return{attempt:this.reconnectAttempt,nextRetryMs:this.nextRetryMs}}getHealthStatus(){return this.healthStatus}getConsecutiveHealthFailures(){return this.consecutiveHealthFailures}async connect(){if(this.status==="connected"||this.status==="connecting")return;this.setStatus("connecting");try{this.transport=new _Y(new URL(this.url)),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleUnexpectedDisconnect()},this.transport.onerror=(X)=>{if((X.name==="AbortError"||X.message.includes("AbortError"))&&(this.isClosing||this.status==="disconnected"))return;this.errorMessage=X.message,this.handleUnexpectedDisconnect()},await this.client.connect(this.transport);let Q=this.client.getServerCapabilities();this.capabilities={tools:Q?.tools!==void 0,resources:Q?.resources!==void 0,prompts:Q?.prompts!==void 0,resourceTemplates:Q?.resources!==void 0,resourceSubscriptions:Q?.resources?.subscribe===!0},this.setStatus("connected"),this.startHealthChecks()}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw this.setStatus("error",X),Q}}async disconnect(){if(this.isClosing=!0,this.stopHealthChecks(),this.cancelReconnection(),this.transport)try{await this.transport.close()}catch{}this.client=null,this.transport=null,this.isClosing=!1,this.setStatus("disconnected")}async forceReconnect(){if(this.stopHealthChecks(),this.cancelReconnection(),this.transport){this.isClosing=!0;try{await this.transport.close()}catch{}this.isClosing=!1}this.client=null,this.transport=null,this.reconnectAttempt=0,this.nextRetryMs=0,this.consecutiveHealthFailures=0,this.healthStatus="healthy",await this.connect()}cancelReconnection(){if(this.reconnectTimeoutHandle)clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=null;this.isReconnecting=!1}async listTools(){let Q=this.getConnectedClient();if(!this.capabilities?.tools)return[];return(await Q.listTools()).tools}async callTool(Q,X={}){return await this.getConnectedClient().callTool({name:Q,arguments:X})}async listResources(){let Q=this.getConnectedClient();if(!this.capabilities?.resources)return[];return(await Q.listResources()).resources}async listResourceTemplates(){let Q=this.getConnectedClient();if(!this.capabilities?.resourceTemplates)return[];return(await Q.listResourceTemplates()).resourceTemplates}async readResource(Q){return await this.getConnectedClient().readResource({uri:Q})}async subscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.subscribeResource({uri:Q})}async unsubscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.unsubscribeResource({uri:Q})}supportsResourceSubscriptions(){return this.capabilities?.resourceSubscriptions===!0}async listPrompts(){let Q=this.getConnectedClient();if(!this.capabilities?.prompts)return[];return(await Q.listPrompts()).prompts}async getPrompt(Q,X={}){return await this.getConnectedClient().getPrompt({name:Q,arguments:X})}setupNotificationHandler(){if(!this.client)return;this.client.setNotificationHandler(Q9,()=>{this.emitNotification("notifications/tools/list_changed")}),this.client.setNotificationHandler(s6,()=>{this.emitNotification("notifications/resources/list_changed")}),this.client.setNotificationHandler(r8,(Q)=>{this.emitNotification("notifications/resources/updated",Q.params)}),this.client.setNotificationHandler(e6,()=>{this.emitNotification("notifications/prompts/list_changed")}),this.client.setNotificationHandler(a8,(Q)=>{if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:Q.params.level,logger:Q.params.logger,data:Q.params.data})}),this.client.setRequestHandler(X9,(Q)=>{return new Promise((X,Y)=>{if(this.onSamplingRequest)this.onSamplingRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Sampling not supported: no handler registered"))})}),this.client.setRequestHandler(Y9,(Q)=>{return new Promise((X,Y)=>{if(this.onElicitationRequest)this.onElicitationRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Elicitation not supported: no handler registered"))})})}emitNotification(Q,X){if(this.onNotification!==void 0)this.onNotification({server:this.name,timestamp:new Date,method:Q,params:X})}handleUnexpectedDisconnect(){if(this.isReconnecting||this.isClosing)return;this.stopHealthChecks(),this.client=null,this.transport=null,this.isReconnecting=!0,this.reconnectAttempt=0,this.setStatus("reconnecting",this.errorMessage),this.scheduleReconnection()}scheduleReconnection(){if(this.isClosing)return;this.reconnectAttempt++;let Q=this.calculateBackoff(this.reconnectAttempt);if(this.nextRetryMs=Q,this.onReconnecting)this.onReconnecting(this.reconnectAttempt,Q);this.reconnectTimeoutHandle=setTimeout(()=>{this.attemptReconnection()},Q)}async attemptReconnection(){if(this.isClosing)return;try{this.transport=new _Y(new URL(this.url)),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleUnexpectedDisconnect()},this.transport.onerror=(Y)=>{if((Y.name==="AbortError"||Y.message.includes("AbortError"))&&(this.isClosing||this.status==="disconnected"))return;this.errorMessage=Y.message,this.handleUnexpectedDisconnect()},await this.client.connect(this.transport);let Q=this.client.getServerCapabilities();this.capabilities={tools:Q?.tools!==void 0,resources:Q?.resources!==void 0,prompts:Q?.prompts!==void 0,resourceTemplates:Q?.resources!==void 0,resourceSubscriptions:Q?.resources?.subscribe===!0};let X=this.reconnectAttempt;if(this.reconnectAttempt=0,this.nextRetryMs=0,this.isReconnecting=!1,this.consecutiveHealthFailures=0,this.healthStatus="healthy",this.setStatus("connected"),this.onReconnected)this.onReconnected(X);this.startHealthChecks()}catch(Q){this.client=null,this.transport=null,this.errorMessage=Q instanceof Error?Q.message:String(Q),this.scheduleReconnection()}}calculateBackoff(Q){let X=Ug*Math.pow(Mg,Q-1),Y=Math.min(X,jg),W=Y*Ng*(Math.random()*2-1);return Math.round(Y+W)}startHealthChecks(){this.stopHealthChecks();let Q=()=>{let X=NO*wg*(Math.random()*2-1),Y=Math.round(NO+X);this.healthCheckIntervalHandle=setTimeout(()=>{this.performHealthCheck(),Q()},Y)};Q()}stopHealthChecks(){if(this.healthCheckIntervalHandle)clearTimeout(this.healthCheckIntervalHandle),this.healthCheckIntervalHandle=null}async performHealthCheck(){if(!this.client||!this.isConnected())return;try{let Q=new AbortController,X=setTimeout(()=>{Q.abort()},bg);try{if(await this.client.listTools(),clearTimeout(X),this.consecutiveHealthFailures>0){let Y=this.healthStatus==="degraded";if(this.consecutiveHealthFailures=0,this.healthStatus="healthy",Y&&this.onHealthRestored)this.onHealthRestored()}}catch(Y){throw clearTimeout(X),Y}}catch(Q){this.consecutiveHealthFailures++;let X=Q instanceof Error?Q.message:String(Q);if(this.consecutiveHealthFailures>=Pg&&this.healthStatus!=="degraded"){if(this.healthStatus="degraded",this.onHealthDegraded)this.onHealthDegraded(this.consecutiveHealthFailures,X)}}}setStatus(Q,X){if(this.status=Q,Q==="error"&&X!==void 0)this.errorMessage=X;else this.errorMessage=void 0;if(this.onStatusChange!==void 0)this.onStatusChange(Q,X)}getConnectedClient(){if(!this.isConnected()||!this.client)throw Error(`Client '${this.name}' is not connected`);return this.client}}var KU=O9(zU(),1);import yY from"node:process";import{PassThrough as Qh}from"node:stream";var Xh=yY.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Yh(){let Q={};for(let X of Xh){let Y=yY.env[X];if(Y===void 0)continue;if(Y.startsWith("()"))continue;Q[X]=Y}return Q}class $G{constructor(Q){if(this._readBuffer=new o4,this._stderrStream=null,this._serverParams=Q,Q.stderr==="pipe"||Q.stderr==="overlapped")this._stderrStream=new Qh}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,X)=>{if(this._process=KU.default(this._serverParams.command,this._serverParams.args??[],{env:{...Yh(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:yY.platform==="win32"&&Wh(),cwd:this._serverParams.cwd}),this._process.on("error",(Y)=>{X(Y),this.onerror?.(Y)}),this._process.on("spawn",()=>{Q()}),this._process.on("close",(Y)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(Y)=>{this.onerror?.(Y)}),this._process.stdout?.on("data",(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()}),this._process.stdout?.on("error",(Y)=>{this.onerror?.(Y)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._process){let Q=this._process;this._process=void 0;let X=new Promise((Y)=>{Q.once("close",()=>{Y()})});try{Q.stdin?.end()}catch{}if(await Promise.race([X,new Promise((Y)=>setTimeout(Y,2000).unref())]),Q.exitCode===null){try{Q.kill("SIGTERM")}catch{}await Promise.race([X,new Promise((Y)=>setTimeout(Y,2000).unref())])}if(Q.exitCode===null)try{Q.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(Q){return new Promise((X)=>{if(!this._process?.stdin)throw Error("Not connected");let Y=OY(Q);if(this._process.stdin.write(Y))X();else this._process.stdin.once("drain",X)})}}function Wh(){return"type"in yY}var $h={enabled:!0,maxAttempts:5,baseDelayMs:1000,maxDelayMs:60000,backoffMultiplier:2};class JG{name;command;args;env;cwd;restartConfig;onStatusChange;onNotification;onLog;onSamplingRequest;onElicitationRequest;onLifecycleEvent;client=null;transport=null;status="disconnected";errorMessage;capabilities;isClosing=!1;restartAttempt=0;restartTimeoutHandle=null;nextRetryMs=0;isRestarting=!1;stderrBuffer=[];maxStderrLines=1000;constructor(Q){this.name=Q.name,this.command=Q.command,this.args=Q.args??[],this.env=Q.env,this.cwd=Q.cwd,this.restartConfig={...$h,...Q.restartConfig},this.onStatusChange=Q.onStatusChange,this.onNotification=Q.onNotification,this.onLog=Q.onLog,this.onSamplingRequest=Q.onSamplingRequest,this.onElicitationRequest=Q.onElicitationRequest,this.onLifecycleEvent=Q.onLifecycleEvent}getTransportType(){return"stdio"}getInfo(){let Q={transportType:"stdio",name:this.name,url:`stdio://${this.command}`,status:this.status},X=this.transport._process;if(X?.pid!==void 0)Q.pid=X.pid;if(this.errorMessage!==void 0)Q.error=this.errorMessage;if(this.capabilities!==void 0)Q.capabilities=this.capabilities;return Q}getName(){return this.name}getStatus(){return this.status}isConnected(){return this.status==="connected"}getReconnectionState(){if(this.status!=="reconnecting")return null;return{attempt:this.restartAttempt,nextRetryMs:this.nextRetryMs}}getHealthStatus(){return this.isConnected()?"healthy":"degraded"}getConsecutiveHealthFailures(){return this.isConnected()?0:this.restartAttempt}getCommand(){return this.command}getArgs(){return[...this.args]}getStderrBuffer(){return[...this.stderrBuffer]}async connect(){if(this.status==="connected"||this.status==="connecting")return;this.setStatus("connecting");try{await this.createTransport(),this.emitLifecycleEvent({event:"process_started",timestamp:new Date}),this.setStatus("connected")}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw this.setStatus("error",X),Q}}async disconnect(){if(this.isClosing=!0,this.cancelReconnection(),this.transport)try{await this.transport.close()}catch{}this.client=null,this.transport=null,this.isClosing=!1,this.setStatus("disconnected"),this.emitLifecycleEvent({event:"process_stopped",timestamp:new Date})}async forceReconnect(){if(this.cancelReconnection(),this.transport){this.isClosing=!0;try{await this.transport.close()}catch{}this.isClosing=!1}this.client=null,this.transport=null,this.restartAttempt=0,this.nextRetryMs=0,await this.connect()}cancelReconnection(){if(this.restartTimeoutHandle)clearTimeout(this.restartTimeoutHandle),this.restartTimeoutHandle=null;this.isRestarting=!1}async listTools(){let Q=this.getConnectedClient();if(!this.capabilities?.tools)return[];return(await Q.listTools()).tools}async callTool(Q,X={}){return await this.getConnectedClient().callTool({name:Q,arguments:X})}async listResources(){let Q=this.getConnectedClient();if(!this.capabilities?.resources)return[];return(await Q.listResources()).resources}async listResourceTemplates(){let Q=this.getConnectedClient();if(!this.capabilities?.resourceTemplates)return[];return(await Q.listResourceTemplates()).resourceTemplates}async readResource(Q){return await this.getConnectedClient().readResource({uri:Q})}async subscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.subscribeResource({uri:Q})}async unsubscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.unsubscribeResource({uri:Q})}supportsResourceSubscriptions(){return this.capabilities?.resourceSubscriptions===!0}async listPrompts(){let Q=this.getConnectedClient();if(!this.capabilities?.prompts)return[];return(await Q.listPrompts()).prompts}async getPrompt(Q,X={}){return await this.getConnectedClient().getPrompt({name:Q,arguments:X})}async createTransport(){let Q;if(this.env){Q={};for(let[Y,W]of Object.entries(process.env))if(W!==void 0)Q[Y]=W;Object.assign(Q,this.env)}this.transport=new $G({command:this.command,args:this.args,env:Q,cwd:this.cwd,stderr:"pipe"}),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleProcessExit()},this.transport.onerror=(Y)=>{if(this.isClosing||this.status==="disconnected")return;this.errorMessage=Y.message,this.handleProcessExit()},await this.client.connect(this.transport),this.setupStderrCapture();let X=this.client.getServerCapabilities();this.capabilities={tools:X?.tools!==void 0,resources:X?.resources!==void 0,prompts:X?.prompts!==void 0,resourceTemplates:X?.resources!==void 0,resourceSubscriptions:X?.resources?.subscribe===!0}}setupStderrCapture(){if(!this.transport)return;let Q=this.transport._process;if(Q?.stderr)Q.stderr.on("data",(X)=>{let Y=X.toString().split(`
54
- `).filter((W)=>W.length>0);for(let W of Y){if(this.stderrBuffer.push(W),this.stderrBuffer.length>this.maxStderrLines)this.stderrBuffer.shift();if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:"warning",source:"stderr",data:W})}})}handleProcessExit(Q,X){if(this.isRestarting||this.isClosing)return;if(this.emitLifecycleEvent({event:"process_crashed",timestamp:new Date,exitCode:Q,signal:X}),this.client=null,this.transport=null,this.restartConfig.enabled)this.isRestarting=!0,this.restartAttempt=0,this.setStatus("reconnecting",this.errorMessage),this.scheduleRestart();else this.setStatus("error",`Process exited with code ${Q!==void 0?String(Q):"unknown"}`)}scheduleRestart(){if(this.isClosing)return;if(this.restartAttempt++,this.restartAttempt>this.restartConfig.maxAttempts){this.isRestarting=!1,this.setStatus("error","Max restart attempts exceeded"),this.emitLifecycleEvent({event:"restart_failed",timestamp:new Date,attempt:this.restartAttempt-1,error:"Max restart attempts exceeded"});return}let Q=this.calculateBackoff(this.restartAttempt);this.nextRetryMs=Q,this.emitLifecycleEvent({event:"restarting",timestamp:new Date,attempt:this.restartAttempt,nextRetryMs:Q}),this.restartTimeoutHandle=setTimeout(()=>{this.attemptRestart()},Q)}async attemptRestart(){if(this.isClosing)return;try{await this.createTransport();let Q=this.restartAttempt;this.restartAttempt=0,this.nextRetryMs=0,this.isRestarting=!1,this.setStatus("connected"),this.emitLifecycleEvent({event:"restarted",timestamp:new Date,attempt:Q})}catch(Q){this.client=null,this.transport=null,this.errorMessage=Q instanceof Error?Q.message:String(Q),this.scheduleRestart()}}calculateBackoff(Q){let X=this.restartConfig.baseDelayMs*Math.pow(this.restartConfig.backoffMultiplier,Q-1);return Math.min(X,this.restartConfig.maxDelayMs)}setupNotificationHandler(){if(!this.client)return;this.client.setNotificationHandler(Q9,()=>{this.emitNotification("notifications/tools/list_changed")}),this.client.setNotificationHandler(s6,()=>{this.emitNotification("notifications/resources/list_changed")}),this.client.setNotificationHandler(r8,(Q)=>{this.emitNotification("notifications/resources/updated",Q.params)}),this.client.setNotificationHandler(e6,()=>{this.emitNotification("notifications/prompts/list_changed")}),this.client.setNotificationHandler(a8,(Q)=>{if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:Q.params.level,logger:Q.params.logger,data:Q.params.data,source:"protocol"})}),this.client.setRequestHandler(X9,(Q)=>{return new Promise((X,Y)=>{if(this.onSamplingRequest)this.onSamplingRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Sampling not supported: no handler registered"))})}),this.client.setRequestHandler(Y9,(Q)=>{return new Promise((X,Y)=>{if(this.onElicitationRequest)this.onElicitationRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Elicitation not supported: no handler registered"))})})}emitNotification(Q,X){if(this.onNotification!==void 0)this.onNotification({server:this.name,timestamp:new Date,method:Q,params:X})}emitLifecycleEvent(Q){if(this.onLifecycleEvent)this.onLifecycleEvent(Q)}setStatus(Q,X){if(this.status=Q,Q==="error"&&X!==void 0)this.errorMessage=X;else this.errorMessage=void 0;if(this.onStatusChange!==void 0)this.onStatusChange(Q,X)}getConnectedClient(){if(!this.isConnected()||!this.client)throw Error(`Client '${this.name}' is not connected`);return this.client}}var Jh={sessionTimeoutMs:86400000,cleanupIntervalMs:300000};class GG{sessions=new Map;serverConfigs;config;logger;cleanupIntervalHandle=null;constructor(Q={}){this.config={...Jh,...Q},this.logger=Q.logger;let X={logger:Q.logger};this.serverConfigs=new SJ(X),this.startCleanupInterval()}async createSession(){let Q=f1(),X=new _J(Q,this.config.sessionStateConfig,this.logger);this.sessions.set(Q,X),this.logger?.info("session_created",{sessionId:Q});let Y=this.serverConfigs.listConfigs();for(let W of Y)try{await this.connectSessionToServer(X,W)}catch($){this.logger?.warn("session_auto_connect_failed",{sessionId:Q,server:W.name,error:$ instanceof Error?$.message:String($)})}return X}getSession(Q){return this.sessions.get(Q)}touchSession(Q){this.sessions.get(Q)?.touch()}async destroySession(Q){let X=this.sessions.get(Q);if(!X)return;this.logger?.info("session_destroying",{sessionId:Q}),await X.cleanup(),this.sessions.delete(Q),this.logger?.info("session_destroyed",{sessionId:Q})}async addServer(Q,X,Y){let W=this.sessions.get(Q);if(!W)throw Error(`Session '${Q}' not found`);let $=this.serverConfigs.addConfig(X,Y,Q),J=this.serverConfigs.getConfig(X);if(!J)throw Error(`Failed to add server config for '${X}'`);let G=await this.connectSessionToServer(W,J);if($){for(let[H,B]of this.sessions)if(H!==Q)B.eventSystem.addEvent("server_added",X,{name:X,url:Y,addedBy:Q})}return G}async addStdioServer(Q,X,Y,W,$){let J=this.sessions.get(Q);if(!J)throw Error(`Session '${Q}' not found`);let G=this.serverConfigs.addStdioConfig(X,Y,W,$,Q),H=this.serverConfigs.getConfig(X);if(!H)throw Error(`Failed to add server config for '${X}'`);let B=await this.connectSessionToServer(J,H);if(G){for(let[z,K]of this.sessions)if(z!==Q)K.eventSystem.addEvent("server_added",X,{name:X,type:"stdio",command:Y,args:W,addedBy:Q})}return B}async removeServer(Q,X){if(this.logger?.debug("removeServer_start",{sessionId:Q,serverName:X}),!this.serverConfigs.removeConfig(X))throw this.logger?.debug("removeServer_not_found",{sessionId:Q,serverName:X}),Error(`Server '${X}' not found`);for(let[W,$]of this.sessions)this.logger?.debug("removeServer_disconnecting_session",{sessionId:W,serverName:X,hasConnection:$.getConnection(X)!==void 0}),await this.disconnectSessionFromServer($,X),$.eventSystem.addEvent("server_removed",X,{name:X,removedBy:Q});this.logger?.debug("removeServer_complete",{sessionId:Q,serverName:X})}listServers(Q){let X=this.sessions.get(Q);return this.serverConfigs.listConfigs().map((W)=>{let $=X?.getConnection(W.name),J;if(RJ(W))J=W.url;else if(EJ(W))J=`stdio://${W.command}`;else J="unknown";let G={name:W.name,url:J,connected:$?.status==="connected",status:$?.status??"not_connected",connectedAt:$?.connectedAt,lastError:$?.lastError};if($?.status==="reconnecting"){let H=$.client.getReconnectionState();if(H)G.reconnectAttempt=H.attempt,G.nextRetryMs=H.nextRetryMs}if($?.status==="connected"){G.healthStatus=$.client.getHealthStatus();let H=$.client.getConsecutiveHealthFailures();if(H>0)G.consecutiveHealthFailures=H}return G})}async reconnectServer(Q,X){let Y=this.sessions.get(Q);if(!Y)throw Error(`Session '${Q}' not found`);let W=this.serverConfigs.getConfig(X);if(!W)throw Error(`Server '${X}' not found`);let $=Y.getConnection(X);if(!$){await this.connectSessionToServer(Y,W);return}this.handleBackendDisconnect(Y,X),await $.client.forceReconnect(),Y.setConnectionStatus(X,"connected"),Y.eventSystem.addEvent("server_reconnected",X,{name:X,attemptsTaken:0,forced:!0}),this.logger?.info("session_server_force_reconnected",{sessionId:Y.sessionId,server:X})}async getOrCreateConnection(Q,X){let Y=this.sessions.get(Q);if(!Y)throw Error(`Session '${Q}' not found`);let W=Y.getConnection(X);if(W?.status==="connected")return W.client;let $=this.serverConfigs.getConfig(X);if(!$)throw Error(`Server '${X}' not found`);return(await this.connectSessionToServer(Y,$)).client}getConnectedClient(Q,X){let Y=this.sessions.get(Q);if(!Y)return;let W=Y.getConnection(X);if(W?.status==="connected")return W.client;return}async connectSessionToServer(Q,X){let Y=Q.backendConnections.get(X.name);if(Y?.status==="connected")return Y;if(Y?.status==="connecting")throw Error(`Already connecting to '${X.name}'`);let W;if(RJ(X))W=this.createHttpClient(Q,X);else if(EJ(X))W=this.createStdioClient(Q,X);else throw Error(`Unknown server config type for '${X.name}'`);Q.addConnection(X.name,W);try{await W.connect(),Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_connected",X.name,{name:X.name,capabilities:W.getInfo().capabilities}),this.logger?.info("session_server_connected",{sessionId:Q.sessionId,server:X.name});let $=Q.getConnection(X.name);if(!$)throw Error("Connection not found after connect");return $}catch($){let J=$ instanceof Error?$.message:String($);throw Q.setConnectionStatus(X.name,"error",J),this.logger?.warn("session_server_connect_failed",{sessionId:Q.sessionId,server:X.name,error:J}),$}}createHttpClient(Q,X){return new oJ({name:X.name,url:X.url,onStatusChange:(Y,W)=>{Q.setConnectionStatus(X.name,Y,W)},onNotification:(Y)=>{Q.bufferManager.addNotification(Y)},onLog:(Y)=>{Q.bufferManager.addLog(Y)},onSamplingRequest:(Y)=>{Q.pendingRequests.addSamplingRequest(Y.server,Y.params,Y.resolve,Y.reject)},onElicitationRequest:(Y)=>{Q.pendingRequests.addElicitationRequest(Y.server,Y.params,Y.resolve,Y.reject)},onReconnecting:(Y,W)=>{if(Y===1)this.handleBackendDisconnect(Q,X.name);Q.eventSystem.addEvent("server_reconnecting",X.name,{name:X.name,attempt:Y,nextRetryMs:W}),this.logger?.debug("session_server_reconnecting",{sessionId:Q.sessionId,server:X.name,attempt:Y,nextRetryMs:W})},onReconnected:(Y)=>{Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_reconnected",X.name,{name:X.name,attemptsTaken:Y}),this.logger?.info("session_server_reconnected",{sessionId:Q.sessionId,server:X.name,attemptsTaken:Y})},onHealthDegraded:(Y,W)=>{Q.eventSystem.addEvent("server_health_degraded",X.name,{name:X.name,consecutiveFailures:Y,lastError:W}),this.logger?.warn("session_server_health_degraded",{sessionId:Q.sessionId,server:X.name,consecutiveFailures:Y,lastError:W})},onHealthRestored:()=>{Q.eventSystem.addEvent("server_health_restored",X.name,{name:X.name}),this.logger?.info("session_server_health_restored",{sessionId:Q.sessionId,server:X.name})}})}createStdioClient(Q,X){return new JG({name:X.name,command:X.command,args:X.args,env:X.env,cwd:X.cwd,restartConfig:X.restartConfig,onStatusChange:(Y,W)=>{Q.setConnectionStatus(X.name,Y,W)},onNotification:(Y)=>{Q.bufferManager.addNotification(Y)},onLog:(Y)=>{Q.bufferManager.addLog({server:Y.server,timestamp:Y.timestamp,level:Y.level,logger:Y.logger,data:Y.data})},onSamplingRequest:(Y)=>{Q.pendingRequests.addSamplingRequest(Y.server,Y.params,Y.resolve,Y.reject)},onElicitationRequest:(Y)=>{Q.pendingRequests.addElicitationRequest(Y.server,Y.params,Y.resolve,Y.reject)},onLifecycleEvent:(Y)=>{switch(Y.event){case"process_started":this.logger?.info("session_stdio_process_started",{sessionId:Q.sessionId,server:X.name});break;case"process_crashed":this.handleBackendDisconnect(Q,X.name),Q.eventSystem.addEvent("server_process_crashed",X.name,{name:X.name,exitCode:Y.exitCode,signal:Y.signal}),this.logger?.warn("session_stdio_process_crashed",{sessionId:Q.sessionId,server:X.name,exitCode:Y.exitCode,signal:Y.signal});break;case"restarting":Q.eventSystem.addEvent("server_reconnecting",X.name,{name:X.name,attempt:Y.attempt,nextRetryMs:Y.nextRetryMs}),this.logger?.debug("session_stdio_restarting",{sessionId:Q.sessionId,server:X.name,attempt:Y.attempt,nextRetryMs:Y.nextRetryMs});break;case"restarted":Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_reconnected",X.name,{name:X.name,attemptsTaken:Y.attempt}),this.logger?.info("session_stdio_restarted",{sessionId:Q.sessionId,server:X.name,attemptsTaken:Y.attempt});break;case"restart_failed":Q.setConnectionStatus(X.name,"error",Y.error),Q.eventSystem.addEvent("server_restart_failed",X.name,{name:X.name,error:Y.error}),this.logger?.error("session_stdio_restart_failed",{sessionId:Q.sessionId,server:X.name,error:Y.error});break;case"process_stopped":this.logger?.info("session_stdio_process_stopped",{sessionId:Q.sessionId,server:X.name});break}}})}async disconnectSessionFromServer(Q,X){let Y=Q.getConnection(X);if(!Y){this.logger?.debug("disconnectSessionFromServer_no_connection",{sessionId:Q.sessionId,serverName:X});return}this.logger?.debug("disconnectSessionFromServer_start",{sessionId:Q.sessionId,serverName:X,connectionStatus:Y.status});let W=Q.taskManager.getTasksForServer(X);for(let $ of W)if($.status==="working")Q.taskManager.failTask($.taskId,"Server removed");Q.pendingRequests.rejectRequestsForServer(X,"Server removed");try{this.logger?.debug("disconnectSessionFromServer_calling_disconnect",{sessionId:Q.sessionId,serverName:X}),await Y.client.disconnect(),this.logger?.debug("disconnectSessionFromServer_disconnect_complete",{sessionId:Q.sessionId,serverName:X})}catch($){this.logger?.debug("disconnectSessionFromServer_disconnect_error",{sessionId:Q.sessionId,serverName:X,error:$ instanceof Error?$.message:String($)})}Q.removeConnection(X),this.logger?.debug("disconnectSessionFromServer_complete",{sessionId:Q.sessionId,serverName:X})}handleBackendDisconnect(Q,X){let Y=Q.taskManager.getTasksForServer(X);for(let W of Y)if(W.status==="working")Q.taskManager.failTask(W.taskId,"Server disconnected");Q.pendingRequests.rejectRequestsForServer(X,"Server disconnected"),Q.eventSystem.addEvent("server_disconnected",X,{name:X}),this.logger?.info("session_server_disconnected",{sessionId:Q.sessionId,server:X})}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runSessionCleanup()},this.config.cleanupIntervalMs)}runSessionCleanup(){let Q=Date.now(),X=[];for(let[Y,W]of this.sessions)if(Q-W.lastActivityAt.getTime()>=this.config.sessionTimeoutMs)X.push(Y);for(let Y of X)this.logger?.info("session_timeout_cleanup",{sessionId:Y}),this.destroySession(Y)}async shutdown(){if(this.logger?.info("session_manager_shutdown_start",{sessionCount:this.sessions.size}),this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of Array.from(this.sessions.keys()))await this.destroySession(Q);this.logger?.info("session_manager_shutdown_complete",{})}getServerConfigs(){return this.serverConfigs}listSessionIds(){return Array.from(this.sessions.keys())}get sessionCount(){return this.sessions.size}}function HG(Q){return"url"in Q&&!(("type"in Q)&&Q.type==="stdio")}function BG(Q){return"type"in Q}var VU={debug:0,info:1,warn:2,error:3};function FU(){let Q=()=>{};return{debug:Q,info:Q,warn:Q,error:Q}}function AU(Q="info",X){let Y=VU[Q],W=K1("fs"),$=(J,G,H)=>{if(VU[J]<Y)return;let B=new Date().toISOString(),z=H?` ${JSON.stringify(H)}`:"",K=`[${B}] ${J.toUpperCase()} ${G}${z}
53
+ `&&W++}}return[X,Y]}class nJ extends TransformStream{constructor({onError:Q,onRetry:X,onComment:Y}={}){let W;super({start($){W=MO({onEvent:(J)=>{$.enqueue(J)},onError(J){Q==="terminate"?$.error(J):typeof Q=="function"&&Q(J)},onRetry:X,onComment:Y})},transform($){W.feed($)}})}}var Og={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class L9 extends Error{constructor(Q,X){super(`Streamable HTTP error: ${X}`);this.code=Q}}class _Y{constructor(Q,X){this._hasCompletedAuthFlow=!1,this._url=Q,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=HO(X?.fetch,X?.requestInit),this._sessionId=X?.sessionId,this._reconnectionOptions=X?.reconnectionOptions??Og}async _authThenStart(){if(!this._authProvider)throw new f6("No auth provider");let Q;try{Q=await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Q!=="AUTHORIZED")throw new f6;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let Q={};if(this._authProvider){let Y=await this._authProvider.tokens();if(Y)Q.Authorization=`Bearer ${Y.access_token}`}if(this._sessionId)Q["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let X=NY(this._requestInit?.headers);return new Headers({...Q,...X})}async _startOrAuthSse(Q){let{resumptionToken:X}=Q;try{let Y=await this._commonHeaders();if(Y.set("Accept","text/event-stream"),X)Y.set("last-event-id",X);let W=await(this._fetch??fetch)(this._url,{method:"GET",headers:Y,signal:this._abortController?.signal});if(!W.ok){if(await W.body?.cancel(),W.status===401&&this._authProvider)return await this._authThenStart();if(W.status===405)return;throw new L9(W.status,`Failed to open SSE stream: ${W.statusText}`)}this._handleSseStream(W.body,Q,!0)}catch(Y){throw this.onerror?.(Y),Y}}_getNextReconnectionDelay(Q){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let X=this._reconnectionOptions.initialReconnectionDelay,Y=this._reconnectionOptions.reconnectionDelayGrowFactor,W=this._reconnectionOptions.maxReconnectionDelay;return Math.min(X*Math.pow(Y,Q),W)}_scheduleReconnection(Q,X=0){let Y=this._reconnectionOptions.maxRetries;if(X>=Y){this.onerror?.(Error(`Maximum reconnection attempts (${Y}) exceeded.`));return}let W=this._getNextReconnectionDelay(X);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(Q).catch(($)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${$ instanceof Error?$.message:String($)}`)),this._scheduleReconnection(Q,X+1)})},W)}_handleSseStream(Q,X,Y){if(!Q)return;let{onresumptiontoken:W,replayMessageId:$}=X,J,G=!1,H=!1;(async()=>{try{let z=Q.pipeThrough(new TextDecoderStream).pipeThrough(new nJ({onRetry:(q)=>{this._serverRetryMs=q}})).getReader();while(!0){let{value:q,done:F}=await z.read();if(F)break;if(q.id)J=q.id,G=!0,W?.(q.id);if(!q.data)continue;if(!q.event||q.event==="message")try{let A=u9.parse(JSON.parse(q.data));if(a6(A)){if(H=!0,$!==void 0)A.id=$}this.onmessage?.(A)}catch(A){this.onerror?.(A)}}if((Y||G)&&!H&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:J,onresumptiontoken:W,replayMessageId:$},0)}catch(z){if(this.onerror?.(Error(`SSE stream disconnected: ${z}`)),(Y||G)&&!H&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:J,onresumptiontoken:W,replayMessageId:$},0)}catch(q){this.onerror?.(Error(`Failed to reconnect: ${q instanceof Error?q.message:String(q)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(Q){if(!this._authProvider)throw new f6("No auth provider");if(await r4(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new f6("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(Q,X){try{let{resumptionToken:Y,onresumptiontoken:W}=X||{};if(Y){this._startOrAuthSse({resumptionToken:Y,replayMessageId:m8(Q)?Q.id:void 0}).catch((V)=>this.onerror?.(V));return}let $=await this._commonHeaders();$.set("content-type","application/json"),$.set("accept","application/json, text/event-stream");let J={...this._requestInit,method:"POST",headers:$,body:JSON.stringify(Q),signal:this._abortController?.signal},G=await(this._fetch??fetch)(this._url,J),H=G.headers.get("mcp-session-id");if(H)this._sessionId=H;if(!G.ok){let V=await G.text().catch(()=>null);if(G.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new L9(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:q,scope:F}=cJ(G);if(this._resourceMetadataUrl=q,this._scope=F,await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new f6;return this._hasCompletedAuthFlow=!0,this.send(Q)}if(G.status===403&&this._authProvider){let{resourceMetadataUrl:q,scope:F,error:A}=cJ(G);if(A==="insufficient_scope"){let D=G.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===D)throw new L9(403,"Server returned 403 after trying upscoping");if(F)this._scope=F;if(q)this._resourceMetadataUrl=q;if(this._lastUpscopingHeader=D??void 0,await r4(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new f6;return this.send(Q)}}throw new L9(G.status,`Error POSTing to endpoint: ${V}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,G.status===202){if(await G.body?.cancel(),E3(Q))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>this.onerror?.(V));return}let z=(Array.isArray(Q)?Q:[Q]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,K=G.headers.get("content-type");if(z)if(K?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:W},!1);else if(K?.includes("application/json")){let V=await G.json(),q=Array.isArray(V)?V.map((F)=>u9.parse(F)):[u9.parse(V)];for(let F of q)this.onmessage?.(F)}else throw await G.body?.cancel(),new L9(-1,`Unexpected content type: ${K}`);else await G.body?.cancel()}catch(Y){throw this.onerror?.(Y),Y}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let Q=await this._commonHeaders(),X={...this._requestInit,method:"DELETE",headers:Q,signal:this._abortController?.signal},Y=await(this._fetch??fetch)(this._url,X);if(await Y.body?.cancel(),!Y.ok&&Y.status!==405)throw new L9(Y.status,`Failed to terminate session: ${Y.statusText}`);this._sessionId=void 0}catch(Q){throw this.onerror?.(Q),Q}}setProtocolVersion(Q){this._protocolVersion=Q}get protocolVersion(){return this._protocolVersion}async resumeStream(Q,X){await this._startOrAuthSse({resumptionToken:Q,onresumptiontoken:X?.onresumptiontoken})}}var Ug=1000,jg=180000,Mg=2,Ng=0.1,NO=120000,wg=0.1,bg=60000,Pg=3;class oJ{name;url;headers;onStatusChange;onNotification;onLog;onSamplingRequest;onElicitationRequest;onReconnecting;onReconnected;onHealthDegraded;onHealthRestored;client=null;transport=null;status="disconnected";errorMessage;capabilities;isClosing=!1;reconnectAttempt=0;reconnectTimeoutHandle=null;nextRetryMs=0;isReconnecting=!1;healthCheckIntervalHandle=null;consecutiveHealthFailures=0;healthStatus="healthy";constructor(Q){this.name=Q.name,this.url=Q.url,this.headers=Q.headers,this.onStatusChange=Q.onStatusChange,this.onNotification=Q.onNotification,this.onLog=Q.onLog,this.onSamplingRequest=Q.onSamplingRequest,this.onElicitationRequest=Q.onElicitationRequest,this.onReconnecting=Q.onReconnecting,this.onReconnected=Q.onReconnected,this.onHealthDegraded=Q.onHealthDegraded,this.onHealthRestored=Q.onHealthRestored}getTransportType(){return"http"}getUrl(){return this.url}getInfo(){let Q={name:this.name,url:this.url,status:this.status};if(this.errorMessage!==void 0)Q.error=this.errorMessage;if(this.capabilities!==void 0)Q.capabilities=this.capabilities;return Q}getName(){return this.name}getStatus(){return this.status}isConnected(){return this.status==="connected"}getReconnectionState(){if(this.status!=="reconnecting")return null;return{attempt:this.reconnectAttempt,nextRetryMs:this.nextRetryMs}}getHealthStatus(){return this.healthStatus}getConsecutiveHealthFailures(){return this.consecutiveHealthFailures}async connect(){if(this.status==="connected"||this.status==="connecting")return;this.setStatus("connecting");try{let Q={};if(this.headers)Q.requestInit={headers:this.headers};this.transport=new _Y(new URL(this.url),Q),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleUnexpectedDisconnect()},this.transport.onerror=(Y)=>{if((Y.name==="AbortError"||Y.message.includes("AbortError"))&&(this.isClosing||this.status==="disconnected"))return;this.errorMessage=Y.message,this.handleUnexpectedDisconnect()},await this.client.connect(this.transport);let X=this.client.getServerCapabilities();this.capabilities={tools:X?.tools!==void 0,resources:X?.resources!==void 0,prompts:X?.prompts!==void 0,resourceTemplates:X?.resources!==void 0,resourceSubscriptions:X?.resources?.subscribe===!0},this.setStatus("connected"),this.startHealthChecks()}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw this.setStatus("error",X),Q}}async disconnect(){if(this.isClosing=!0,this.stopHealthChecks(),this.cancelReconnection(),this.transport)try{await this.transport.close()}catch{}this.client=null,this.transport=null,this.isClosing=!1,this.setStatus("disconnected")}async forceReconnect(){if(this.stopHealthChecks(),this.cancelReconnection(),this.transport){this.isClosing=!0;try{await this.transport.close()}catch{}this.isClosing=!1}this.client=null,this.transport=null,this.reconnectAttempt=0,this.nextRetryMs=0,this.consecutiveHealthFailures=0,this.healthStatus="healthy",await this.connect()}cancelReconnection(){if(this.reconnectTimeoutHandle)clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=null;this.isReconnecting=!1}async listTools(){let Q=this.getConnectedClient();if(!this.capabilities?.tools)return[];return(await Q.listTools()).tools}async callTool(Q,X={}){return await this.getConnectedClient().callTool({name:Q,arguments:X})}async listResources(){let Q=this.getConnectedClient();if(!this.capabilities?.resources)return[];return(await Q.listResources()).resources}async listResourceTemplates(){let Q=this.getConnectedClient();if(!this.capabilities?.resourceTemplates)return[];return(await Q.listResourceTemplates()).resourceTemplates}async readResource(Q){return await this.getConnectedClient().readResource({uri:Q})}async subscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.subscribeResource({uri:Q})}async unsubscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.unsubscribeResource({uri:Q})}supportsResourceSubscriptions(){return this.capabilities?.resourceSubscriptions===!0}async listPrompts(){let Q=this.getConnectedClient();if(!this.capabilities?.prompts)return[];return(await Q.listPrompts()).prompts}async getPrompt(Q,X={}){return await this.getConnectedClient().getPrompt({name:Q,arguments:X})}setupNotificationHandler(){if(!this.client)return;this.client.setNotificationHandler(Q9,()=>{this.emitNotification("notifications/tools/list_changed")}),this.client.setNotificationHandler(s6,()=>{this.emitNotification("notifications/resources/list_changed")}),this.client.setNotificationHandler(r8,(Q)=>{this.emitNotification("notifications/resources/updated",Q.params)}),this.client.setNotificationHandler(e6,()=>{this.emitNotification("notifications/prompts/list_changed")}),this.client.setNotificationHandler(a8,(Q)=>{if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:Q.params.level,logger:Q.params.logger,data:Q.params.data})}),this.client.setRequestHandler(X9,(Q)=>{return new Promise((X,Y)=>{if(this.onSamplingRequest)this.onSamplingRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Sampling not supported: no handler registered"))})}),this.client.setRequestHandler(Y9,(Q)=>{return new Promise((X,Y)=>{if(this.onElicitationRequest)this.onElicitationRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Elicitation not supported: no handler registered"))})})}emitNotification(Q,X){if(this.onNotification!==void 0)this.onNotification({server:this.name,timestamp:new Date,method:Q,params:X})}handleUnexpectedDisconnect(){if(this.isReconnecting||this.isClosing)return;this.stopHealthChecks(),this.client=null,this.transport=null,this.isReconnecting=!0,this.reconnectAttempt=0,this.setStatus("reconnecting",this.errorMessage),this.scheduleReconnection()}scheduleReconnection(){if(this.isClosing)return;this.reconnectAttempt++;let Q=this.calculateBackoff(this.reconnectAttempt);if(this.nextRetryMs=Q,this.onReconnecting)this.onReconnecting(this.reconnectAttempt,Q);this.reconnectTimeoutHandle=setTimeout(()=>{this.attemptReconnection()},Q)}async attemptReconnection(){if(this.isClosing)return;try{let Q={};if(this.headers)Q.requestInit={headers:this.headers};this.transport=new _Y(new URL(this.url),Q),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleUnexpectedDisconnect()},this.transport.onerror=(W)=>{if((W.name==="AbortError"||W.message.includes("AbortError"))&&(this.isClosing||this.status==="disconnected"))return;this.errorMessage=W.message,this.handleUnexpectedDisconnect()},await this.client.connect(this.transport);let X=this.client.getServerCapabilities();this.capabilities={tools:X?.tools!==void 0,resources:X?.resources!==void 0,prompts:X?.prompts!==void 0,resourceTemplates:X?.resources!==void 0,resourceSubscriptions:X?.resources?.subscribe===!0};let Y=this.reconnectAttempt;if(this.reconnectAttempt=0,this.nextRetryMs=0,this.isReconnecting=!1,this.consecutiveHealthFailures=0,this.healthStatus="healthy",this.setStatus("connected"),this.onReconnected)this.onReconnected(Y);this.startHealthChecks()}catch(Q){this.client=null,this.transport=null,this.errorMessage=Q instanceof Error?Q.message:String(Q),this.scheduleReconnection()}}calculateBackoff(Q){let X=Ug*Math.pow(Mg,Q-1),Y=Math.min(X,jg),W=Y*Ng*(Math.random()*2-1);return Math.round(Y+W)}startHealthChecks(){this.stopHealthChecks();let Q=()=>{let X=NO*wg*(Math.random()*2-1),Y=Math.round(NO+X);this.healthCheckIntervalHandle=setTimeout(()=>{this.performHealthCheck(),Q()},Y)};Q()}stopHealthChecks(){if(this.healthCheckIntervalHandle)clearTimeout(this.healthCheckIntervalHandle),this.healthCheckIntervalHandle=null}async performHealthCheck(){if(!this.client||!this.isConnected())return;try{let Q=new AbortController,X=setTimeout(()=>{Q.abort()},bg);try{if(await this.client.listTools(),clearTimeout(X),this.consecutiveHealthFailures>0){let Y=this.healthStatus==="degraded";if(this.consecutiveHealthFailures=0,this.healthStatus="healthy",Y&&this.onHealthRestored)this.onHealthRestored()}}catch(Y){throw clearTimeout(X),Y}}catch(Q){this.consecutiveHealthFailures++;let X=Q instanceof Error?Q.message:String(Q);if(this.consecutiveHealthFailures>=Pg&&this.healthStatus!=="degraded"){if(this.healthStatus="degraded",this.onHealthDegraded)this.onHealthDegraded(this.consecutiveHealthFailures,X)}}}setStatus(Q,X){if(this.status=Q,Q==="error"&&X!==void 0)this.errorMessage=X;else this.errorMessage=void 0;if(this.onStatusChange!==void 0)this.onStatusChange(Q,X)}getConnectedClient(){if(!this.isConnected()||!this.client)throw Error(`Client '${this.name}' is not connected`);return this.client}}var KU=O9(zU(),1);import yY from"node:process";import{PassThrough as Qh}from"node:stream";var Xh=yY.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Yh(){let Q={};for(let X of Xh){let Y=yY.env[X];if(Y===void 0)continue;if(Y.startsWith("()"))continue;Q[X]=Y}return Q}class $G{constructor(Q){if(this._readBuffer=new o4,this._stderrStream=null,this._serverParams=Q,Q.stderr==="pipe"||Q.stderr==="overlapped")this._stderrStream=new Qh}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,X)=>{if(this._process=KU.default(this._serverParams.command,this._serverParams.args??[],{env:{...Yh(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:yY.platform==="win32"&&Wh(),cwd:this._serverParams.cwd}),this._process.on("error",(Y)=>{X(Y),this.onerror?.(Y)}),this._process.on("spawn",()=>{Q()}),this._process.on("close",(Y)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(Y)=>{this.onerror?.(Y)}),this._process.stdout?.on("data",(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()}),this._process.stdout?.on("error",(Y)=>{this.onerror?.(Y)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._process){let Q=this._process;this._process=void 0;let X=new Promise((Y)=>{Q.once("close",()=>{Y()})});try{Q.stdin?.end()}catch{}if(await Promise.race([X,new Promise((Y)=>setTimeout(Y,2000).unref())]),Q.exitCode===null){try{Q.kill("SIGTERM")}catch{}await Promise.race([X,new Promise((Y)=>setTimeout(Y,2000).unref())])}if(Q.exitCode===null)try{Q.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(Q){return new Promise((X)=>{if(!this._process?.stdin)throw Error("Not connected");let Y=OY(Q);if(this._process.stdin.write(Y))X();else this._process.stdin.once("drain",X)})}}function Wh(){return"type"in yY}var $h={enabled:!0,maxAttempts:5,baseDelayMs:1000,maxDelayMs:60000,backoffMultiplier:2};class JG{name;command;args;env;cwd;restartConfig;onStatusChange;onNotification;onLog;onSamplingRequest;onElicitationRequest;onLifecycleEvent;client=null;transport=null;status="disconnected";errorMessage;capabilities;isClosing=!1;restartAttempt=0;restartTimeoutHandle=null;nextRetryMs=0;isRestarting=!1;stderrBuffer=[];maxStderrLines=1000;constructor(Q){this.name=Q.name,this.command=Q.command,this.args=Q.args??[],this.env=Q.env,this.cwd=Q.cwd,this.restartConfig={...$h,...Q.restartConfig},this.onStatusChange=Q.onStatusChange,this.onNotification=Q.onNotification,this.onLog=Q.onLog,this.onSamplingRequest=Q.onSamplingRequest,this.onElicitationRequest=Q.onElicitationRequest,this.onLifecycleEvent=Q.onLifecycleEvent}getTransportType(){return"stdio"}getInfo(){let Q={transportType:"stdio",name:this.name,url:`stdio://${this.command}`,status:this.status},X=this.transport._process;if(X?.pid!==void 0)Q.pid=X.pid;if(this.errorMessage!==void 0)Q.error=this.errorMessage;if(this.capabilities!==void 0)Q.capabilities=this.capabilities;return Q}getName(){return this.name}getStatus(){return this.status}isConnected(){return this.status==="connected"}getReconnectionState(){if(this.status!=="reconnecting")return null;return{attempt:this.restartAttempt,nextRetryMs:this.nextRetryMs}}getHealthStatus(){return this.isConnected()?"healthy":"degraded"}getConsecutiveHealthFailures(){return this.isConnected()?0:this.restartAttempt}getCommand(){return this.command}getArgs(){return[...this.args]}getStderrBuffer(){return[...this.stderrBuffer]}async connect(){if(this.status==="connected"||this.status==="connecting")return;this.setStatus("connecting");try{await this.createTransport(),this.emitLifecycleEvent({event:"process_started",timestamp:new Date}),this.setStatus("connected")}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw this.setStatus("error",X),Q}}async disconnect(){if(this.isClosing=!0,this.cancelReconnection(),this.transport)try{await this.transport.close()}catch{}this.client=null,this.transport=null,this.isClosing=!1,this.setStatus("disconnected"),this.emitLifecycleEvent({event:"process_stopped",timestamp:new Date})}async forceReconnect(){if(this.cancelReconnection(),this.transport){this.isClosing=!0;try{await this.transport.close()}catch{}this.isClosing=!1}this.client=null,this.transport=null,this.restartAttempt=0,this.nextRetryMs=0,await this.connect()}cancelReconnection(){if(this.restartTimeoutHandle)clearTimeout(this.restartTimeoutHandle),this.restartTimeoutHandle=null;this.isRestarting=!1}async listTools(){let Q=this.getConnectedClient();if(!this.capabilities?.tools)return[];return(await Q.listTools()).tools}async callTool(Q,X={}){return await this.getConnectedClient().callTool({name:Q,arguments:X})}async listResources(){let Q=this.getConnectedClient();if(!this.capabilities?.resources)return[];return(await Q.listResources()).resources}async listResourceTemplates(){let Q=this.getConnectedClient();if(!this.capabilities?.resourceTemplates)return[];return(await Q.listResourceTemplates()).resourceTemplates}async readResource(Q){return await this.getConnectedClient().readResource({uri:Q})}async subscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.subscribeResource({uri:Q})}async unsubscribeResource(Q){let X=this.getConnectedClient();if(!this.capabilities?.resourceSubscriptions)throw Error(`Server '${this.name}' does not support resource subscriptions`);await X.unsubscribeResource({uri:Q})}supportsResourceSubscriptions(){return this.capabilities?.resourceSubscriptions===!0}async listPrompts(){let Q=this.getConnectedClient();if(!this.capabilities?.prompts)return[];return(await Q.listPrompts()).prompts}async getPrompt(Q,X={}){return await this.getConnectedClient().getPrompt({name:Q,arguments:X})}async createTransport(){let Q;if(this.env){Q={};for(let[Y,W]of Object.entries(process.env))if(W!==void 0)Q[Y]=W;Object.assign(Q,this.env)}this.transport=new $G({command:this.command,args:this.args,env:Q,cwd:this.cwd,stderr:"pipe"}),this.client=new F8({name:"emceepee",version:"0.1.0"},{capabilities:{sampling:{},elicitation:{form:{}}}}),this.setupNotificationHandler(),this.transport.onclose=()=>{if(!this.isClosing)this.handleProcessExit()},this.transport.onerror=(Y)=>{if(this.isClosing||this.status==="disconnected")return;this.errorMessage=Y.message,this.handleProcessExit()},await this.client.connect(this.transport),this.setupStderrCapture();let X=this.client.getServerCapabilities();this.capabilities={tools:X?.tools!==void 0,resources:X?.resources!==void 0,prompts:X?.prompts!==void 0,resourceTemplates:X?.resources!==void 0,resourceSubscriptions:X?.resources?.subscribe===!0}}setupStderrCapture(){if(!this.transport)return;let Q=this.transport._process;if(Q?.stderr)Q.stderr.on("data",(X)=>{let Y=X.toString().split(`
54
+ `).filter((W)=>W.length>0);for(let W of Y){if(this.stderrBuffer.push(W),this.stderrBuffer.length>this.maxStderrLines)this.stderrBuffer.shift();if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:"warning",source:"stderr",data:W})}})}handleProcessExit(Q,X){if(this.isRestarting||this.isClosing)return;if(this.emitLifecycleEvent({event:"process_crashed",timestamp:new Date,exitCode:Q,signal:X}),this.client=null,this.transport=null,this.restartConfig.enabled)this.isRestarting=!0,this.restartAttempt=0,this.setStatus("reconnecting",this.errorMessage),this.scheduleRestart();else this.setStatus("error",`Process exited with code ${Q!==void 0?String(Q):"unknown"}`)}scheduleRestart(){if(this.isClosing)return;if(this.restartAttempt++,this.restartAttempt>this.restartConfig.maxAttempts){this.isRestarting=!1,this.setStatus("error","Max restart attempts exceeded"),this.emitLifecycleEvent({event:"restart_failed",timestamp:new Date,attempt:this.restartAttempt-1,error:"Max restart attempts exceeded"});return}let Q=this.calculateBackoff(this.restartAttempt);this.nextRetryMs=Q,this.emitLifecycleEvent({event:"restarting",timestamp:new Date,attempt:this.restartAttempt,nextRetryMs:Q}),this.restartTimeoutHandle=setTimeout(()=>{this.attemptRestart()},Q)}async attemptRestart(){if(this.isClosing)return;try{await this.createTransport();let Q=this.restartAttempt;this.restartAttempt=0,this.nextRetryMs=0,this.isRestarting=!1,this.setStatus("connected"),this.emitLifecycleEvent({event:"restarted",timestamp:new Date,attempt:Q})}catch(Q){this.client=null,this.transport=null,this.errorMessage=Q instanceof Error?Q.message:String(Q),this.scheduleRestart()}}calculateBackoff(Q){let X=this.restartConfig.baseDelayMs*Math.pow(this.restartConfig.backoffMultiplier,Q-1);return Math.min(X,this.restartConfig.maxDelayMs)}setupNotificationHandler(){if(!this.client)return;this.client.setNotificationHandler(Q9,()=>{this.emitNotification("notifications/tools/list_changed")}),this.client.setNotificationHandler(s6,()=>{this.emitNotification("notifications/resources/list_changed")}),this.client.setNotificationHandler(r8,(Q)=>{this.emitNotification("notifications/resources/updated",Q.params)}),this.client.setNotificationHandler(e6,()=>{this.emitNotification("notifications/prompts/list_changed")}),this.client.setNotificationHandler(a8,(Q)=>{if(this.onLog)this.onLog({server:this.name,timestamp:new Date,level:Q.params.level,logger:Q.params.logger,data:Q.params.data,source:"protocol"})}),this.client.setRequestHandler(X9,(Q)=>{return new Promise((X,Y)=>{if(this.onSamplingRequest)this.onSamplingRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Sampling not supported: no handler registered"))})}),this.client.setRequestHandler(Y9,(Q)=>{return new Promise((X,Y)=>{if(this.onElicitationRequest)this.onElicitationRequest({id:crypto.randomUUID(),server:this.name,timestamp:new Date,params:Q.params,resolve:X,reject:Y});else Y(Error("Elicitation not supported: no handler registered"))})})}emitNotification(Q,X){if(this.onNotification!==void 0)this.onNotification({server:this.name,timestamp:new Date,method:Q,params:X})}emitLifecycleEvent(Q){if(this.onLifecycleEvent)this.onLifecycleEvent(Q)}setStatus(Q,X){if(this.status=Q,Q==="error"&&X!==void 0)this.errorMessage=X;else this.errorMessage=void 0;if(this.onStatusChange!==void 0)this.onStatusChange(Q,X)}getConnectedClient(){if(!this.isConnected()||!this.client)throw Error(`Client '${this.name}' is not connected`);return this.client}}var Jh={sessionTimeoutMs:86400000,cleanupIntervalMs:300000};class GG{sessions=new Map;serverConfigs;config;logger;cleanupIntervalHandle=null;constructor(Q={}){this.config={...Jh,...Q},this.logger=Q.logger;let X={logger:Q.logger};this.serverConfigs=new SJ(X),this.startCleanupInterval()}async createSession(){let Q=f1(),X=new _J(Q,this.config.sessionStateConfig,this.logger);this.sessions.set(Q,X),this.logger?.info("session_created",{sessionId:Q});let Y=this.serverConfigs.listConfigs();for(let W of Y)try{await this.connectSessionToServer(X,W)}catch($){this.logger?.warn("session_auto_connect_failed",{sessionId:Q,server:W.name,error:$ instanceof Error?$.message:String($)})}return X}getSession(Q){return this.sessions.get(Q)}touchSession(Q){this.sessions.get(Q)?.touch()}async destroySession(Q){let X=this.sessions.get(Q);if(!X)return;this.logger?.info("session_destroying",{sessionId:Q}),await X.cleanup(),this.sessions.delete(Q),this.logger?.info("session_destroyed",{sessionId:Q})}async addServer(Q,X,Y,W){let $=this.sessions.get(Q);if(!$)throw Error(`Session '${Q}' not found`);let J=this.serverConfigs.addConfig(X,Y,{headers:W?.headers},Q),G=this.serverConfigs.getConfig(X);if(!G)throw Error(`Failed to add server config for '${X}'`);let H=await this.connectSessionToServer($,G);if(J){for(let[B,z]of this.sessions)if(B!==Q)z.eventSystem.addEvent("server_added",X,{name:X,url:Y,addedBy:Q})}return H}async addStdioServer(Q,X,Y,W,$){let J=this.sessions.get(Q);if(!J)throw Error(`Session '${Q}' not found`);let G=this.serverConfigs.addStdioConfig(X,Y,W,$,Q),H=this.serverConfigs.getConfig(X);if(!H)throw Error(`Failed to add server config for '${X}'`);let B=await this.connectSessionToServer(J,H);if(G){for(let[z,K]of this.sessions)if(z!==Q)K.eventSystem.addEvent("server_added",X,{name:X,type:"stdio",command:Y,args:W,addedBy:Q})}return B}async removeServer(Q,X){if(this.logger?.debug("removeServer_start",{sessionId:Q,serverName:X}),!this.serverConfigs.removeConfig(X))throw this.logger?.debug("removeServer_not_found",{sessionId:Q,serverName:X}),Error(`Server '${X}' not found`);for(let[W,$]of this.sessions)this.logger?.debug("removeServer_disconnecting_session",{sessionId:W,serverName:X,hasConnection:$.getConnection(X)!==void 0}),await this.disconnectSessionFromServer($,X),$.eventSystem.addEvent("server_removed",X,{name:X,removedBy:Q});this.logger?.debug("removeServer_complete",{sessionId:Q,serverName:X})}listServers(Q){let X=this.sessions.get(Q);return this.serverConfigs.listConfigs().map((W)=>{let $=X?.getConnection(W.name),J;if(RJ(W))J=W.url;else if(EJ(W))J=`stdio://${W.command}`;else J="unknown";let G={name:W.name,url:J,connected:$?.status==="connected",status:$?.status??"not_connected",connectedAt:$?.connectedAt,lastError:$?.lastError};if($?.status==="reconnecting"){let H=$.client.getReconnectionState();if(H)G.reconnectAttempt=H.attempt,G.nextRetryMs=H.nextRetryMs}if($?.status==="connected"){G.healthStatus=$.client.getHealthStatus();let H=$.client.getConsecutiveHealthFailures();if(H>0)G.consecutiveHealthFailures=H}return G})}async reconnectServer(Q,X){let Y=this.sessions.get(Q);if(!Y)throw Error(`Session '${Q}' not found`);let W=this.serverConfigs.getConfig(X);if(!W)throw Error(`Server '${X}' not found`);let $=Y.getConnection(X);if(!$){await this.connectSessionToServer(Y,W);return}this.handleBackendDisconnect(Y,X),await $.client.forceReconnect(),Y.setConnectionStatus(X,"connected"),Y.eventSystem.addEvent("server_reconnected",X,{name:X,attemptsTaken:0,forced:!0}),this.logger?.info("session_server_force_reconnected",{sessionId:Y.sessionId,server:X})}async getOrCreateConnection(Q,X){let Y=this.sessions.get(Q);if(!Y)throw Error(`Session '${Q}' not found`);let W=Y.getConnection(X);if(W?.status==="connected")return W.client;let $=this.serverConfigs.getConfig(X);if(!$)throw Error(`Server '${X}' not found`);return(await this.connectSessionToServer(Y,$)).client}getConnectedClient(Q,X){let Y=this.sessions.get(Q);if(!Y)return;let W=Y.getConnection(X);if(W?.status==="connected")return W.client;return}async connectSessionToServer(Q,X){let Y=Q.backendConnections.get(X.name);if(Y?.status==="connected")return Y;if(Y?.status==="connecting")throw Error(`Already connecting to '${X.name}'`);let W;if(RJ(X))W=this.createHttpClient(Q,X);else if(EJ(X))W=this.createStdioClient(Q,X);else throw Error(`Unknown server config type for '${X.name}'`);Q.addConnection(X.name,W);try{await W.connect(),Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_connected",X.name,{name:X.name,capabilities:W.getInfo().capabilities}),this.logger?.info("session_server_connected",{sessionId:Q.sessionId,server:X.name});let $=Q.getConnection(X.name);if(!$)throw Error("Connection not found after connect");return $}catch($){let J=$ instanceof Error?$.message:String($);throw Q.setConnectionStatus(X.name,"error",J),this.logger?.warn("session_server_connect_failed",{sessionId:Q.sessionId,server:X.name,error:J}),$}}createHttpClient(Q,X){return new oJ({name:X.name,url:X.url,headers:X.headers,onStatusChange:(Y,W)=>{Q.setConnectionStatus(X.name,Y,W)},onNotification:(Y)=>{Q.bufferManager.addNotification(Y)},onLog:(Y)=>{Q.bufferManager.addLog(Y)},onSamplingRequest:(Y)=>{Q.pendingRequests.addSamplingRequest(Y.server,Y.params,Y.resolve,Y.reject)},onElicitationRequest:(Y)=>{Q.pendingRequests.addElicitationRequest(Y.server,Y.params,Y.resolve,Y.reject)},onReconnecting:(Y,W)=>{if(Y===1)this.handleBackendDisconnect(Q,X.name);Q.eventSystem.addEvent("server_reconnecting",X.name,{name:X.name,attempt:Y,nextRetryMs:W}),this.logger?.debug("session_server_reconnecting",{sessionId:Q.sessionId,server:X.name,attempt:Y,nextRetryMs:W})},onReconnected:(Y)=>{Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_reconnected",X.name,{name:X.name,attemptsTaken:Y}),this.logger?.info("session_server_reconnected",{sessionId:Q.sessionId,server:X.name,attemptsTaken:Y})},onHealthDegraded:(Y,W)=>{Q.eventSystem.addEvent("server_health_degraded",X.name,{name:X.name,consecutiveFailures:Y,lastError:W}),this.logger?.warn("session_server_health_degraded",{sessionId:Q.sessionId,server:X.name,consecutiveFailures:Y,lastError:W})},onHealthRestored:()=>{Q.eventSystem.addEvent("server_health_restored",X.name,{name:X.name}),this.logger?.info("session_server_health_restored",{sessionId:Q.sessionId,server:X.name})}})}createStdioClient(Q,X){return new JG({name:X.name,command:X.command,args:X.args,env:X.env,cwd:X.cwd,restartConfig:X.restartConfig,onStatusChange:(Y,W)=>{Q.setConnectionStatus(X.name,Y,W)},onNotification:(Y)=>{Q.bufferManager.addNotification(Y)},onLog:(Y)=>{Q.bufferManager.addLog({server:Y.server,timestamp:Y.timestamp,level:Y.level,logger:Y.logger,data:Y.data})},onSamplingRequest:(Y)=>{Q.pendingRequests.addSamplingRequest(Y.server,Y.params,Y.resolve,Y.reject)},onElicitationRequest:(Y)=>{Q.pendingRequests.addElicitationRequest(Y.server,Y.params,Y.resolve,Y.reject)},onLifecycleEvent:(Y)=>{switch(Y.event){case"process_started":this.logger?.info("session_stdio_process_started",{sessionId:Q.sessionId,server:X.name});break;case"process_crashed":this.handleBackendDisconnect(Q,X.name),Q.eventSystem.addEvent("server_process_crashed",X.name,{name:X.name,exitCode:Y.exitCode,signal:Y.signal}),this.logger?.warn("session_stdio_process_crashed",{sessionId:Q.sessionId,server:X.name,exitCode:Y.exitCode,signal:Y.signal});break;case"restarting":Q.eventSystem.addEvent("server_reconnecting",X.name,{name:X.name,attempt:Y.attempt,nextRetryMs:Y.nextRetryMs}),this.logger?.debug("session_stdio_restarting",{sessionId:Q.sessionId,server:X.name,attempt:Y.attempt,nextRetryMs:Y.nextRetryMs});break;case"restarted":Q.setConnectionStatus(X.name,"connected"),Q.eventSystem.addEvent("server_reconnected",X.name,{name:X.name,attemptsTaken:Y.attempt}),this.logger?.info("session_stdio_restarted",{sessionId:Q.sessionId,server:X.name,attemptsTaken:Y.attempt});break;case"restart_failed":Q.setConnectionStatus(X.name,"error",Y.error),Q.eventSystem.addEvent("server_restart_failed",X.name,{name:X.name,error:Y.error}),this.logger?.error("session_stdio_restart_failed",{sessionId:Q.sessionId,server:X.name,error:Y.error});break;case"process_stopped":this.logger?.info("session_stdio_process_stopped",{sessionId:Q.sessionId,server:X.name});break}}})}async disconnectSessionFromServer(Q,X){let Y=Q.getConnection(X);if(!Y){this.logger?.debug("disconnectSessionFromServer_no_connection",{sessionId:Q.sessionId,serverName:X});return}this.logger?.debug("disconnectSessionFromServer_start",{sessionId:Q.sessionId,serverName:X,connectionStatus:Y.status});let W=Q.taskManager.getTasksForServer(X);for(let $ of W)if($.status==="working")Q.taskManager.failTask($.taskId,"Server removed");Q.pendingRequests.rejectRequestsForServer(X,"Server removed");try{this.logger?.debug("disconnectSessionFromServer_calling_disconnect",{sessionId:Q.sessionId,serverName:X}),await Y.client.disconnect(),this.logger?.debug("disconnectSessionFromServer_disconnect_complete",{sessionId:Q.sessionId,serverName:X})}catch($){this.logger?.debug("disconnectSessionFromServer_disconnect_error",{sessionId:Q.sessionId,serverName:X,error:$ instanceof Error?$.message:String($)})}Q.removeConnection(X),this.logger?.debug("disconnectSessionFromServer_complete",{sessionId:Q.sessionId,serverName:X})}handleBackendDisconnect(Q,X){let Y=Q.taskManager.getTasksForServer(X);for(let W of Y)if(W.status==="working")Q.taskManager.failTask(W.taskId,"Server disconnected");Q.pendingRequests.rejectRequestsForServer(X,"Server disconnected"),Q.eventSystem.addEvent("server_disconnected",X,{name:X}),this.logger?.info("session_server_disconnected",{sessionId:Q.sessionId,server:X})}startCleanupInterval(){this.cleanupIntervalHandle=setInterval(()=>{this.runSessionCleanup()},this.config.cleanupIntervalMs)}runSessionCleanup(){let Q=Date.now(),X=[];for(let[Y,W]of this.sessions)if(Q-W.lastActivityAt.getTime()>=this.config.sessionTimeoutMs)X.push(Y);for(let Y of X)this.logger?.info("session_timeout_cleanup",{sessionId:Y}),this.destroySession(Y)}async shutdown(){if(this.logger?.info("session_manager_shutdown_start",{sessionCount:this.sessions.size}),this.cleanupIntervalHandle)clearInterval(this.cleanupIntervalHandle),this.cleanupIntervalHandle=null;for(let Q of Array.from(this.sessions.keys()))await this.destroySession(Q);this.logger?.info("session_manager_shutdown_complete",{})}getServerConfigs(){return this.serverConfigs}listSessionIds(){return Array.from(this.sessions.keys())}get sessionCount(){return this.sessions.size}}function HG(Q){return"url"in Q&&!(("type"in Q)&&Q.type==="stdio")}function BG(Q){return"type"in Q}var VU={debug:0,info:1,warn:2,error:3};function FU(){let Q=()=>{};return{debug:Q,info:Q,warn:Q,error:Q}}function AU(Q="info",X){let Y=VU[Q],W=K1("fs"),$=(J,G,H)=>{if(VU[J]<Y)return;let B=new Date().toISOString(),z=H?` ${JSON.stringify(H)}`:"",K=`[${B}] ${J.toUpperCase()} ${G}${z}
55
55
  `;try{W.appendFileSync(X,K)}catch(V){process.stderr.write(`Failed to write to log file: ${String(V)}
56
56
  `),process.stderr.write(K)}};return{debug:(J,G)=>{$("debug",J,G)},info:(J,G)=>{$("info",J,G)},warn:(J,G)=>{$("warn",J,G)},error:(J,G)=>{$("error",J,G)}}}function Hh(Q,X){return{start:async()=>{return X.debug("transport_start",{}),Q.start()},send:async(W,$)=>{return X.debug("transport_send",{message:JSON.stringify(W),hasRelatedRequestId:$?.relatedRequestId!==void 0}),Q.send(W,$)},close:async()=>{return X.debug("transport_close",{}),Q.close()},get sessionId(){return Q.sessionId},set onclose(W){Q.onclose=W?()=>{X.debug("transport_onclose",{}),W()}:void 0},get onclose(){return Q.onclose},set onerror(W){Q.onerror=W?($)=>{X.debug("transport_onerror",{error:$.message}),W($)}:void 0},get onerror(){return Q.onerror},set onmessage(W){Q.onmessage=W?($)=>{X.debug("transport_onmessage",{message:JSON.stringify($)}),W($)}:void 0},get onmessage(){return Q.onmessage},setProtocolVersion:Q.setProtocolVersion?.bind(Q)}}function Bh(){let Q=process.argv.slice(2),X,Y="info",W;for(let $=0;$<Q.length;$++){let J=Q[$];if(J==="--config"&&Q[$+1])X=Q[$+1],$++;else if(J?.startsWith("--config="))X=J.slice(9);else if(J==="--log-level"&&Q[$+1])Y=Q[$+1],$++;else if(J?.startsWith("--log-level="))Y=J.slice(12);else if(J==="--log-file"&&Q[$+1])W=Q[$+1],$++;else if(J?.startsWith("--log-file="))W=J.slice(11)}return{configPath:X,logLevel:Y,logFile:W}}function zh(Q){let X=Gh(Q,"utf-8");return JSON.parse(X)}function Kh(Q){return JSON.parse(Q)}function N0(Q){return Q}function qU(Q){let X=Q.pendingRequests.getPendingSamplingRequests().length,Y=Q.pendingRequests.getPendingElicitationRequests().length,W=Q.timerManager.getAndClearExpired(),$=Q.bufferManager.getAndClearNotifications(),J=X>0||Y>0,G=W.length>0,H=$.length>0;if(!J&&!G&&!H)return null;let B={};if(J)B.pending_client={sampling:X,elicitation:Y};if(G)B.expired_timers=W;if(H)B.notifications=$.map((z)=>({server:z.server,method:z.method,timestamp:z.timestamp.toISOString(),params:z.params}));return B}function DU(Q,X){if(!X)return Q;let Y=qU(X);if(!Y)return Q;return{...Q,content:[...Q.content,{type:"text",text:JSON.stringify(Y)}]}}function c(Q){return{content:[{type:"text",text:Q}],isError:!0}}function m0(Q,X){return DU({content:[{type:"text",text:Q}]},X)}function S0(Q,X){let Y={content:[{type:"text",text:JSON.stringify(Q,null,2)}]};return DU(Y,X)}function Vh(Q,X,Y){Q.registerTool("add_server",{description:`Connect to a backend MCP server. Supports two transport types:
57
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emceepee",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "description": "MCP proxy server with static tools for managing dynamic backend MCP servers",
5
5
  "type": "module",
6
6
  "bin": {