@0xmonaco/mcp-server 0.8.15 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +1 -1
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -133,7 +133,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
133
133
  `:`[${Y[K]}\r
134
134
  ]`;continue}if(X+=Y[K],Y[K]==="\\")G=!0;else if(W&&Y[K]==="]")W=!1;else if(!W&&Y[K]==="[")W=!0}try{new RegExp(X)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return X}function iN($,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&$.keyType?._def.typeName===J$.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((Y,X)=>({...Y,[X]:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",X]})??h4(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return Q;if($.keyType?._def.typeName===J$.ZodString&&$.keyType._def.checks?.length){let{type:Y,...X}=cN($.keyType._def,J);return{...Q,propertyNames:X}}else if($.keyType?._def.typeName===J$.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===J$.ZodBranded&&$.keyType._def.type._def.typeName===J$.ZodString&&$.keyType._def.type._def.checks?.length){let{type:Y,...X}=nN($.keyType._def,J);return{...Q,propertyNames:X}}return Q}function nk($,J){if(J.mapStrategy==="record")return iN($,J);let Q=P$($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||h4(J),Y=P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||h4(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,Y],minItems:2,maxItems:2}}}function ck($){let J=$.values,Y=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),X=Array.from(new Set(Y.map((G)=>typeof G)));return{type:X.length===1?X[0]==="string"?"string":"number":["string","number"],enum:Y}}function ik($){return $.target==="openAi"?void 0:{not:h4({...$,currentPath:[...$.currentPath,"not"]})}}function ok($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _V={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tk($,J){if(J.target==="openApi3")return rk($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in _V)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((X,G)=>{let W=_V[G._def.typeName];return W&&!X.includes(W)?[...X,W]:X},[]);return{type:Y.length>1?Y:Y[0]}}else if(Q.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=Q.reduce((X,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...X,W];case"bigint":return[...X,"integer"];case"object":if(G._def.value===null)return[...X,"null"];case"symbol":case"undefined":case"function":default:return X}},[]);if(Y.length===Q.length){let X=Y.filter((G,W,V)=>V.indexOf(G)===W);return{type:X.length>1?X:X[0],enum:Q.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(Q.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((Y,X)=>[...Y,...X._def.values.filter((G)=>!Y.includes(G))],[])};return rk($,J)}var rk=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((Y,X)=>P$(Y._def,{...J,currentPath:[...J.currentPath,"anyOf",`${X}`]})).filter((Y)=>!!Y&&(!J.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return Q.length?{anyOf:Q}:void 0};function ak($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:_V[$.innerType._def.typeName],nullable:!0};return{type:[_V[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let Y=P$($.innerType._def,{...J,currentPath:[...J.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let Q=P$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function sk($,J){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",_Z(Q,"type",Y.message,J);break;case"min":if(J.target==="jsonSchema7")if(Y.inclusive)t$(Q,"minimum",Y.value,Y.message,J);else t$(Q,"exclusiveMinimum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;t$(Q,"minimum",Y.value,Y.message,J)}break;case"max":if(J.target==="jsonSchema7")if(Y.inclusive)t$(Q,"maximum",Y.value,Y.message,J);else t$(Q,"exclusiveMaximum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;t$(Q,"maximum",Y.value,Y.message,J)}break;case"multipleOf":t$(Q,"multipleOf",Y.value,Y.message,J);break}return Q}function ek($,J){let Q=J.target==="openAi",Y={type:"object",properties:{}},X=[],G=$.shape();for(let V in G){let K=G[V];if(K===void 0||K._def===void 0)continue;let D=U0$(K);if(D&&Q){if(K._def.typeName==="ZodOptional")K=K._def.innerType;if(!K.isNullable())K=K.nullable();D=!1}let O=P$(K._def,{...J,currentPath:[...J.currentPath,"properties",V],propertyPath:[...J.currentPath,"properties",V]});if(O===void 0)continue;if(Y.properties[V]=O,!D)X.push(V)}if(X.length)Y.required=X;let W=D0$($,J);if(W!==void 0)Y.additionalProperties=W;return Y}function D0$($,J){if($.catchall._def.typeName!=="ZodNever")return P$($.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function U0$($){try{return $.isOptional()}catch{return!0}}var $x=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return P$($.innerType._def,J);let Q=P$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:h4(J)},Q]}:h4(J)};var Jx=($,J)=>{if(J.pipeStrategy==="input")return P$($.in._def,J);else if(J.pipeStrategy==="output")return P$($.out._def,J);let Q=P$($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),Y=P$($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,Y].filter((X)=>X!==void 0)}};function Qx($,J){return P$($.type._def,J)}function Xx($,J){let Y={type:"array",uniqueItems:!0,items:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)t$(Y,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)t$(Y,"maxItems",$.maxSize.value,$.maxSize.message,J);return Y}function Yx($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,Y)=>P$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[]),additionalItems:P$($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,Y)=>P$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[])}}function Gx($){return{not:h4($)}}function Wx($){return h4($)}var Vx=($,J)=>{return P$($.innerType._def,J)};var Kx=($,J,Q)=>{switch(J){case J$.ZodString:return cN($,Q);case J$.ZodNumber:return sk($,Q);case J$.ZodObject:return ek($,Q);case J$.ZodBigInt:return bk($,Q);case J$.ZodBoolean:return gk();case J$.ZodDate:return TZ($,Q);case J$.ZodUndefined:return Gx(Q);case J$.ZodNull:return ok(Q);case J$.ZodArray:return fk($,Q);case J$.ZodUnion:case J$.ZodDiscriminatedUnion:return tk($,Q);case J$.ZodIntersection:return lk($,Q);case J$.ZodTuple:return Yx($,Q);case J$.ZodRecord:return iN($,Q);case J$.ZodLiteral:return dk($,Q);case J$.ZodEnum:return mk($);case J$.ZodNativeEnum:return ck($);case J$.ZodNullable:return ak($,Q);case J$.ZodOptional:return $x($,Q);case J$.ZodMap:return nk($,Q);case J$.ZodSet:return Xx($,Q);case J$.ZodLazy:return()=>$.getter()._def;case J$.ZodPromise:return Qx($,Q);case J$.ZodNaN:case J$.ZodNever:return ik(Q);case J$.ZodEffects:return uk($,Q);case J$.ZodAny:return h4(Q);case J$.ZodUnknown:return Wx(Q);case J$.ZodDefault:return hk($,Q);case J$.ZodBranded:return nN($,Q);case J$.ZodReadonly:return Vx($,Q);case J$.ZodCatch:return yk($,Q);case J$.ZodPipeline:return Jx($,Q);case J$.ZodFunction:case J$.ZodVoid:case J$.ZodSymbol:return;default:return((Y)=>{return})(J)}};function P$($,J,Q=!1){let Y=J.seen.get($);if(J.override){let V=J.override?.($,J,Y,Q);if(V!==vk)return V}if(Y&&!Q){let V=O0$(Y,J);if(V!==void 0)return V}let X={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,X);let G=Kx($,$.typeName,J),W=typeof G==="function"?P$(G(),J):G;if(W)N0$($,J,W);if(J.postProcess){let V=J.postProcess(W,$,J);return X.jsonSchema=W,V}return X.jsonSchema=W,W}var O0$=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:pN(J.currentPath,$.path)};case"none":case"seen":{if($.path.length<J.currentPath.length&&$.path.every((Q,Y)=>J.currentPath[Y]===Q))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),h4(J);return J.$refStrategy==="seen"?h4(J):void 0}}},N0$=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var PZ=($,J)=>{let Q=xk(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((K,[D,O])=>({...K,[D]:P$(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,D]},!0)??h4(Q)}),{}):void 0,X=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=P$($._def,X===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,X]},!1)??h4(Q),W=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(W!==void 0)G.title=W;if(Q.flags.hasReferencedOpenAiAnyType){if(!Y)Y={};if(!Y[Q.openAiAnyTypeName])Y[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let V=X===void 0?Y?{...G,[Q.definitionPath]:Y}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,X].join("/"),[Q.definitionPath]:{...Y,[X]:G}};if(Q.target==="jsonSchema7")V.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")V.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.target==="openAi"&&(("anyOf"in V)||("oneOf"in V)||("allOf"in V)||("type"in V)&&Array.isArray(V.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return V};function M0$($){if(!$)return"draft-7";if($==="jsonSchema7"||$==="draft-7")return"draft-7";if($==="jsonSchema2019-09"||$==="draft-2020-12")return"draft-2020-12";return"draft-7"}function vZ($,J){if($0($))return cX($,{target:M0$(J?.target),io:J?.pipeStrategy??"input"});return PZ($,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function kZ($){let Q=q8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=i3(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function xZ($,J){let Q=I8($,J);if(!Q.success)throw Q.error;return Q.data}var w0$=60000;class fZ{constructor($){if(this._options=$,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(_N,(J)=>{this._oncancel(J)}),this.setNotificationHandler(RN,(J)=>{this._onprogress(J)}),this.setRequestHandler(TN,(J)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(CN,async(J,Q)=>{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new L$(j$.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(vN,async(J,Q)=>{let Y=async()=>{let X=J.params.taskId;if(this._taskMessageQueue){let W;while(W=await this._taskMessageQueue.dequeue(X,Q.sessionId)){if(W.type==="response"||W.type==="error"){let V=W.message,K=V.id,D=this._requestResolvers.get(K);if(D)if(this._requestResolvers.delete(K),W.type==="response")D(V);else{let O=V,N=new L$(O.error.code,O.error.message,O.error.data);D(N)}else{let O=W.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${K}`))}continue}await this._transport?.send(W.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(X,Q.sessionId);if(!G)throw new L$(j$.InvalidParams,`Task not found: ${X}`);if(!B8(G.status))return await this._waitForTaskUpdate(X,Q.signal),await Y();if(B8(G.status)){let W=await this._taskStore.getTaskResult(X,Q.sessionId);return this._clearTaskQueue(X),{...W,_meta:{...W._meta,[Z8]:{taskId:X}}}}return await Y()};return await Y()}),this.setRequestHandler(kN,async(J,Q)=>{try{let{tasks:Y,nextCursor:X}=await this._taskStore.listTasks(J.params?.cursor,Q.sessionId);return{tasks:Y,nextCursor:X,_meta:{}}}catch(Y){throw new L$(j$.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(fN,async(J,Q)=>{try{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new L$(j$.InvalidParams,`Task not found: ${J.params.taskId}`);if(B8(Y.status))throw new L$(j$.InvalidParams,`Cannot cancel task in terminal status: ${Y.status}`);await this._taskStore.updateTaskStatus(J.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(J.params.taskId);let X=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!X)throw new L$(j$.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...X}}catch(Y){if(Y instanceof L$)throw Y;throw new L$(j$.InvalidRequest,`Failed to cancel task: ${Y instanceof Error?Y.message:String(Y)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,J,Q,Y,X=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,J),startTime:Date.now(),timeout:J,maxTotalTimeout:Q,resetTimeoutOnProgress:X,onTimeout:Y})}_resetTimeout($){let J=this._timeoutInfo.get($);if(!J)return!1;let Q=Date.now()-J.startTime;if(J.maxTotalTimeout&&Q>=J.maxTotalTimeout)throw this._timeoutInfo.delete($),L$.fromError(j$.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:J.maxTotalTimeout,totalElapsed:Q});return clearTimeout(J.timeoutId),J.timeoutId=setTimeout(J.onTimeout,J.timeout),!0}_cleanupTimeout($){let J=this._timeoutInfo.get($);if(J)clearTimeout(J.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let J=this.transport?.onclose;this._transport.onclose=()=>{J?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(X)=>{Q?.(X),this._onerror(X)};let Y=this._transport?.onmessage;this._transport.onmessage=(X,G)=>{if(Y?.(X,G),IV(X)||qk(X))this._onresponse(X);else if(MZ(X))this._onrequest(X,G);else if(Ik(X))this._onnotification(X);else this._onerror(Error(`Unknown message type: ${JSON.stringify(X)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Q of this._timeoutInfo.values())clearTimeout(Q.timeoutId);this._timeoutInfo.clear();for(let Q of this._requestHandlerAbortControllers.values())Q.abort();this._requestHandlerAbortControllers.clear();let J=L$.fromError(j$.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of $.values())Q(J)}_onerror($){this.onerror?.($)}_onnotification($){let J=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(J===void 0)return;Promise.resolve().then(()=>J($)).catch((Q)=>this._onerror(Error(`Uncaught error in notification handler: ${Q}`)))}_onrequest($,J){let Q=this._requestHandlers.get($.method)??this.fallbackRequestHandler,Y=this._transport,X=$.params?._meta?.[Z8]?.taskId;if(Q===void 0){let D={jsonrpc:"2.0",id:$.id,error:{code:j$.MethodNotFound,message:"Method not found"}};if(X&&this._taskMessageQueue)this._enqueueTaskMessage(X,{type:"error",message:D,timestamp:Date.now()},Y?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else Y?.send(D).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let W=Hk($.params)?$.params.task:void 0,V=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,K={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(D)=>{if(G.signal.aborted)return;let O={relatedRequestId:$.id};if(X)O.relatedTask={taskId:X};await this.notification(D,O)},sendRequest:async(D,O,N)=>{if(G.signal.aborted)throw new L$(j$.ConnectionClosed,"Request was cancelled");let M={...N,relatedRequestId:$.id};if(X&&!M.relatedTask)M.relatedTask={taskId:X};let w=M.relatedTask?.taskId??X;if(w&&V)await V.updateTaskStatus(w,"input_required");return await this.request(D,O,M)},authInfo:J?.authInfo,requestId:$.id,requestInfo:J?.requestInfo,taskId:X,taskStore:V,taskRequestedTtl:W?.ttl,closeSSEStream:J?.closeSSEStream,closeStandaloneSSEStream:J?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(W)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,K)).then(async(D)=>{if(G.signal.aborted)return;let O={result:D,jsonrpc:"2.0",id:$.id};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"response",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)},async(D)=>{if(G.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(D.code)?D.code:j$.InternalError,message:D.message??"Internal error",...D.data!==void 0&&{data:D.data}}};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"error",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)}).catch((D)=>this._onerror(Error(`Failed to send response: ${D}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:J,...Q}=$.params,Y=Number(J),X=this._progressHandlers.get(Y);if(!X){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(Y),W=this._timeoutInfo.get(Y);if(W&&G&&W.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(V){this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),G(V);return}X(Q)}_onresponse($){let J=Number($.id),Q=this._requestResolvers.get(J);if(Q){if(this._requestResolvers.delete(J),IV($))Q($);else{let G=new L$($.error.code,$.error.message,$.error.data);Q(G)}return}let Y=this._responseHandlers.get(J);if(Y===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(J),this._cleanupTimeout(J);let X=!1;if(IV($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let W=G.task;if(typeof W.taskId==="string")X=!0,this._taskProgressTokens.set(W.taskId,J)}}if(!X)this._progressHandlers.delete(J);if(IV($))Y($);else{let G=L$.fromError($.error.code,$.error.message,$.error.data);Y(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,J,Q){let{task:Y}=Q??{};if(!Y){try{yield{type:"result",result:await this.request($,J,Q)}}catch(G){yield{type:"error",error:G instanceof L$?G:new L$(j$.InternalError,String(G))}}return}let X;try{let G=await this.request($,z5,Q);if(G.task)X=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new L$(j$.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:X},Q);if(yield{type:"taskStatus",task:W},B8(W.status)){if(W.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:X},J,Q)};else if(W.status==="failed")yield{type:"error",error:new L$(j$.InternalError,`Task ${X} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new L$(j$.InternalError,`Task ${X} was cancelled`)};return}if(W.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:X},J,Q)};return}let V=W.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((K)=>setTimeout(K,V)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof L$?G:new L$(j$.InternalError,String(G))}}}request($,J,Q){let{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G,task:W,relatedTask:V}=Q??{};return new Promise((K,D)=>{let O=(L)=>{D(L)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(L){O(L);return}Q?.signal?.throwIfAborted();let N=this._requestMessageId++,M={...$,jsonrpc:"2.0",id:N};if(Q?.onprogress)this._progressHandlers.set(N,Q.onprogress),M.params={...$.params,_meta:{...$.params?._meta||{},progressToken:N}};if(W)M.params={...M.params,task:W};if(V)M.params={...M.params,_meta:{...M.params?._meta||{},[Z8]:V}};let w=(L)=>{this._responseHandlers.delete(N),this._progressHandlers.delete(N),this._cleanupTimeout(N),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:N,reason:String(L)}},{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((B)=>this._onerror(Error(`Failed to send cancellation: ${B}`)));let E=L instanceof L$?L:new L$(j$.RequestTimeout,String(L));D(E)};this._responseHandlers.set(N,(L)=>{if(Q?.signal?.aborted)return;if(L instanceof Error)return D(L);try{let E=I8(J,L.result);if(!E.success)D(E.error);else K(E.data)}catch(E){D(E)}}),Q?.signal?.addEventListener("abort",()=>{w(Q?.signal?.reason)});let A=Q?.timeout??w0$,q=()=>w(L$.fromError(j$.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(N,A,Q?.maxTotalTimeout,q,Q?.resetTimeoutOnProgress??!1);let F=V?.taskId;if(F){let L=(E)=>{let B=this._responseHandlers.get(N);if(B)B(E);else this._onerror(Error(`Response handler missing for side-channeled request ${N}`))};this._requestResolvers.set(N,L),this._enqueueTaskMessage(F,{type:"request",message:M,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(N),D(E)})}else this._transport.send(M,{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((L)=>{this._cleanupTimeout(N),D(L)})})}async getTask($,J){return this.request({method:"tasks/get",params:$},PN,J)}async getTaskResult($,J,Q){return this.request({method:"tasks/result",params:$},J,Q)}async listTasks($,J){return this.request({method:"tasks/list",params:$},xN,J)}async cancelTask($,J){return this.request({method:"tasks/cancel",params:$},Bk,J)}async notification($,J){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let Q=J?.relatedTask?.taskId;if(Q){let W={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[Z8]:J.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:W,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!J?.relatedRequestId&&!J?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let W={...$,jsonrpc:"2.0"};if(J?.relatedTask)W={...W,params:{...W.params,_meta:{...W.params?._meta||{},[Z8]:J.relatedTask}}};this._transport?.send(W,J).catch((V)=>this._onerror(V))});return}let G={...$,jsonrpc:"2.0"};if(J?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Z8]:J.relatedTask}}};await this._transport.send(G,J)}setRequestHandler($,J){let Q=kZ($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,X)=>{let G=xZ($,Y);return Promise.resolve(J(G,X))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,J){let Q=kZ($);this._notificationHandlers.set(Q,(Y)=>{let X=xZ($,Y);return Promise.resolve(J(X))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let J=this._taskProgressTokens.get($);if(J!==void 0)this._progressHandlers.delete(J),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,J,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Y=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,J,Q,Y)}async _clearTaskQueue($,J){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,J);for(let Y of Q)if(Y.type==="request"&&MZ(Y.message)){let X=Y.message.id,G=this._requestResolvers.get(X);if(G)G(new L$(j$.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(X);else this._onerror(Error(`Resolver missing for request ${X} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,J){let Q=this._options?.defaultTaskPollInterval??1000;try{let Y=await this._taskStore?.getTask($);if(Y?.pollInterval)Q=Y.pollInterval}catch{}return new Promise((Y,X)=>{if(J.aborted){X(new L$(j$.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);J.addEventListener("abort",()=>{clearTimeout(G),X(new L$(j$.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,J){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(Y)=>{if(!$)throw Error("No request provided");return await Q.createTask(Y,$.id,{method:$.method,params:$.params},J)},getTask:async(Y)=>{let X=await Q.getTask(Y,J);if(!X)throw new L$(j$.InvalidParams,"Failed to retrieve task: Task not found");return X},storeTaskResult:async(Y,X,G)=>{await Q.storeTaskResult(Y,X,G,J);let W=await Q.getTask(Y,J);if(W){let V=FV.parse({method:"notifications/tasks/status",params:W});if(await this.notification(V),B8(W.status))this._cleanupTaskProgressHandler(Y)}},getTaskResult:(Y)=>{return Q.getTaskResult(Y,J)},updateTaskStatus:async(Y,X,G)=>{let W=await Q.getTask(Y,J);if(!W)throw new L$(j$.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(B8(W.status))throw new L$(j$.InvalidParams,`Cannot update task "${Y}" from terminal status "${W.status}" to "${X}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(Y,X,G,J);let V=await Q.getTask(Y,J);if(V){let K=FV.parse({method:"notifications/tasks/status",params:V});if(await this.notification(K),B8(V.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,J)}}}}function Dx($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Ux($,J){let Q={...$};for(let Y in J){let X=Y,G=J[X];if(G===void 0)continue;let W=Q[X];if(Dx(W)&&Dx(G))Q[X]={...W,...G};else Q[X]=G}return Q}var iy=s6(CB(),1),oy=s6(cy(),1);function bG$(){let $=new iy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return oy.default($),$}class uB{constructor($){this._ajv=$??bG$()}getValidator($){let J="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(Q)=>{if(J(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(J.errors)}}}}class mB{constructor($){this._server=$}requestStream($,J,Q){return this._server.requestStream($,J,Q)}createMessageStream($,J){let Q=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!Q?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let Y=$.messages[$.messages.length-1],X=Array.isArray(Y.content)?Y.content:[Y.content],G=X.some((D)=>D.type==="tool_result"),W=$.messages.length>1?$.messages[$.messages.length-2]:void 0,V=W?Array.isArray(W.content)?W.content:[W.content]:[],K=V.some((D)=>D.type==="tool_use");if(G){if(X.some((D)=>D.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!K)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(K){let D=new Set(V.filter((N)=>N.type==="tool_use").map((N)=>N.id)),O=new Set(X.filter((N)=>N.type==="tool_result").map((N)=>N.toolUseId));if(D.size!==O.size||![...D].every((N)=>O.has(N)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},SV,J)}elicitInputStream($,J){let Q=this._server.getClientCapabilities(),Y=$.mode??"form";switch(Y){case"url":{if(!Q?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Q?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let X=Y==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:X},L5,J)}async getTask($,J){return this._server.getTask({taskId:$},J)}async getTaskResult($,J,Q){return this._server.getTaskResult({taskId:$},J,Q)}async listTasks($,J){return this._server.listTasks($?{cursor:$}:void 0,J)}async cancelTask($,J){return this._server.cancelTask({taskId:$},J)}}function ry($,J,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${J})`);switch(J){case"tools/call":if(!$.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${J})`);break;default:break}}function ty($,J,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${J})`);switch(J){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${J})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${J})`);break;default:break}}class lB extends fZ{constructor($,J){super(J);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(EV.options.map((Q,Y)=>[Q,Y])),this.isMessageIgnored=(Q,Y)=>{let X=this._loggingLevels.get(Y);return X?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(X):!1},this._capabilities=J?.capabilities??{},this._instructions=J?.instructions,this._jsonSchemaValidator=J?.jsonSchemaValidator??new uB,this.setRequestHandler(AZ,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(zZ,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(jZ,async(Q,Y)=>{let X=Y.sessionId||Y.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=Q.params,W=EV.safeParse(G);if(W.success)this._loggingLevels.set(X,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new mB(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Ux(this._capabilities,$)}setRequestHandler($,J){let Y=q8($)?.method;if(!Y)throw Error("Schema is missing a method literal");let X;if($0(Y)){let W=Y;X=W._zod?.def?.value??W.value}else{let W=Y;X=W._def?.value??W.value}if(typeof X!=="string")throw Error("Schema method literal must be a string");if(X==="tools/call"){let W=async(V,K)=>{let D=I8(q5,V);if(!D.success){let w=D.error instanceof Error?D.error.message:String(D.error);throw new L$(j$.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:O}=D.data,N=await Promise.resolve(J(V,K));if(O.task){let w=I8(z5,N);if(!w.success){let A=w.error instanceof Error?w.error.message:String(w.error);throw new L$(j$.InvalidParams,`Invalid task creation result: ${A}`)}return w.data}let M=I8(lN,N);if(!M.success){let w=M.error instanceof Error?M.error.message:String(M.error);throw new L$(j$.InvalidParams,`Invalid tools/call result: ${w}`)}return M.data};return super.setRequestHandler($,W)}return super.setRequestHandler($,J)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);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 ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);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 ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){ty(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;ry(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let J=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:Nk.includes(J)?J:OZ,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"},SN)}async createMessage($,J){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let Q=$.messages[$.messages.length-1],Y=Array.isArray(Q.content)?Q.content:[Q.content],X=Y.some((K)=>K.type==="tool_result"),G=$.messages.length>1?$.messages[$.messages.length-2]:void 0,W=G?Array.isArray(G.content)?G.content:[G.content]:[],V=W.some((K)=>K.type==="tool_use");if(X){if(Y.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!V)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(V){let K=new Set(W.filter((O)=>O.type==="tool_use").map((O)=>O.id)),D=new Set(Y.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(K.size!==D.size||![...K].every((O)=>D.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},EZ,J);return this.request({method:"sampling/createMessage",params:$},SV,J)}async elicitInput($,J){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let Y=$;return this.request({method:"elicitation/create",params:Y},L5,J)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let Y=$.mode==="form"?$:{...$,mode:"form"},X=await this.request({method:"elicitation/create",params:Y},L5,J);if(X.action==="accept"&&X.content&&Y.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(Y.requestedSchema)(X.content);if(!W.valid)throw new L$(j$.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof L$)throw G;throw new L$(j$.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return X}}}createElicitationCompletionNotifier($,J){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:$}},J)}async listRoots($,J){return this.request({method:"roots/list",params:$},SZ,J)}async sendLoggingMessage($,J){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,J))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}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 sy=Symbol.for("mcp.completable");function dB($){return!!$&&typeof $==="object"&&sy in $}function ey($){return $[sy]?.complete}var ay;(function($){$.Completable="McpCompletable"})(ay||(ay={}));var gG$=/^[A-Za-z0-9._-]{1,128}$/;function yG$($){let J=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))J.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))J.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))J.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))J.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!gG$.test($)){let Q=$.split("").filter((Y)=>!/[A-Za-z0-9._-]/.test(Y)).filter((Y,X,G)=>G.indexOf(Y)===X);return J.push(`Tool name contains invalid characters: ${Q.map((Y)=>`"${Y}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:J}}return{isValid:!0,warnings:J}}function hG$($,J){if(J.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let Q of J)console.warn(` - ${Q}`);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 pB($){let J=yG$($);return hG$($,J.warnings),J.isValid}class nB{constructor($){this._mcpServer=$}registerToolTask($,J,Q){let Y={taskSupport:"required",...J.execution};if(Y.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${$}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool($,J.title,J.description,J.inputSchema,J.outputSchema,J.annotations,Y,J._meta,Q)}}class iB{constructor($,J){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new lB($,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new nB(this)};return this._experimental}async connect($){return await this.server.connect($)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(mN)),this.server.assertCanSetRequestHandler(C8(q5)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mN,()=>({tools:Object.entries(this._registeredTools).filter(([,$])=>$.enabled).map(([$,J])=>{let Q={name:$,title:J.title,description:J.description,inputSchema:(()=>{let Y=W5(J.inputSchema);return Y?vZ(Y,{strictUnions:!0,pipeStrategy:"input"}):uG$})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let Y=W5(J.outputSchema);if(Y)Q.outputSchema=vZ(Y,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(q5,async($,J)=>{try{let Q=this._registeredTools[$.params.name];if(!Q)throw new L$(j$.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new L$(j$.InvalidParams,`Tool ${$.params.name} disabled`);let Y=!!$.params.task,X=Q.execution?.taskSupport,G="createTask"in Q.handler;if((X==="required"||X==="optional")&&!G)throw new L$(j$.InternalError,`Tool ${$.params.name} has taskSupport '${X}' but was not registered with registerToolTask`);if(X==="required"&&!Y)throw new L$(j$.MethodNotFound,`Tool ${$.params.name} requires task augmentation (taskSupport: 'required')`);if(X==="optional"&&!Y&&G)return await this.handleAutomaticTaskPolling(Q,$,J);let W=await this.validateToolInput(Q,$.params.arguments,$.params.name),V=await this.executeToolHandler(Q,W,J);if(Y)return V;return await this.validateToolOutput(Q,V,$.params.name),V}catch(Q){if(Q instanceof L$){if(Q.code===j$.UrlElicitationRequired)throw Q}return this.createToolError(Q instanceof Error?Q.message:String(Q))}}),this._toolHandlersInitialized=!0}createToolError($){return{content:[{type:"text",text:$}],isError:!0}}async validateToolInput($,J,Q){if(!$.inputSchema)return;let X=W5($.inputSchema)??$.inputSchema,G=await n3(X,J);if(!G.success){let W="error"in G?G.error:"Unknown error",V=c3(W);throw new L$(j$.InvalidParams,`Input validation error: Invalid arguments for tool ${Q}: ${V}`)}return G.data}async validateToolOutput($,J,Q){if(!$.outputSchema)return;if(!("content"in J))return;if(J.isError)return;if(!J.structuredContent)throw new L$(j$.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let Y=W5($.outputSchema),X=await n3(Y,J.structuredContent);if(!X.success){let G="error"in X?X.error:"Unknown error",W=c3(G);throw new L$(j$.InvalidParams,`Output validation error: Invalid structured content for tool ${Q}: ${W}`)}}async executeToolHandler($,J,Q){let Y=$.handler;if("createTask"in Y){if(!Q.taskStore)throw Error("No task store provided.");let G={...Q,taskStore:Q.taskStore};if($.inputSchema)return await Promise.resolve(Y.createTask(J,G));else return await Promise.resolve(Y.createTask(G))}if($.inputSchema)return await Promise.resolve(Y(J,Q));else return await Promise.resolve(Y(Q))}async handleAutomaticTaskPolling($,J,Q){if(!Q.taskStore)throw Error("No task store provided for task-capable tool.");let Y=await this.validateToolInput($,J.params.arguments,J.params.name),X=$.handler,G={...Q,taskStore:Q.taskStore},W=Y?await Promise.resolve(X.createTask(Y,G)):await Promise.resolve(X.createTask(G)),V=W.task.taskId,K=W.task,D=K.pollInterval??5000;while(K.status!=="completed"&&K.status!=="failed"&&K.status!=="cancelled"){await new Promise((N)=>setTimeout(N,D));let O=await Q.taskStore.getTask(V);if(!O)throw new L$(j$.InternalError,`Task ${V} not found during polling`);K=O}return await Q.taskStore.getTaskResult(V)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(C8(dN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(dN,async($)=>{switch($.params.ref.type){case"ref/prompt":return Tk($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return Rk($),this.handleResourceCompletion($,$.params.ref);default:throw new L$(j$.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,J){let Q=this._registeredPrompts[J.name];if(!Q)throw new L$(j$.InvalidParams,`Prompt ${J.name} not found`);if(!Q.enabled)throw new L$(j$.InvalidParams,`Prompt ${J.name} disabled`);if(!Q.argsSchema)return aV;let X=q8(Q.argsSchema)?.[$.params.argument.name];if(!dB(X))return aV;let G=ey(X);if(!G)return aV;let W=await G($.params.argument.value,$.params.context);return Jh(W)}async handleResourceCompletion($,J){let Q=Object.values(this._registeredResourceTemplates).find((G)=>G.resourceTemplate.uriTemplate.toString()===J.uri);if(!Q){if(this._registeredResources[J.uri])return aV;throw new L$(j$.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let Y=Q.resourceTemplate.completeCallback($.params.argument.name);if(!Y)return aV;let X=await Y($.params.argument.value,$.params.context);return Jh(X)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(bN)),this.server.assertCanSetRequestHandler(C8(gN)),this.server.assertCanSetRequestHandler(C8(yN)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(bN,async($,J)=>{let Q=Object.entries(this._registeredResources).filter(([X,G])=>G.enabled).map(([X,G])=>({uri:X,name:G.name,...G.metadata})),Y=[];for(let X of Object.values(this._registeredResourceTemplates)){if(!X.resourceTemplate.listCallback)continue;let G=await X.resourceTemplate.listCallback(J);for(let W of G.resources)Y.push({...X.metadata,...W})}return{resources:[...Q,...Y]}}),this.server.setRequestHandler(gN,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([J,Q])=>({name:J,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(yN,async($,J)=>{let Q=new URL($.params.uri),Y=this._registeredResources[Q.toString()];if(Y){if(!Y.enabled)throw new L$(j$.InvalidParams,`Resource ${Q} disabled`);return Y.readCallback(Q,J)}for(let X of Object.values(this._registeredResourceTemplates)){let G=X.resourceTemplate.uriTemplate.match(Q.toString());if(G)return X.readCallback(Q,G,J)}throw new L$(j$.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(hN)),this.server.assertCanSetRequestHandler(C8(uN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,J])=>{return{name:$,title:J.title,description:J.description,arguments:J.argsSchema?mG$(J.argsSchema):void 0}})})),this.server.setRequestHandler(uN,async($,J)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new L$(j$.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new L$(j$.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=W5(Q.argsSchema),X=await n3(Y,$.params.arguments);if(!X.success){let V="error"in X?X.error:"Unknown error",K=c3(V);throw new L$(j$.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${K}`)}let G=X.data,W=Q.callback;return await Promise.resolve(W(G,J))}else{let Y=Q.callback;return await Promise.resolve(Y(J))}}),this._promptHandlersInitialized=!0}resource($,J,...Q){let Y;if(typeof Q[0]==="object")Y=Q.shift();let X=Q[0];if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let G=this._createRegisteredResource($,void 0,J,Y,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let G=this._createRegisteredResourceTemplate($,void 0,J,Y,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}}registerResource($,J,Q,Y){if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let X=this._createRegisteredResource($,Q.title,J,Q,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),X}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let X=this._createRegisteredResourceTemplate($,Q.title,J,Q,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),X}}_createRegisteredResource($,J,Q,Y,X){let G={name:$,title:J,metadata:Y,readCallback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({uri:null}),update:(W)=>{if(typeof W.uri<"u"&&W.uri!==Q){if(delete this._registeredResources[Q],W.uri)this._registeredResources[W.uri]=G}if(typeof W.name<"u")G.name=W.name;if(typeof W.title<"u")G.title=W.title;if(typeof W.metadata<"u")G.metadata=W.metadata;if(typeof W.callback<"u")G.readCallback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendResourceListChanged()}};return this._registeredResources[Q]=G,G}_createRegisteredResourceTemplate($,J,Q,Y,X){let G={resourceTemplate:Q,title:J,metadata:Y,readCallback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(K)=>{if(typeof K.name<"u"&&K.name!==$){if(delete this._registeredResourceTemplates[$],K.name)this._registeredResourceTemplates[K.name]=G}if(typeof K.title<"u")G.title=K.title;if(typeof K.template<"u")G.resourceTemplate=K.template;if(typeof K.metadata<"u")G.metadata=K.metadata;if(typeof K.callback<"u")G.readCallback=K.callback;if(typeof K.enabled<"u")G.enabled=K.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[$]=G;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((K)=>!!Q.completeCallback(K)))this.setCompletionRequestHandler();return G}_createRegisteredPrompt($,J,Q,Y,X){let G={title:J,description:Q,argsSchema:Y===void 0?void 0:iX(Y),callback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(W)=>{if(typeof W.name<"u"&&W.name!==$){if(delete this._registeredPrompts[$],W.name)this._registeredPrompts[W.name]=G}if(typeof W.title<"u")G.title=W.title;if(typeof W.description<"u")G.description=W.description;if(typeof W.argsSchema<"u")G.argsSchema=iX(W.argsSchema);if(typeof W.callback<"u")G.callback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[$]=G,Y){if(Object.values(Y).some((V)=>{let K=V instanceof H5?V._def?.innerType:V;return dB(K)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool($,J,Q,Y,X,G,W,V,K){pB($);let D={title:J,description:Q,inputSchema:$h(Y),outputSchema:$h(X),annotations:G,execution:W,_meta:V,handler:K,enabled:!0,disable:()=>D.update({enabled:!1}),enable:()=>D.update({enabled:!0}),remove:()=>D.update({name:null}),update:(O)=>{if(typeof O.name<"u"&&O.name!==$){if(typeof O.name==="string")pB(O.name);if(delete this._registeredTools[$],O.name)this._registeredTools[O.name]=D}if(typeof O.title<"u")D.title=O.title;if(typeof O.description<"u")D.description=O.description;if(typeof O.paramsSchema<"u")D.inputSchema=iX(O.paramsSchema);if(typeof O.outputSchema<"u")D.outputSchema=iX(O.outputSchema);if(typeof O.callback<"u")D.handler=O.callback;if(typeof O.annotations<"u")D.annotations=O.annotations;if(typeof O._meta<"u")D._meta=O._meta;if(typeof O.enabled<"u")D.enabled=O.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=D,this.setToolRequestHandlers(),this.sendToolListChanged(),D}tool($,...J){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let Q,Y,X,G;if(typeof J[0]==="string")Q=J.shift();if(J.length>1){let V=J[0];if(cB(V)){if(Y=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!cB(J[0]))G=J.shift()}else if(typeof V==="object"&&V!==null){if(Object.values(V).some((K)=>typeof K==="object"&&K!==null))throw Error(`Tool ${$} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);G=J.shift()}}let W=J[0];return this._createRegisteredTool($,void 0,Q,Y,X,G,{taskSupport:"forbidden"},void 0,W)}registerTool($,J,Q){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let{title:Y,description:X,inputSchema:G,outputSchema:W,annotations:V,_meta:K}=J;return this._createRegisteredTool($,Y,X,G,W,V,{taskSupport:"forbidden"},K,Q)}prompt($,...J){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let Q;if(typeof J[0]==="string")Q=J.shift();let Y;if(J.length>1)Y=J.shift();let X=J[0],G=this._createRegisteredPrompt($,void 0,Q,Y,X);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}registerPrompt($,J,Q){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let{title:Y,description:X,argsSchema:G}=J,W=this._createRegisteredPrompt($,Y,X,G,Q);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage($,J){return this.server.sendLoggingMessage($,J)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var uG$={type:"object",properties:{}};function Qh($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function Xh($){return"_def"in $||"_zod"in $||Qh($)}function cB($){if(typeof $!=="object"||$===null)return!1;if(Xh($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(Qh)}function $h($){if(!$)return;if(cB($))return iX($);if(!Xh($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function mG$($){let J=q8($);if(!J)return[];return Object.entries(J).map(([Q,Y])=>{let X=aP(Y),G=sP(Y);return{name:Q,description:X,required:!G}})}function C8($){let Q=q8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=i3(Q);if(typeof Y==="string")return Y;throw Error("Schema method literal must be a string")}function Jh($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var aV={completion:{values:[],hasMore:!1}};import Gh from"node:process";class oB{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
135
135
  `);if($===-1)return null;let J=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),lG$(J)}clear(){this._buffer=void 0}}function lG$($){return Lk.parse(JSON.parse($))}function Yh($){return JSON.stringify($)+`
136
- `}class rB{constructor($=Gh.stdin,J=Gh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new oB,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{this.onerror?.(Q)}}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 $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}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($){return new Promise((J)=>{let Q=Yh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var CM={name:"@0xmonaco/mcp-server",version:"0.8.15",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"0.8.15","@0xmonaco/types":"0.8.15","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var pG$={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function P8($=process.env){let J=$.MONACO_PRIVATE_KEY||null;if(J&&!J.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let Q=$.MONACO_CLIENT_ID||null;if(J&&!Q)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let Y=["mainnet","development","staging","local"],X=$.MONACO_NETWORK||"mainnet";if(!Y.includes(X))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}. Got: "${X}".`);let G=X,W=$.MONACO_RPC_URL||pG$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function nG$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function x5($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>x5(Q));let J={};for(let[Q,Y]of Object.entries($))J[nG$(Q)]=typeof Y==="object"&&Y!==null?x5(Y):Y;return J}W0();QK();W0();MF();w9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ZJ=BigInt(0),D1=BigInt(1),ch=BigInt(2),M7$=BigInt(8),w7$={zip215:!0};function H7$($){let J=GK($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function ih($){let J=H7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:V,h:K}=J,D=ch<<BigInt(V*8)-D1,O=Q.create,N=HQ(J.n,J.nBitLength);function M(_,C){let m=Q.sqr(_),K$=Q.sqr(C),D$=Q.add(Q.mul(J.a,m),K$),A$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(m,K$)));return Q.eql(D$,A$)}if(!M(J.Gx,J.Gy))throw Error("bad curve params: generator point");let w=J.uvRatio||((_,C)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(C))}}catch(m){return{isValid:!1,value:ZJ}}}),A=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,C,m)=>{if(qJ("phflag",m),C.length||m)throw Error("Contexts/pre-hash are not supported");return _});function F(_,C,m=!1){let K$=m?D1:ZJ;V1("coordinate "+_,C,K$,D)}function L(_){if(!(_ instanceof Z))throw Error("ExtendedPoint expected")}let E=h5((_,C)=>{let{ex:m,ey:K$,ez:D$}=_,A$=_.is0();if(C==null)C=A$?M7$:Q.inv(D$);let R$=O(m*C),I$=O(K$*C),W4=O(D$*C);if(A$)return{x:ZJ,y:D1};if(W4!==D1)throw Error("invZ was invalid");return{x:R$,y:I$}}),B=h5((_)=>{let{a:C,d:m}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:K$,ey:D$,ez:A$,et:R$}=_,I$=O(K$*K$),W4=O(D$*D$),L4=O(A$*A$),w4=O(L4*L4),d4=O(I$*C),a4=O(L4*O(d4+W4)),Y6=O(w4+O(m*O(I$*W4)));if(a4!==Y6)throw Error("bad point: equation left != right (1)");let d6=O(K$*D$),s4=O(A$*R$);if(d6!==s4)throw Error("bad point: equation left != right (2)");return!0});class Z{constructor(_,C,m,K$){F("x",_),F("y",C),F("z",m,!0),F("t",K$),this.ex=_,this.ey=C,this.ez=m,this.et=K$,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof Z)throw Error("extended point not allowed");let{x:C,y:m}=_||{};return F("x",C),F("y",m),new Z(C,m,D1,O(C*m))}static normalizeZ(_){let C=wQ(Q,_.map((m)=>m.ez));return _.map((m,K$)=>m.toAffine(C[K$])).map(Z.fromAffine)}static msm(_,C){return uM(Z,N,_,C)}_setWindowSize(_){x.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){L(_);let{ex:C,ey:m,ez:K$}=this,{ex:D$,ey:A$,ez:R$}=_,I$=O(C*R$),W4=O(D$*K$),L4=O(m*R$),w4=O(A$*K$);return I$===W4&&L4===w4}is0(){return this.equals(Z.ZERO)}negate(){return new Z(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:_}=J,{ex:C,ey:m,ez:K$}=this,D$=O(C*C),A$=O(m*m),R$=O(ch*O(K$*K$)),I$=O(_*D$),W4=C+m,L4=O(O(W4*W4)-D$-A$),w4=I$+A$,d4=w4-R$,a4=I$-A$,Y6=O(L4*d4),d6=O(w4*a4),s4=O(L4*a4),L1=O(d4*w4);return new Z(Y6,d6,L1,s4)}add(_){L(_);let{a:C,d:m}=J,{ex:K$,ey:D$,ez:A$,et:R$}=this,{ex:I$,ey:W4,ez:L4,et:w4}=_,d4=O(K$*I$),a4=O(D$*W4),Y6=O(R$*m*w4),d6=O(A$*L4),s4=O((K$+D$)*(I$+W4)-d4-a4),L1=d6-Y6,p6=d6+Y6,dQ=O(a4-C*d4),C7=O(s4*L1),QY=O(p6*dQ),fD=O(s4*dQ),q0=O(L1*p6);return new Z(C7,QY,q0,fD)}subtract(_){return this.add(_.negate())}wNAF(_){return x.wNAFCached(this,_,Z.normalizeZ)}multiply(_){let C=_;V1("scalar",C,D1,Y);let{p:m,f:K$}=this.wNAF(C);return Z.normalizeZ([m,K$])[0]}multiplyUnsafe(_,C=Z.ZERO){let m=_;if(V1("scalar",m,ZJ,Y),m===ZJ)return T;if(this.is0()||m===D1)return this;return x.wNAFCachedUnsafe(this,m,Z.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(K).is0()}isTorsionFree(){return x.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===D1)return this;return this.multiplyUnsafe(_)}static fromHex(_,C=!1){let{d:m,a:K$}=J,D$=Q.BYTES;_=A4("pointHex",_,D$),qJ("zip215",C);let A$=_.slice(),R$=_[D$-1];A$[D$-1]=R$&-129;let I$=D9(A$),W4=C?D:Q.ORDER;V1("pointHex.y",I$,ZJ,W4);let L4=O(I$*I$),w4=O(L4-D1),d4=O(m*L4-K$),{isValid:a4,value:Y6}=w(w4,d4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d6=(Y6&D1)===D1,s4=(R$&128)!==0;if(!C&&Y6===ZJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d6)Y6=O(-Y6);return Z.fromAffine({x:Y6,y:I$})}static fromPrivateKey(_){let{scalar:C}=R(_);return j.multiply(C)}toRawBytes(){let{x:_,y:C}=this.toAffine(),m=y5(C,Q.BYTES);return m[m.length-1]|=_&D1?128:0,m}toHex(){return f8(this.toRawBytes())}}Z.BASE=new Z(J.Gx,J.Gy,D1,O(J.Gx*J.Gy)),Z.ZERO=new Z(ZJ,D1,D1,ZJ);let{BASE:j,ZERO:T}=Z,x=hM(Z,V*8);function f(_){return Y4(_,Y)}function u(_){return f(D9(_))}function R(_){let C=Q.BYTES;_=A4("private key",_,C);let m=A4("hashed private key",G(_),2*C),K$=A(m.slice(0,C)),D$=m.slice(C,2*C),A$=u(K$);return{head:K$,prefix:D$,scalar:A$}}function d(_){let{head:C,prefix:m,scalar:K$}=R(_),D$=j.multiply(K$),A$=D$.toRawBytes();return{head:C,prefix:m,scalar:K$,point:D$,pointBytes:A$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...C){let m=A6(...C);return u(G(q(m,A4("context",_),!!X)))}function c(_,C,m={}){if(_=A4("message",_),X)_=X(_);let{prefix:K$,scalar:D$,pointBytes:A$}=d(C),R$=Y$(m.context,K$,_),I$=j.multiply(R$).toRawBytes(),W4=Y$(m.context,I$,A$,_),L4=f(R$+W4*D$);V1("signature.s",L4,ZJ,Y);let w4=A6(I$,y5(L4,Q.BYTES));return A4("result",w4,Q.BYTES*2)}let k=w7$;function n(_,C,m,K$=k){let{context:D$,zip215:A$}=K$,R$=Q.BYTES;if(_=A4("signature",_,2*R$),C=A4("message",C),m=A4("publicKey",m,R$),A$!==void 0)qJ("zip215",A$);if(X)C=X(C);let I$=D9(_.slice(R$,2*R$)),W4,L4,w4;try{W4=Z.fromHex(m,A$),L4=Z.fromHex(_.slice(0,R$),A$),w4=j.multiplyUnsafe(I$)}catch(Y6){return!1}if(!A$&&W4.isSmallOrder())return!1;let d4=Y$(D$,L4.toRawBytes(),W4.toRawBytes(),C);return L4.add(W4.multiplyUnsafe(d4)).subtract(w4).clearCofactor().equals(Z.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:n,ExtendedPoint:Z,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,C=Z.BASE){return C._setWindowSize(_),C.multiply(BigInt(3)),C}}}}w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var wF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),sh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c2$=BigInt(0),L7$=BigInt(1),eh=BigInt(2),i2$=BigInt(3),Z7$=BigInt(5),B7$=BigInt(8);function F7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=wF,V=$*$%G*$%G,K=u4(V,eh,G)*V%G,D=u4(K,L7$,G)*$%G,O=u4(D,Z7$,G)*D%G,N=u4(O,J,G)*O%G,M=u4(N,Q,G)*N%G,w=u4(M,Y,G)*M%G,A=u4(w,X,G)*w%G,q=u4(A,X,G)*w%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,eh,G)*$%G,b2:V}}function j7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function E7$($,J){let Q=wF,Y=Y4(J*J*J,Q),X=Y4(Y*Y*J,Q),G=F7$($*X).pow_p_5_8,W=Y4($*Y*G,Q),V=Y4(J*W*W,Q),K=W,D=Y4(W*sh,Q),O=V===$,N=V===Y4(-$,Q),M=V===Y4(-$*sh,Q);if(O)W=K;if(N||M)W=D;if(hh(W,Q))W=Y4(-W,Q);return{isValid:O||N,value:W}}var $u=(()=>HQ(wF,void 0,!0))(),S7$=(()=>({a:$u.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:$u,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:B7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_h,randomBytes:b5,adjustScalarBytes:j7$,uvRatio:E7$}))(),mM=(()=>ih(S7$))();QK();W0();function lM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=mM.utils.randomPrivateKey();return{publicKey:mM.getPublicKey($),privateKey:$}}function dM($){return Y9($.publicKey)}function pM($){return Y9($.privateKey)}function Ju($,J){return{publicKey:sV($),privateKey:sV(J)}}function Qu($){return Y9(OQ($))}function Xu($,J,Q,Y){return`${$.toUpperCase()}
136
+ `}class rB{constructor($=Gh.stdin,J=Gh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new oB,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{this.onerror?.(Q)}}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 $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}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($){return new Promise((J)=>{let Q=Yh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var CM={name:"@0xmonaco/mcp-server",version:"0.8.16",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"0.8.16","@0xmonaco/types":"0.8.16","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var pG$={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function P8($=process.env){let J=$.MONACO_PRIVATE_KEY||null;if(J&&!J.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let Q=$.MONACO_CLIENT_ID||null;if(J&&!Q)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let Y=["mainnet","development","staging","local"],X=$.MONACO_NETWORK||"mainnet";if(!Y.includes(X))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}. Got: "${X}".`);let G=X,W=$.MONACO_RPC_URL||pG$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function nG$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function x5($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>x5(Q));let J={};for(let[Q,Y]of Object.entries($))J[nG$(Q)]=typeof Y==="object"&&Y!==null?x5(Y):Y;return J}W0();QK();W0();MF();w9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ZJ=BigInt(0),D1=BigInt(1),ch=BigInt(2),M7$=BigInt(8),w7$={zip215:!0};function H7$($){let J=GK($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function ih($){let J=H7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:V,h:K}=J,D=ch<<BigInt(V*8)-D1,O=Q.create,N=HQ(J.n,J.nBitLength);function M(_,C){let m=Q.sqr(_),K$=Q.sqr(C),D$=Q.add(Q.mul(J.a,m),K$),A$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(m,K$)));return Q.eql(D$,A$)}if(!M(J.Gx,J.Gy))throw Error("bad curve params: generator point");let w=J.uvRatio||((_,C)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(C))}}catch(m){return{isValid:!1,value:ZJ}}}),A=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,C,m)=>{if(qJ("phflag",m),C.length||m)throw Error("Contexts/pre-hash are not supported");return _});function F(_,C,m=!1){let K$=m?D1:ZJ;V1("coordinate "+_,C,K$,D)}function L(_){if(!(_ instanceof Z))throw Error("ExtendedPoint expected")}let E=h5((_,C)=>{let{ex:m,ey:K$,ez:D$}=_,A$=_.is0();if(C==null)C=A$?M7$:Q.inv(D$);let R$=O(m*C),I$=O(K$*C),W4=O(D$*C);if(A$)return{x:ZJ,y:D1};if(W4!==D1)throw Error("invZ was invalid");return{x:R$,y:I$}}),B=h5((_)=>{let{a:C,d:m}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:K$,ey:D$,ez:A$,et:R$}=_,I$=O(K$*K$),W4=O(D$*D$),L4=O(A$*A$),w4=O(L4*L4),d4=O(I$*C),a4=O(L4*O(d4+W4)),Y6=O(w4+O(m*O(I$*W4)));if(a4!==Y6)throw Error("bad point: equation left != right (1)");let d6=O(K$*D$),s4=O(A$*R$);if(d6!==s4)throw Error("bad point: equation left != right (2)");return!0});class Z{constructor(_,C,m,K$){F("x",_),F("y",C),F("z",m,!0),F("t",K$),this.ex=_,this.ey=C,this.ez=m,this.et=K$,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof Z)throw Error("extended point not allowed");let{x:C,y:m}=_||{};return F("x",C),F("y",m),new Z(C,m,D1,O(C*m))}static normalizeZ(_){let C=wQ(Q,_.map((m)=>m.ez));return _.map((m,K$)=>m.toAffine(C[K$])).map(Z.fromAffine)}static msm(_,C){return uM(Z,N,_,C)}_setWindowSize(_){x.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){L(_);let{ex:C,ey:m,ez:K$}=this,{ex:D$,ey:A$,ez:R$}=_,I$=O(C*R$),W4=O(D$*K$),L4=O(m*R$),w4=O(A$*K$);return I$===W4&&L4===w4}is0(){return this.equals(Z.ZERO)}negate(){return new Z(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:_}=J,{ex:C,ey:m,ez:K$}=this,D$=O(C*C),A$=O(m*m),R$=O(ch*O(K$*K$)),I$=O(_*D$),W4=C+m,L4=O(O(W4*W4)-D$-A$),w4=I$+A$,d4=w4-R$,a4=I$-A$,Y6=O(L4*d4),d6=O(w4*a4),s4=O(L4*a4),L1=O(d4*w4);return new Z(Y6,d6,L1,s4)}add(_){L(_);let{a:C,d:m}=J,{ex:K$,ey:D$,ez:A$,et:R$}=this,{ex:I$,ey:W4,ez:L4,et:w4}=_,d4=O(K$*I$),a4=O(D$*W4),Y6=O(R$*m*w4),d6=O(A$*L4),s4=O((K$+D$)*(I$+W4)-d4-a4),L1=d6-Y6,p6=d6+Y6,dQ=O(a4-C*d4),C7=O(s4*L1),QY=O(p6*dQ),fD=O(s4*dQ),q0=O(L1*p6);return new Z(C7,QY,q0,fD)}subtract(_){return this.add(_.negate())}wNAF(_){return x.wNAFCached(this,_,Z.normalizeZ)}multiply(_){let C=_;V1("scalar",C,D1,Y);let{p:m,f:K$}=this.wNAF(C);return Z.normalizeZ([m,K$])[0]}multiplyUnsafe(_,C=Z.ZERO){let m=_;if(V1("scalar",m,ZJ,Y),m===ZJ)return T;if(this.is0()||m===D1)return this;return x.wNAFCachedUnsafe(this,m,Z.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(K).is0()}isTorsionFree(){return x.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===D1)return this;return this.multiplyUnsafe(_)}static fromHex(_,C=!1){let{d:m,a:K$}=J,D$=Q.BYTES;_=A4("pointHex",_,D$),qJ("zip215",C);let A$=_.slice(),R$=_[D$-1];A$[D$-1]=R$&-129;let I$=D9(A$),W4=C?D:Q.ORDER;V1("pointHex.y",I$,ZJ,W4);let L4=O(I$*I$),w4=O(L4-D1),d4=O(m*L4-K$),{isValid:a4,value:Y6}=w(w4,d4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d6=(Y6&D1)===D1,s4=(R$&128)!==0;if(!C&&Y6===ZJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d6)Y6=O(-Y6);return Z.fromAffine({x:Y6,y:I$})}static fromPrivateKey(_){let{scalar:C}=R(_);return j.multiply(C)}toRawBytes(){let{x:_,y:C}=this.toAffine(),m=y5(C,Q.BYTES);return m[m.length-1]|=_&D1?128:0,m}toHex(){return f8(this.toRawBytes())}}Z.BASE=new Z(J.Gx,J.Gy,D1,O(J.Gx*J.Gy)),Z.ZERO=new Z(ZJ,D1,D1,ZJ);let{BASE:j,ZERO:T}=Z,x=hM(Z,V*8);function f(_){return Y4(_,Y)}function u(_){return f(D9(_))}function R(_){let C=Q.BYTES;_=A4("private key",_,C);let m=A4("hashed private key",G(_),2*C),K$=A(m.slice(0,C)),D$=m.slice(C,2*C),A$=u(K$);return{head:K$,prefix:D$,scalar:A$}}function d(_){let{head:C,prefix:m,scalar:K$}=R(_),D$=j.multiply(K$),A$=D$.toRawBytes();return{head:C,prefix:m,scalar:K$,point:D$,pointBytes:A$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...C){let m=A6(...C);return u(G(q(m,A4("context",_),!!X)))}function c(_,C,m={}){if(_=A4("message",_),X)_=X(_);let{prefix:K$,scalar:D$,pointBytes:A$}=d(C),R$=Y$(m.context,K$,_),I$=j.multiply(R$).toRawBytes(),W4=Y$(m.context,I$,A$,_),L4=f(R$+W4*D$);V1("signature.s",L4,ZJ,Y);let w4=A6(I$,y5(L4,Q.BYTES));return A4("result",w4,Q.BYTES*2)}let k=w7$;function n(_,C,m,K$=k){let{context:D$,zip215:A$}=K$,R$=Q.BYTES;if(_=A4("signature",_,2*R$),C=A4("message",C),m=A4("publicKey",m,R$),A$!==void 0)qJ("zip215",A$);if(X)C=X(C);let I$=D9(_.slice(R$,2*R$)),W4,L4,w4;try{W4=Z.fromHex(m,A$),L4=Z.fromHex(_.slice(0,R$),A$),w4=j.multiplyUnsafe(I$)}catch(Y6){return!1}if(!A$&&W4.isSmallOrder())return!1;let d4=Y$(D$,L4.toRawBytes(),W4.toRawBytes(),C);return L4.add(W4.multiplyUnsafe(d4)).subtract(w4).clearCofactor().equals(Z.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:n,ExtendedPoint:Z,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,C=Z.BASE){return C._setWindowSize(_),C.multiply(BigInt(3)),C}}}}w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var wF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),sh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c2$=BigInt(0),L7$=BigInt(1),eh=BigInt(2),i2$=BigInt(3),Z7$=BigInt(5),B7$=BigInt(8);function F7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=wF,V=$*$%G*$%G,K=u4(V,eh,G)*V%G,D=u4(K,L7$,G)*$%G,O=u4(D,Z7$,G)*D%G,N=u4(O,J,G)*O%G,M=u4(N,Q,G)*N%G,w=u4(M,Y,G)*M%G,A=u4(w,X,G)*w%G,q=u4(A,X,G)*w%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,eh,G)*$%G,b2:V}}function j7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function E7$($,J){let Q=wF,Y=Y4(J*J*J,Q),X=Y4(Y*Y*J,Q),G=F7$($*X).pow_p_5_8,W=Y4($*Y*G,Q),V=Y4(J*W*W,Q),K=W,D=Y4(W*sh,Q),O=V===$,N=V===Y4(-$,Q),M=V===Y4(-$*sh,Q);if(O)W=K;if(N||M)W=D;if(hh(W,Q))W=Y4(-W,Q);return{isValid:O||N,value:W}}var $u=(()=>HQ(wF,void 0,!0))(),S7$=(()=>({a:$u.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:$u,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:B7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_h,randomBytes:b5,adjustScalarBytes:j7$,uvRatio:E7$}))(),mM=(()=>ih(S7$))();QK();W0();function lM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=mM.utils.randomPrivateKey();return{publicKey:mM.getPublicKey($),privateKey:$}}function dM($){return Y9($.publicKey)}function pM($){return Y9($.privateKey)}function Ju($,J){return{publicKey:sV($),privateKey:sV(J)}}function Qu($){return Y9(OQ($))}function Xu($,J,Q,Y){return`${$.toUpperCase()}
137
137
  ${J}
138
138
  ${Q}
139
139
  ${Y}`}function Yu($,J){return`WS-AUTH
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/mcp-server",
3
- "version": "0.8.15",
3
+ "version": "0.8.16",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  },
26
26
  "author": "@codebycarson",
27
27
  "dependencies": {
28
- "@0xmonaco/core": "0.8.15",
29
- "@0xmonaco/types": "0.8.15",
28
+ "@0xmonaco/core": "0.8.16",
29
+ "@0xmonaco/types": "0.8.16",
30
30
  "@modelcontextprotocol/sdk": "^1.29.0",
31
31
  "node-fetch": "^3.3.2",
32
32
  "viem": "^2.53.1",