@0xmonaco/mcp-server 1.0.38-develop.ebf8e8c → 1.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- 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[D]}\r
|
|
134
134
|
]`;continue}if(X+=Y[D],Y[D]==="\\")G=!0;else if(W&&Y[D]==="]")W=!1;else if(!W&&Y[D]==="[")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===Y$.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]})??d4(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===Y$.ZodString&&$.keyType._def.checks?.length){let{type:Y,...X}=cN($.keyType._def,J);return{...Q,propertyNames:X}}else if($.keyType?._def.typeName===Y$.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===Y$.ZodBranded&&$.keyType._def.type._def.typeName===Y$.ZodString&&$.keyType._def.type._def.checks?.length){let{type:Y,...X}=nN($.keyType._def,J);return{...Q,propertyNames:X}}return Q}function Ix($,J){if(J.mapStrategy==="record")return iN($,J);let Q=P$($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||d4(J),Y=P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||d4(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,Y],minItems:2,maxItems:2}}}function Lx($){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 Bx($){return $.target==="openAi"?void 0:{not:d4({...$,currentPath:[...$.currentPath,"not"]})}}function Fx($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var SV={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ex($,J){if(J.target==="openApi3")return jx($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in SV)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((X,G)=>{let W=SV[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 jx($,J)}var jx=($,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 _x($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:SV[$.innerType._def.typeName],nullable:!0};return{type:[SV[$.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 Sx($,J){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",hL(Q,"type",Y.message,J);break;case"min":if(J.target==="jsonSchema7")if(Y.inclusive)Q4(Q,"minimum",Y.value,Y.message,J);else Q4(Q,"exclusiveMinimum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;Q4(Q,"minimum",Y.value,Y.message,J)}break;case"max":if(J.target==="jsonSchema7")if(Y.inclusive)Q4(Q,"maximum",Y.value,Y.message,J);else Q4(Q,"exclusiveMaximum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;Q4(Q,"maximum",Y.value,Y.message,J)}break;case"multipleOf":Q4(Q,"multipleOf",Y.value,Y.message,J);break}return Q}function Rx($,J){let Q=J.target==="openAi",Y={type:"object",properties:{}},X=[],G=$.shape();for(let V in G){let D=G[V];if(D===void 0||D._def===void 0)continue;let K=QQ$(D);if(K&&Q){if(D._def.typeName==="ZodOptional")D=D._def.innerType;if(!D.isNullable())D=D.nullable();K=!1}let O=P$(D._def,{...J,currentPath:[...J.currentPath,"properties",V],propertyPath:[...J.currentPath,"properties",V]});if(O===void 0)continue;if(Y.properties[V]=O,!K)X.push(V)}if(X.length)Y.required=X;let W=JQ$($,J);if(W!==void 0)Y.additionalProperties=W;return Y}function JQ$($,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 QQ$($){try{return $.isOptional()}catch{return!0}}var Tx=($,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:d4(J)},Q]}:d4(J)};var Cx=($,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 vx($,J){return P$($.type._def,J)}function Px($,J){let Y={type:"array",uniqueItems:!0,items:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)Q4(Y,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)Q4(Y,"maxItems",$.maxSize.value,$.maxSize.message,J);return Y}function kx($,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 xx($){return{not:d4($)}}function fx($){return d4($)}var bx=($,J)=>{return P$($.innerType._def,J)};var gx=($,J,Q)=>{switch(J){case Y$.ZodString:return cN($,Q);case Y$.ZodNumber:return Sx($,Q);case Y$.ZodObject:return Rx($,Q);case Y$.ZodBigInt:return Ox($,Q);case Y$.ZodBoolean:return Nx();case Y$.ZodDate:return uL($,Q);case Y$.ZodUndefined:return xx(Q);case Y$.ZodNull:return Fx(Q);case Y$.ZodArray:return Ux($,Q);case Y$.ZodUnion:case Y$.ZodDiscriminatedUnion:return Ex($,Q);case Y$.ZodIntersection:return Ax($,Q);case Y$.ZodTuple:return kx($,Q);case Y$.ZodRecord:return iN($,Q);case Y$.ZodLiteral:return qx($,Q);case Y$.ZodEnum:return zx($);case Y$.ZodNativeEnum:return Lx($);case Y$.ZodNullable:return _x($,Q);case Y$.ZodOptional:return Tx($,Q);case Y$.ZodMap:return Ix($,Q);case Y$.ZodSet:return Px($,Q);case Y$.ZodLazy:return()=>$.getter()._def;case Y$.ZodPromise:return vx($,Q);case Y$.ZodNaN:case Y$.ZodNever:return Bx(Q);case Y$.ZodEffects:return Hx($,Q);case Y$.ZodAny:return d4(Q);case Y$.ZodUnknown:return fx(Q);case Y$.ZodDefault:return wx($,Q);case Y$.ZodBranded:return nN($,Q);case Y$.ZodReadonly:return bx($,Q);case Y$.ZodCatch:return Mx($,Q);case Y$.ZodPipeline:return Cx($,Q);case Y$.ZodFunction:case Y$.ZodVoid:case Y$.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!==Vx)return V}if(Y&&!Q){let V=XQ$(Y,J);if(V!==void 0)return V}let X={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,X);let G=gx($,$.typeName,J),W=typeof G==="function"?P$(G(),J):G;if(W)YQ$($,J,W);if(J.postProcess){let V=J.postProcess(W,$,J);return X.jsonSchema=W,V}return X.jsonSchema=W,W}var XQ$=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:dN(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`),d4(J);return J.$refStrategy==="seen"?d4(J):void 0}}},YQ$=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var pL=($,J)=>{let Q=Kx(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((D,[K,O])=>({...D,[K]:P$(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,K]},!0)??d4(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)??d4(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 GQ$($){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 dL($,J){if(Q6($))return iX($,{target:GQ$(J?.target),io:J?.pipeStrategy??"input"});return pL($,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function nL($){let Q=L8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=iO(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function cL($,J){let Q=I8($,J);if(!Q.success)throw Q.error;return Q.data}var WQ$=60000;class iL{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(SN,(J)=>{this._oncancel(J)}),this.setNotificationHandler(TN,(J)=>{this._onprogress(J)}),this.setRequestHandler(RN,(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 j$(S$.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(PN,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,D=V.id,K=this._requestResolvers.get(D);if(K)if(this._requestResolvers.delete(D),W.type==="response")K(V);else{let O=V,N=new j$(O.error.code,O.error.message,O.error.data);K(N)}else{let O=W.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${D}`))}continue}await this._transport?.send(W.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(X,Q.sessionId);if(!G)throw new j$(S$.InvalidParams,`Task not found: ${X}`);if(!j8(G.status))return await this._waitForTaskUpdate(X,Q.signal),await Y();if(j8(G.status)){let W=await this._taskStore.getTaskResult(X,Q.sessionId);return this._clearTaskQueue(X),{...W,_meta:{...W._meta,[F8]:{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 j$(S$.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 j$(S$.InvalidParams,`Task not found: ${J.params.taskId}`);if(j8(Y.status))throw new j$(S$.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 j$(S$.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...X}}catch(Y){if(Y instanceof j$)throw Y;throw new j$(S$.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($),j$.fromError(S$.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),qV(X)||ok(X))this._onresponse(X);else if(EL(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=j$.fromError(S$.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?.[F8]?.taskId;if(Q===void 0){let K={jsonrpc:"2.0",id:$.id,error:{code:S$.MethodNotFound,message:"Method not found"}};if(X&&this._taskMessageQueue)this._enqueueTaskMessage(X,{type:"error",message:K,timestamp:Date.now()},Y?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else Y?.send(K).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let W=dk($.params)?$.params.task:void 0,V=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,D={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(K)=>{if(G.signal.aborted)return;let O={relatedRequestId:$.id};if(X)O.relatedTask={taskId:X};await this.notification(K,O)},sendRequest:async(K,O,N)=>{if(G.signal.aborted)throw new j$(S$.ConnectionClosed,"Request was cancelled");let w={...N,relatedRequestId:$.id};if(X&&!w.relatedTask)w.relatedTask={taskId:X};let H=w.relatedTask?.taskId??X;if(H&&V)await V.updateTaskStatus(H,"input_required");return await this.request(K,O,w)},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($,D)).then(async(K)=>{if(G.signal.aborted)return;let O={result:K,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(K)=>{if(G.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(K.code)?K.code:S$.InternalError,message:K.message??"Internal error",...K.data!==void 0&&{data:K.data}}};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"error",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)}).catch((K)=>this._onerror(Error(`Failed to send response: ${K}`))).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),qV($))Q($);else{let G=new j$($.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(qV($)&&$.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(qV($))Y($);else{let G=j$.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 j$?G:new j$(S$.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 j$(S$.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:X},Q);if(yield{type:"taskStatus",task:W},j8(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 j$(S$.InternalError,`Task ${X} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new j$(S$.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((D)=>setTimeout(D,V)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof j$?G:new j$(S$.InternalError,String(G))}}}request($,J,Q){let{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G,task:W,relatedTask:V}=Q??{};return new Promise((D,K)=>{let O=(I)=>{K(I)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(I){O(I);return}Q?.signal?.throwIfAborted();let N=this._requestMessageId++,w={...$,jsonrpc:"2.0",id:N};if(Q?.onprogress)this._progressHandlers.set(N,Q.onprogress),w.params={...$.params,_meta:{...$.params?._meta||{},progressToken:N}};if(W)w.params={...w.params,task:W};if(V)w.params={...w.params,_meta:{...w.params?._meta||{},[F8]:V}};let H=(I)=>{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(I)}},{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((B)=>this._onerror(Error(`Failed to send cancellation: ${B}`)));let E=I instanceof j$?I:new j$(S$.RequestTimeout,String(I));K(E)};this._responseHandlers.set(N,(I)=>{if(Q?.signal?.aborted)return;if(I instanceof Error)return K(I);try{let E=I8(J,I.result);if(!E.success)K(E.error);else D(E.data)}catch(E){K(E)}}),Q?.signal?.addEventListener("abort",()=>{H(Q?.signal?.reason)});let A=Q?.timeout??WQ$,Z=()=>H(j$.fromError(S$.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(N,A,Q?.maxTotalTimeout,Z,Q?.resetTimeoutOnProgress??!1);let F=V?.taskId;if(F){let I=(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,I),this._enqueueTaskMessage(F,{type:"request",message:w,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(N),K(E)})}else this._transport.send(w,{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((I)=>{this._cleanupTimeout(N),K(I)})})}async getTask($,J){return this.request({method:"tasks/get",params:$},vN,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:$},ak,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||{},[F8]: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||{},[F8]: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||{},[F8]:J.relatedTask}}};await this._transport.send(G,J)}setRequestHandler($,J){let Q=nL($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,X)=>{let G=cL($,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=nL($);this._notificationHandlers.set(Q,(Y)=>{let X=cL($,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"&&EL(Y.message)){let X=Y.message.id,G=this._requestResolvers.get(X);if(G)G(new j$(S$.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 j$(S$.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);J.addEventListener("abort",()=>{clearTimeout(G),X(new j$(S$.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 j$(S$.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),j8(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 j$(S$.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(j8(W.status))throw new j$(S$.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 D=FV.parse({method:"notifications/tasks/status",params:V});if(await this.notification(D),j8(V.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,J)}}}}function yx($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function hx($,J){let Q={...$};for(let Y in J){let X=Y,G=J[X];if(G===void 0)continue;let W=Q[X];if(yx(W)&&yx(G))Q[X]={...W,...G};else Q[X]=G}return Q}var Bh=J1(lB(),1),Fh=J1(Lh(),1);function RW$(){let $=new Bh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Fh.default($),$}class sB{constructor($){this._ajv=$??RW$()}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 eB{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((K)=>K.type==="tool_result"),W=$.messages.length>1?$.messages[$.messages.length-2]:void 0,V=W?Array.isArray(W.content)?W.content:[W.content]:[],D=V.some((K)=>K.type==="tool_use");if(G){if(X.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let K=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(K.size!==O.size||![...K].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:$},_V,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},B5,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 jh($,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 Eh($,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 $F extends iL{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 sB,this.setRequestHandler(RL,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(TL,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(bL,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 eB(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hx(this._capabilities,$)}setRequestHandler($,J){let Y=L8($)?.method;if(!Y)throw Error("Schema is missing a method literal");let X;if(Q6(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,D)=>{let K=I8(L5,V);if(!K.success){let H=K.error instanceof Error?K.error.message:String(K.error);throw new j$(S$.InvalidParams,`Invalid tools/call request: ${H}`)}let{params:O}=K.data,N=await Promise.resolve(J(V,D));if(O.task){let H=I8(Z5,N);if(!H.success){let A=H.error instanceof Error?H.error.message:String(H.error);throw new j$(S$.InvalidParams,`Invalid task creation result: ${A}`)}return H.data}let w=I8(lN,N);if(!w.success){let H=w.error instanceof Error?w.error.message:String(w.error);throw new j$(S$.InvalidParams,`Invalid tools/call result: ${H}`)}return w.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($){Eh(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;jh(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let J=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:mk.includes(J)?J:FL,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"},_N)}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((D)=>D.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((D)=>D.type==="tool_use");if(X){if(Y.some((D)=>D.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 D=new Set(W.filter((O)=>O.type==="tool_use").map((O)=>O.id)),K=new Set(Y.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(D.size!==K.size||![...D].every((O)=>K.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:$},gL,J);return this.request({method:"sampling/createMessage",params:$},_V,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},B5,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},B5,J);if(X.action==="accept"&&X.content&&Y.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(Y.requestedSchema)(X.content);if(!W.valid)throw new j$(S$.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof j$)throw G;throw new j$(S$.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:$},yL,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 Sh=Symbol.for("mcp.completable");function JF($){return!!$&&typeof $==="object"&&Sh in $}function Rh($){return $[Sh]?.complete}var _h;(function($){$.Completable="McpCompletable"})(_h||(_h={}));var TW$=/^[A-Za-z0-9._-]{1,128}$/;function CW$($){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(!TW$.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 vW$($,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 QF($){let J=CW$($);return vW$($,J.warnings),J.isValid}class XF{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 GF{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 $F($,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new XF(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(P8(mN)),this.server.assertCanSetRequestHandler(P8(L5)),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=D5(J.inputSchema);return Y?dL(Y,{strictUnions:!0,pipeStrategy:"input"}):PW$})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let Y=D5(J.outputSchema);if(Y)Q.outputSchema=dL(Y,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(L5,async($,J)=>{try{let Q=this._registeredTools[$.params.name];if(!Q)throw new j$(S$.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new j$(S$.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 j$(S$.InternalError,`Tool ${$.params.name} has taskSupport '${X}' but was not registered with registerToolTask`);if(X==="required"&&!Y)throw new j$(S$.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 j$){if(Q.code===S$.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=D5($.inputSchema)??$.inputSchema,G=await nO(X,J);if(!G.success){let W="error"in G?G.error:"Unknown error",V=cO(W);throw new j$(S$.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 j$(S$.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let Y=D5($.outputSchema),X=await nO(Y,J.structuredContent);if(!X.success){let G="error"in X?X.error:"Unknown error",W=cO(G);throw new j$(S$.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,D=W.task,K=D.pollInterval??5000;while(D.status!=="completed"&&D.status!=="failed"&&D.status!=="cancelled"){await new Promise((N)=>setTimeout(N,K));let O=await Q.taskStore.getTask(V);if(!O)throw new j$(S$.InternalError,`Task ${V} not found during polling`);D=O}return await Q.taskStore.getTaskResult(V)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(P8(pN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pN,async($)=>{switch($.params.ref.type){case"ref/prompt":return Xx($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return Yx($),this.handleResourceCompletion($,$.params.ref);default:throw new j$(S$.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,J){let Q=this._registeredPrompts[J.name];if(!Q)throw new j$(S$.InvalidParams,`Prompt ${J.name} not found`);if(!Q.enabled)throw new j$(S$.InvalidParams,`Prompt ${J.name} disabled`);if(!Q.argsSchema)return aV;let X=L8(Q.argsSchema)?.[$.params.argument.name];if(!JF(X))return aV;let G=Rh(X);if(!G)return aV;let W=await G($.params.argument.value,$.params.context);return Ch(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 j$(S$.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 Ch(X)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(P8(bN)),this.server.assertCanSetRequestHandler(P8(gN)),this.server.assertCanSetRequestHandler(P8(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 j$(S$.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 j$(S$.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(P8(hN)),this.server.assertCanSetRequestHandler(P8(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?kW$(J.argsSchema):void 0}})})),this.server.setRequestHandler(uN,async($,J)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new j$(S$.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new j$(S$.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=D5(Q.argsSchema),X=await nO(Y,$.params.arguments);if(!X.success){let V="error"in X?X.error:"Unknown error",D=cO(V);throw new j$(S$.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${D}`)}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:(D)=>{if(typeof D.name<"u"&&D.name!==$){if(delete this._registeredResourceTemplates[$],D.name)this._registeredResourceTemplates[D.name]=G}if(typeof D.title<"u")G.title=D.title;if(typeof D.template<"u")G.resourceTemplate=D.template;if(typeof D.metadata<"u")G.metadata=D.metadata;if(typeof D.callback<"u")G.readCallback=D.callback;if(typeof D.enabled<"u")G.enabled=D.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[$]=G;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((D)=>!!Q.completeCallback(D)))this.setCompletionRequestHandler();return G}_createRegisteredPrompt($,J,Q,Y,X){let G={title:J,description:Q,argsSchema:Y===void 0?void 0:oX(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=oX(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 D=V instanceof A5?V._def?.innerType:V;return JF(D)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool($,J,Q,Y,X,G,W,V,D){QF($);let K={title:J,description:Q,inputSchema:Th(Y),outputSchema:Th(X),annotations:G,execution:W,_meta:V,handler:D,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({name:null}),update:(O)=>{if(typeof O.name<"u"&&O.name!==$){if(typeof O.name==="string")QF(O.name);if(delete this._registeredTools[$],O.name)this._registeredTools[O.name]=K}if(typeof O.title<"u")K.title=O.title;if(typeof O.description<"u")K.description=O.description;if(typeof O.paramsSchema<"u")K.inputSchema=oX(O.paramsSchema);if(typeof O.outputSchema<"u")K.outputSchema=oX(O.outputSchema);if(typeof O.callback<"u")K.handler=O.callback;if(typeof O.annotations<"u")K.annotations=O.annotations;if(typeof O._meta<"u")K._meta=O._meta;if(typeof O.enabled<"u")K.enabled=O.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=K,this.setToolRequestHandlers(),this.sendToolListChanged(),K}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(YF(V)){if(Y=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!YF(J[0]))G=J.shift()}else if(typeof V==="object"&&V!==null){if(Object.values(V).some((D)=>typeof D==="object"&&D!==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:D}=J;return this._createRegisteredTool($,Y,X,G,W,V,{taskSupport:"forbidden"},D,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 PW$={type:"object",properties:{}};function vh($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function Ph($){return"_def"in $||"_zod"in $||vh($)}function YF($){if(typeof $!=="object"||$===null)return!1;if(Ph($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(vh)}function Th($){if(!$)return;if(YF($))return oX($);if(!Ph($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function kW$($){let J=L8($);if(!J)return[];return Object.entries(J).map(([Q,Y])=>{let X=_P(Y),G=SP(Y);return{name:Q,description:X,required:!G}})}function P8($){let Q=L8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=iO(Q);if(typeof Y==="string")return Y;throw Error("Schema method literal must be a string")}function Ch($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var aV={completion:{values:[],hasMore:!1}};import xh from"node:process";class WF{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),xW$(J)}clear(){this._buffer=void 0}}function xW$($){return rk.parse(JSON.parse($))}function kh($){return JSON.stringify($)+`
|
|
136
|
-
`}class VF{constructor($=xh.stdin,J=xh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new WF,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=kh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var CM={name:"@0xmonaco/mcp-server",version:"1.0.38",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":"1.0.38","@0xmonaco/types":"1.0.38","@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 vM=["read","market-maker","full"],qJ=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_position_margin",description:"Add isolated margin collateral to a perpetual position.",category:"positions",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"reduce_position_margin",description:"Withdraw isolated margin collateral from a perpetual position back to the account.",category:"positions",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],aB$=qJ.map(($)=>$.name),fh=qJ.filter(($)=>$.authMode==="public").map(($)=>$.name),sB$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="read").map(($)=>$.name),eB$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="market-maker").map(($)=>$.name),$F$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="full").map(($)=>$.name),JF$=qJ.filter(($)=>$.excludedOnMainnet).map(($)=>$.name),bh=qJ.filter(($)=>$.sideEffect==="fund-movement").map(($)=>$.name),bW$=new Map(qJ.map(($)=>[$.name,$.sideEffect]));function gh($){let J=bW$.get($);if(!J)return;let Q=J==="read-only";return{readOnlyHint:Q,destructiveHint:!Q}}var yh={read:0,"market-maker":1,full:2},DF=fh,KF=Object.fromEntries(qJ.filter(($)=>$.authMode==="authenticated").map(($)=>[$.name,{capability:$.capability??"full",...$.sideEffect==="fund-movement"?{fundMovement:!0}:{},...$.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),hh=Object.fromEntries(Object.entries(KF).map(([$,J])=>[$,J.capability])),YF$=new Set(bh);function uh($){let J=KF[$];if(!J)return"full";if(J.fundMovement)return"full";return J.capability}function mh($){return uh($)==="read"}function lh($,J){if(J.network==="mainnet"&&KF[$]?.excludedOnMainnet)return!1;if(J.deny.includes($))return!1;if(DF.includes($))return!0;if(!J.authenticated)return!1;if(J.allow.includes($))return!0;return yh[J.capability]>=yh[uh($)]}var gW$=new Set([...DF,...Object.keys(hh)]),yW$={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 ph($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter(Boolean)}function X9($=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;if(J&&!X)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${Y.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let G=X||"mainnet";if(!Y.includes(G))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}.`);let W=G,V=$.MONACO_CAPABILITY;if(V&&!vM.includes(V))throw Error(`MONACO_CAPABILITY must be one of: ${vM.join(", ")}.`);let D=V||"read",K=ph($.MONACO_TOOL_ALLOWLIST),O=ph($.MONACO_TOOL_DENYLIST),N=[...K,...O].filter((A)=>!gW$.has(A)).length;if(N>0)throw Error(`${N} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let w=$.MONACO_RPC_URL||yW$[W],H=null;if($.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let A=$.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!A)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!J||!Q)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");H=A}return{privateKey:J,clientId:Q,network:W,seiRpcUrl:w,capability:D,allow:K,deny:O,delegatedOwnerUserId:H}}function hW$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function k8($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>k8(Q));let J={};for(let[Q,Y]of Object.entries($))J[hW$(Q)]=typeof Y==="object"&&Y!==null?k8(Y):Y;return J}D6();QD();D6();SF();z9();w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var BJ=BigInt(0),N1=BigInt(1),Cu=BigInt(2),VV$=BigInt(8),DV$={zip215:!0};function KV$($){let J=GD($);return h6($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function vu($){let J=KV$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:V,h:D}=J,K=Cu<<BigInt(V*8)-N1,O=Q.create,N=AQ(J.n,J.nBitLength);function w(P,h){let x=Q.sqr(P),t=Q.sqr(h),e=Q.add(Q.mul(J.a,x),t),V$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(x,t)));return Q.eql(e,V$)}if(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let H=J.uvRatio||((P,h)=>{try{return{isValid:!0,value:Q.sqrt(P*Q.inv(h))}}catch(x){return{isValid:!1,value:BJ}}}),A=J.adjustScalarBytes||((P)=>P),Z=J.domain||((P,h,x)=>{if(IJ("phflag",x),h.length||x)throw Error("Contexts/pre-hash are not supported");return P});function F(P,h,x=!1){let t=x?N1:BJ;U1("coordinate "+P,h,t,K)}function I(P){if(!(P instanceof L))throw Error("ExtendedPoint expected")}let E=u5((P,h)=>{let{ex:x,ey:t,ez:e}=P,V$=P.is0();if(h==null)h=V$?VV$:Q.inv(e);let c=O(x*h),M$=O(t*h),f$=O(e*h);if(V$)return{x:BJ,y:N1};if(f$!==N1)throw Error("invZ was invalid");return{x:c,y:M$}}),B=u5((P)=>{let{a:h,d:x}=J;if(P.is0())throw Error("bad point: ZERO");let{ex:t,ey:e,ez:V$,et:c}=P,M$=O(t*t),f$=O(e*e),b$=O(V$*V$),h$=O(b$*b$),y4=O(M$*h),Z4=O(b$*O(y4+f$)),V0=O(h$+O(x*O(M$*f$)));if(Z4!==V0)throw Error("bad point: equation left != right (1)");let c0=O(t*e),$0=O(V$*c);if(c0!==$0)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(P,h,x,t){F("x",P),F("y",h),F("z",x,!0),F("t",t),this.ex=P,this.ey=h,this.ez=x,this.et=t,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof L)throw Error("extended point not allowed");let{x:h,y:x}=P||{};return F("x",h),F("y",x),new L(h,x,N1,O(h*x))}static normalizeZ(P){let h=zQ(Q,P.map((x)=>x.ez));return P.map((x,t)=>x.toAffine(h[t])).map(L.fromAffine)}static msm(P,h){return mM(L,N,P,h)}_setWindowSize(P){v.setWindowSize(this,P)}assertValidity(){B(this)}equals(P){I(P);let{ex:h,ey:x,ez:t}=this,{ex:e,ey:V$,ez:c}=P,M$=O(h*c),f$=O(e*t),b$=O(x*c),h$=O(V$*t);return M$===f$&&b$===h$}is0(){return this.equals(L.ZERO)}negate(){return new L(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:P}=J,{ex:h,ey:x,ez:t}=this,e=O(h*h),V$=O(x*x),c=O(Cu*O(t*t)),M$=O(P*e),f$=h+x,b$=O(O(f$*f$)-e-V$),h$=M$+V$,y4=h$-c,Z4=M$-V$,V0=O(b$*y4),c0=O(h$*Z4),$0=O(b$*Z4),F1=O(y4*h$);return new L(V0,c0,F1,$0)}add(P){I(P);let{a:h,d:x}=J,{ex:t,ey:e,ez:V$,et:c}=this,{ex:M$,ey:f$,ez:b$,et:h$}=P,y4=O(t*M$),Z4=O(e*f$),V0=O(c*x*h$),c0=O(V$*b$),$0=O((t+e)*(M$+f$)-y4-Z4),F1=c0-V0,i0=c0+V0,nQ=O(Z4-h*y4),C7=O($0*F1),YY=O(i0*nQ),fK=O($0*nQ),L6=O(F1*i0);return new L(C7,YY,L6,fK)}subtract(P){return this.add(P.negate())}wNAF(P){return v.wNAFCached(this,P,L.normalizeZ)}multiply(P){let h=P;U1("scalar",h,N1,Y);let{p:x,f:t}=this.wNAF(h);return L.normalizeZ([x,t])[0]}multiplyUnsafe(P,h=L.ZERO){let x=P;if(U1("scalar",x,BJ,Y),x===BJ)return S;if(this.is0()||x===N1)return this;return v.wNAFCachedUnsafe(this,x,L.normalizeZ,h)}isSmallOrder(){return this.multiplyUnsafe(D).is0()}isTorsionFree(){return v.unsafeLadder(this,Y).is0()}toAffine(P){return E(this,P)}clearCofactor(){let{h:P}=J;if(P===N1)return this;return this.multiplyUnsafe(P)}static fromHex(P,h=!1){let{d:x,a:t}=J,e=Q.BYTES;P=q4("pointHex",P,e),IJ("zip215",h);let V$=P.slice(),c=P[e-1];V$[e-1]=c&-129;let M$=O9(V$),f$=h?K:Q.ORDER;U1("pointHex.y",M$,BJ,f$);let b$=O(M$*M$),h$=O(b$-N1),y4=O(x*b$-t),{isValid:Z4,value:V0}=H(h$,y4);if(!Z4)throw Error("Point.fromHex: invalid y coordinate");let c0=(V0&N1)===N1,$0=(c&128)!==0;if(!h&&V0===BJ&&$0)throw Error("Point.fromHex: x=0 and x_0=1");if($0!==c0)V0=O(-V0);return L.fromAffine({x:V0,y:M$})}static fromPrivateKey(P){let{scalar:h}=R(P);return j.multiply(h)}toRawBytes(){let{x:P,y:h}=this.toAffine(),x=h5(h,Q.BYTES);return x[x.length-1]|=P&N1?128:0,x}toHex(){return g8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,N1,O(J.Gx*J.Gy)),L.ZERO=new L(BJ,N1,N1,BJ);let{BASE:j,ZERO:S}=L,v=uM(L,V*8);function k(P){return K4(P,Y)}function b(P){return k(O9(P))}function R(P){let h=Q.BYTES;P=q4("private key",P,h);let x=q4("hashed private key",G(P),2*h),t=A(x.slice(0,h)),e=x.slice(h,2*h),V$=b(t);return{head:t,prefix:e,scalar:V$}}function d(P){let{head:h,prefix:x,scalar:t}=R(P),e=j.multiply(t),V$=e.toRawBytes();return{head:h,prefix:x,scalar:t,point:e,pointBytes:V$}}function n(P){return d(P).pointBytes}function D$(P=Uint8Array.of(),...h){let x=q0(...h);return b(G(Z(x,q4("context",P),!!X)))}function i(P,h,x={}){if(P=q4("message",P),X)P=X(P);let{prefix:t,scalar:e,pointBytes:V$}=d(h),c=D$(x.context,t,P),M$=j.multiply(c).toRawBytes(),f$=D$(x.context,M$,V$,P),b$=k(c+f$*e);U1("signature.s",b$,BJ,Y);let h$=q0(M$,h5(b$,Q.BYTES));return q4("result",h$,Q.BYTES*2)}let p=DV$;function N$(P,h,x,t=p){let{context:e,zip215:V$}=t,c=Q.BYTES;if(P=q4("signature",P,2*c),h=q4("message",h),x=q4("publicKey",x,c),V$!==void 0)IJ("zip215",V$);if(X)h=X(h);let M$=O9(P.slice(c,2*c)),f$,b$,h$;try{f$=L.fromHex(x,V$),b$=L.fromHex(P.slice(0,c),V$),h$=j.multiplyUnsafe(M$)}catch(V0){return!1}if(!V$&&f$.isSmallOrder())return!1;let y4=D$(e,b$.toRawBytes(),f$.toRawBytes(),h);return b$.add(f$.multiplyUnsafe(y4)).subtract(h$).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:n,sign:i,verify:N$,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(P=8,h=L.BASE){return h._setWindowSize(P),h.multiply(BigInt(3)),h}}}}z9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var RF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),bu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uF$=BigInt(0),wV$=BigInt(1),gu=BigInt(2),mF$=BigInt(3),HV$=BigInt(5),zV$=BigInt(8);function AV$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=RF,V=$*$%G*$%G,D=n4(V,gu,G)*V%G,K=n4(D,wV$,G)*$%G,O=n4(K,HV$,G)*K%G,N=n4(O,J,G)*O%G,w=n4(N,Q,G)*N%G,H=n4(w,Y,G)*w%G,A=n4(H,X,G)*H%G,Z=n4(A,X,G)*H%G,F=n4(Z,J,G)*O%G;return{pow_p_5_8:n4(F,gu,G)*$%G,b2:V}}function qV$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function ZV$($,J){let Q=RF,Y=K4(J*J*J,Q),X=K4(Y*Y*J,Q),G=AV$($*X).pow_p_5_8,W=K4($*Y*G,Q),V=K4(J*W*W,Q),D=W,K=K4(W*bu,Q),O=V===$,N=V===K4(-$,Q),w=V===K4(-$*bu,Q);if(O)W=D;if(N||w)W=K;if(Fu(W,Q))W=K4(-W,Q);return{isValid:O||N,value:W}}var yu=(()=>AQ(RF,void 0,!0))(),IV$=(()=>({a:yu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:yu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:zV$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ou,randomBytes:g5,adjustScalarBytes:qV$,uvRatio:ZV$}))(),lM=(()=>vu(IV$))();QD();D6();function pM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lM.utils.randomPrivateKey();return{publicKey:lM.getPublicKey($),privateKey:$}}function dM($){return W9($.publicKey)}function nM($){return W9($.privateKey)}function hu($,J){return{publicKey:sV($),privateKey:sV(J)}}function uu($){return W9(MQ($))}function mu($,J,Q,Y){return`${$.toUpperCase()}
|
|
136
|
+
`}class VF{constructor($=xh.stdin,J=xh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new WF,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=kh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var CM={name:"@0xmonaco/mcp-server",version:"1.0.39",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":"1.0.39","@0xmonaco/types":"1.0.39","@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 vM=["read","market-maker","full"],qJ=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_position_margin",description:"Add isolated margin collateral to a perpetual position.",category:"positions",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"reduce_position_margin",description:"Withdraw isolated margin collateral from a perpetual position back to the account.",category:"positions",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],aB$=qJ.map(($)=>$.name),fh=qJ.filter(($)=>$.authMode==="public").map(($)=>$.name),sB$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="read").map(($)=>$.name),eB$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="market-maker").map(($)=>$.name),$F$=qJ.filter(($)=>$.authMode==="authenticated"&&$.capability==="full").map(($)=>$.name),JF$=qJ.filter(($)=>$.excludedOnMainnet).map(($)=>$.name),bh=qJ.filter(($)=>$.sideEffect==="fund-movement").map(($)=>$.name),bW$=new Map(qJ.map(($)=>[$.name,$.sideEffect]));function gh($){let J=bW$.get($);if(!J)return;let Q=J==="read-only";return{readOnlyHint:Q,destructiveHint:!Q}}var yh={read:0,"market-maker":1,full:2},DF=fh,KF=Object.fromEntries(qJ.filter(($)=>$.authMode==="authenticated").map(($)=>[$.name,{capability:$.capability??"full",...$.sideEffect==="fund-movement"?{fundMovement:!0}:{},...$.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),hh=Object.fromEntries(Object.entries(KF).map(([$,J])=>[$,J.capability])),YF$=new Set(bh);function uh($){let J=KF[$];if(!J)return"full";if(J.fundMovement)return"full";return J.capability}function mh($){return uh($)==="read"}function lh($,J){if(J.network==="mainnet"&&KF[$]?.excludedOnMainnet)return!1;if(J.deny.includes($))return!1;if(DF.includes($))return!0;if(!J.authenticated)return!1;if(J.allow.includes($))return!0;return yh[J.capability]>=yh[uh($)]}var gW$=new Set([...DF,...Object.keys(hh)]),yW$={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 ph($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter(Boolean)}function X9($=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;if(J&&!X)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${Y.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let G=X||"mainnet";if(!Y.includes(G))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}.`);let W=G,V=$.MONACO_CAPABILITY;if(V&&!vM.includes(V))throw Error(`MONACO_CAPABILITY must be one of: ${vM.join(", ")}.`);let D=V||"read",K=ph($.MONACO_TOOL_ALLOWLIST),O=ph($.MONACO_TOOL_DENYLIST),N=[...K,...O].filter((A)=>!gW$.has(A)).length;if(N>0)throw Error(`${N} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let w=$.MONACO_RPC_URL||yW$[W],H=null;if($.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let A=$.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!A)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!J||!Q)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");H=A}return{privateKey:J,clientId:Q,network:W,seiRpcUrl:w,capability:D,allow:K,deny:O,delegatedOwnerUserId:H}}function hW$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function k8($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>k8(Q));let J={};for(let[Q,Y]of Object.entries($))J[hW$(Q)]=typeof Y==="object"&&Y!==null?k8(Y):Y;return J}D6();QD();D6();SF();z9();w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var BJ=BigInt(0),N1=BigInt(1),Cu=BigInt(2),VV$=BigInt(8),DV$={zip215:!0};function KV$($){let J=GD($);return h6($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function vu($){let J=KV$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:V,h:D}=J,K=Cu<<BigInt(V*8)-N1,O=Q.create,N=AQ(J.n,J.nBitLength);function w(P,h){let x=Q.sqr(P),t=Q.sqr(h),e=Q.add(Q.mul(J.a,x),t),V$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(x,t)));return Q.eql(e,V$)}if(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let H=J.uvRatio||((P,h)=>{try{return{isValid:!0,value:Q.sqrt(P*Q.inv(h))}}catch(x){return{isValid:!1,value:BJ}}}),A=J.adjustScalarBytes||((P)=>P),Z=J.domain||((P,h,x)=>{if(IJ("phflag",x),h.length||x)throw Error("Contexts/pre-hash are not supported");return P});function F(P,h,x=!1){let t=x?N1:BJ;U1("coordinate "+P,h,t,K)}function I(P){if(!(P instanceof L))throw Error("ExtendedPoint expected")}let E=u5((P,h)=>{let{ex:x,ey:t,ez:e}=P,V$=P.is0();if(h==null)h=V$?VV$:Q.inv(e);let c=O(x*h),M$=O(t*h),f$=O(e*h);if(V$)return{x:BJ,y:N1};if(f$!==N1)throw Error("invZ was invalid");return{x:c,y:M$}}),B=u5((P)=>{let{a:h,d:x}=J;if(P.is0())throw Error("bad point: ZERO");let{ex:t,ey:e,ez:V$,et:c}=P,M$=O(t*t),f$=O(e*e),b$=O(V$*V$),h$=O(b$*b$),y4=O(M$*h),Z4=O(b$*O(y4+f$)),V0=O(h$+O(x*O(M$*f$)));if(Z4!==V0)throw Error("bad point: equation left != right (1)");let c0=O(t*e),$0=O(V$*c);if(c0!==$0)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(P,h,x,t){F("x",P),F("y",h),F("z",x,!0),F("t",t),this.ex=P,this.ey=h,this.ez=x,this.et=t,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof L)throw Error("extended point not allowed");let{x:h,y:x}=P||{};return F("x",h),F("y",x),new L(h,x,N1,O(h*x))}static normalizeZ(P){let h=zQ(Q,P.map((x)=>x.ez));return P.map((x,t)=>x.toAffine(h[t])).map(L.fromAffine)}static msm(P,h){return mM(L,N,P,h)}_setWindowSize(P){v.setWindowSize(this,P)}assertValidity(){B(this)}equals(P){I(P);let{ex:h,ey:x,ez:t}=this,{ex:e,ey:V$,ez:c}=P,M$=O(h*c),f$=O(e*t),b$=O(x*c),h$=O(V$*t);return M$===f$&&b$===h$}is0(){return this.equals(L.ZERO)}negate(){return new L(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:P}=J,{ex:h,ey:x,ez:t}=this,e=O(h*h),V$=O(x*x),c=O(Cu*O(t*t)),M$=O(P*e),f$=h+x,b$=O(O(f$*f$)-e-V$),h$=M$+V$,y4=h$-c,Z4=M$-V$,V0=O(b$*y4),c0=O(h$*Z4),$0=O(b$*Z4),F1=O(y4*h$);return new L(V0,c0,F1,$0)}add(P){I(P);let{a:h,d:x}=J,{ex:t,ey:e,ez:V$,et:c}=this,{ex:M$,ey:f$,ez:b$,et:h$}=P,y4=O(t*M$),Z4=O(e*f$),V0=O(c*x*h$),c0=O(V$*b$),$0=O((t+e)*(M$+f$)-y4-Z4),F1=c0-V0,i0=c0+V0,nQ=O(Z4-h*y4),C7=O($0*F1),YY=O(i0*nQ),fK=O($0*nQ),L6=O(F1*i0);return new L(C7,YY,L6,fK)}subtract(P){return this.add(P.negate())}wNAF(P){return v.wNAFCached(this,P,L.normalizeZ)}multiply(P){let h=P;U1("scalar",h,N1,Y);let{p:x,f:t}=this.wNAF(h);return L.normalizeZ([x,t])[0]}multiplyUnsafe(P,h=L.ZERO){let x=P;if(U1("scalar",x,BJ,Y),x===BJ)return S;if(this.is0()||x===N1)return this;return v.wNAFCachedUnsafe(this,x,L.normalizeZ,h)}isSmallOrder(){return this.multiplyUnsafe(D).is0()}isTorsionFree(){return v.unsafeLadder(this,Y).is0()}toAffine(P){return E(this,P)}clearCofactor(){let{h:P}=J;if(P===N1)return this;return this.multiplyUnsafe(P)}static fromHex(P,h=!1){let{d:x,a:t}=J,e=Q.BYTES;P=q4("pointHex",P,e),IJ("zip215",h);let V$=P.slice(),c=P[e-1];V$[e-1]=c&-129;let M$=O9(V$),f$=h?K:Q.ORDER;U1("pointHex.y",M$,BJ,f$);let b$=O(M$*M$),h$=O(b$-N1),y4=O(x*b$-t),{isValid:Z4,value:V0}=H(h$,y4);if(!Z4)throw Error("Point.fromHex: invalid y coordinate");let c0=(V0&N1)===N1,$0=(c&128)!==0;if(!h&&V0===BJ&&$0)throw Error("Point.fromHex: x=0 and x_0=1");if($0!==c0)V0=O(-V0);return L.fromAffine({x:V0,y:M$})}static fromPrivateKey(P){let{scalar:h}=R(P);return j.multiply(h)}toRawBytes(){let{x:P,y:h}=this.toAffine(),x=h5(h,Q.BYTES);return x[x.length-1]|=P&N1?128:0,x}toHex(){return g8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,N1,O(J.Gx*J.Gy)),L.ZERO=new L(BJ,N1,N1,BJ);let{BASE:j,ZERO:S}=L,v=uM(L,V*8);function k(P){return K4(P,Y)}function b(P){return k(O9(P))}function R(P){let h=Q.BYTES;P=q4("private key",P,h);let x=q4("hashed private key",G(P),2*h),t=A(x.slice(0,h)),e=x.slice(h,2*h),V$=b(t);return{head:t,prefix:e,scalar:V$}}function d(P){let{head:h,prefix:x,scalar:t}=R(P),e=j.multiply(t),V$=e.toRawBytes();return{head:h,prefix:x,scalar:t,point:e,pointBytes:V$}}function n(P){return d(P).pointBytes}function D$(P=Uint8Array.of(),...h){let x=q0(...h);return b(G(Z(x,q4("context",P),!!X)))}function i(P,h,x={}){if(P=q4("message",P),X)P=X(P);let{prefix:t,scalar:e,pointBytes:V$}=d(h),c=D$(x.context,t,P),M$=j.multiply(c).toRawBytes(),f$=D$(x.context,M$,V$,P),b$=k(c+f$*e);U1("signature.s",b$,BJ,Y);let h$=q0(M$,h5(b$,Q.BYTES));return q4("result",h$,Q.BYTES*2)}let p=DV$;function N$(P,h,x,t=p){let{context:e,zip215:V$}=t,c=Q.BYTES;if(P=q4("signature",P,2*c),h=q4("message",h),x=q4("publicKey",x,c),V$!==void 0)IJ("zip215",V$);if(X)h=X(h);let M$=O9(P.slice(c,2*c)),f$,b$,h$;try{f$=L.fromHex(x,V$),b$=L.fromHex(P.slice(0,c),V$),h$=j.multiplyUnsafe(M$)}catch(V0){return!1}if(!V$&&f$.isSmallOrder())return!1;let y4=D$(e,b$.toRawBytes(),f$.toRawBytes(),h);return b$.add(f$.multiplyUnsafe(y4)).subtract(h$).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:n,sign:i,verify:N$,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(P=8,h=L.BASE){return h._setWindowSize(P),h.multiply(BigInt(3)),h}}}}z9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var RF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),bu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uF$=BigInt(0),wV$=BigInt(1),gu=BigInt(2),mF$=BigInt(3),HV$=BigInt(5),zV$=BigInt(8);function AV$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=RF,V=$*$%G*$%G,D=n4(V,gu,G)*V%G,K=n4(D,wV$,G)*$%G,O=n4(K,HV$,G)*K%G,N=n4(O,J,G)*O%G,w=n4(N,Q,G)*N%G,H=n4(w,Y,G)*w%G,A=n4(H,X,G)*H%G,Z=n4(A,X,G)*H%G,F=n4(Z,J,G)*O%G;return{pow_p_5_8:n4(F,gu,G)*$%G,b2:V}}function qV$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function ZV$($,J){let Q=RF,Y=K4(J*J*J,Q),X=K4(Y*Y*J,Q),G=AV$($*X).pow_p_5_8,W=K4($*Y*G,Q),V=K4(J*W*W,Q),D=W,K=K4(W*bu,Q),O=V===$,N=V===K4(-$,Q),w=V===K4(-$*bu,Q);if(O)W=D;if(N||w)W=K;if(Fu(W,Q))W=K4(-W,Q);return{isValid:O||N,value:W}}var yu=(()=>AQ(RF,void 0,!0))(),IV$=(()=>({a:yu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:yu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:zV$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ou,randomBytes:g5,adjustScalarBytes:qV$,uvRatio:ZV$}))(),lM=(()=>vu(IV$))();QD();D6();function pM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lM.utils.randomPrivateKey();return{publicKey:lM.getPublicKey($),privateKey:$}}function dM($){return W9($.publicKey)}function nM($){return W9($.privateKey)}function hu($,J){return{publicKey:sV($),privateKey:sV(J)}}function uu($){return W9(MQ($))}function mu($,J,Q,Y){return`${$.toUpperCase()}
|
|
137
137
|
${J}
|
|
138
138
|
${Q}
|
|
139
139
|
${Y}`}function lu($,J){return`WS-AUTH
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xmonaco/mcp-server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.39",
|
|
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": "1.0.
|
|
29
|
-
"@0xmonaco/types": "1.0.
|
|
28
|
+
"@0xmonaco/core": "1.0.39",
|
|
29
|
+
"@0xmonaco/types": "1.0.39",
|
|
30
30
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
31
31
|
"node-fetch": "^3.3.2",
|
|
32
32
|
"viem": "^2.53.1",
|