@0xmonaco/mcp-server 1.0.73-develop.af0f5d0 → 1.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +1 -1
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -133,7 +133,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
133
133
  `:`[${n[c]}\r
134
134
  ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Kg(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===se.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Vt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===se.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Wg(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===se.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===se.ZodBranded&&e.keyType._def.type._def.typeName===se.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Zg(e.keyType._def,t);return{...r,propertyNames:o}}return r}function nC(e,t){if(t.mapStrategy==="record")return Kg(e,t);let r=De(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Vt(t),n=De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Vt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function oC(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function iC(e){return e.target==="openAi"?void 0:{not:Vt({...e,currentPath:[...e.currentPath,"not"]})}}function sC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var af={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function cC(e,t){if(t.target==="openApi3")return aC(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in af)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=af[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return aC(e,t)}var aC=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>De(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function uC(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:af[e.innerType._def.typeName],nullable:!0};return{type:[af[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=De(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function dC(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",vS(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)ut(r,"minimum",n.value,n.message,t);else ut(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;ut(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)ut(r,"maximum",n.value,n.message,t);else ut(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;ut(r,"maximum",n.value,n.message,t)}break;case"multipleOf":ut(r,"multipleOf",n.value,n.message,t);break}return r}function lC(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let d=CQ(c);if(d&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();d=!1}let l=De(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!d)o.push(a)}if(o.length)n.required=o;let s=OQ(e,t);if(s!==void 0)n.additionalProperties=s;return n}function OQ(e,t){if(e.catchall._def.typeName!=="ZodNever")return De(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function CQ(e){try{return e.isOptional()}catch{return!0}}var pC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return De(e.innerType._def,t);let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Vt(t)},r]}:Vt(t)};var fC=(e,t)=>{if(t.pipeStrategy==="input")return De(e.in._def,t);else if(t.pipeStrategy==="output")return De(e.out._def,t);let r=De(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=De(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function mC(e,t){return De(e.type._def,t)}function hC(e,t){let n={type:"array",uniqueItems:!0,items:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)ut(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)ut(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function gC(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:De(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function yC(e){return{not:Vt(e)}}function bC(e){return Vt(e)}var xC=(e,t)=>De(e.innerType._def,t);var _C=(e,t,r)=>{switch(t){case se.ZodString:return Wg(e,r);case se.ZodNumber:return dC(e,r);case se.ZodObject:return lC(e,r);case se.ZodBigInt:return WO(e,r);case se.ZodBoolean:return KO();case se.ZodDate:return ES(e,r);case se.ZodUndefined:return yC(r);case se.ZodNull:return sC(r);case se.ZodArray:return ZO(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return cC(e,r);case se.ZodIntersection:return eC(e,r);case se.ZodTuple:return gC(e,r);case se.ZodRecord:return Kg(e,r);case se.ZodLiteral:return tC(e,r);case se.ZodEnum:return XO(e);case se.ZodNativeEnum:return oC(e);case se.ZodNullable:return uC(e,r);case se.ZodOptional:return pC(e,r);case se.ZodMap:return nC(e,r);case se.ZodSet:return hC(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return mC(e,r);case se.ZodNaN:case se.ZodNever:return iC(r);case se.ZodEffects:return QO(e,r);case se.ZodAny:return Vt(r);case se.ZodUnknown:return bC(r);case se.ZodDefault:return JO(e,r);case se.ZodBranded:return Zg(e,r);case se.ZodReadonly:return xC(e,r);case se.ZodCatch:return YO(e,r);case se.ZodPipeline:return fC(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return((n)=>{return})(t)}};function De(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==HO)return a}if(n&&!r){let a=MQ(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=_C(e,e.typeName,t),s=typeof i==="function"?De(i(),t):i;if(s)NQ(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var MQ=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Vg(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Vt(t);return t.$refStrategy==="seen"?Vt(t):void 0}}},NQ=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var IS=(e,t)=>{let r=VO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,l])=>({...c,[d]:De(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Vt(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=De(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Vt(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function $Q(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function kS(e,t){if(Wn(e))return tS(e,{target:$Q(t?.target),io:t?.pipeStrategy??"input"});return IS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function RS(e){let r=Ys(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=wg(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function OS(e,t){let r=Ks(e,t);if(!r.success)throw r.error;return r.data}var zQ=60000;class CS{constructor(e){if(this._options=e,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(kg,(t)=>{this._oncancel(t)}),this.setNotificationHandler(Og,(t)=>{this._onprogress(t)}),this.setRequestHandler(Rg,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Cg,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ae(Ne.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ng,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,d=this._requestResolvers.get(c);if(d)if(this._requestResolvers.delete(c),s.type==="response")d(a);else{let l=a,p=new Ae(l.error.code,l.error.message,l.error.data);d(p)}else{let l=s.type==="response"?"Response":"Error";this._onerror(Error(`${l} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ae(Ne.InvalidParams,`Task not found: ${o}`);if(!Xs(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Xs(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Qs]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler($g,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ae(Ne.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Lg,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ae(Ne.InvalidParams,`Task not found: ${t.params.taskId}`);if(Xs(n.status))throw new Ae(Ne.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ae(Ne.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Ae)throw n;throw new Ae(Ne.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ae.fromError(Ne.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){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=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),Jp(o)||OO(o))this._onresponse(o);else if(dS(o))this._onrequest(o,i);else if(RO(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Ae.fromError(Ne.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Qs]?.taskId;if(r===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:Ne.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId).catch((l)=>this._onerror(Error(`Failed to enqueue error response: ${l}`)));else n?.send(d).catch((l)=>this._onerror(Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=AO(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(d)=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};if(o)l.relatedTask={taskId:o};await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new Ae(Ne.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:e.id};if(o&&!h.relatedTask)h.relatedTask={taskId:o};let g=h.relatedTask?.taskId??o;if(g&&a)await a.updateTaskStatus(g,"input_required");return await this.request(d,l,h)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(d)=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)},async(d)=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Ne.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)}).catch((d)=>this._onerror(Error(`Failed to send response: ${d}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Jp(e))r(e);else{let i=new Ae(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(Jp(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(Jp(e))n(e);else{let i=Ae.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ae?i:new Ae(Ne.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Uu,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ae(Ne.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Xs(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ae(Ne.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ae(Ne.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ae?i:new Ae(Ne.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{let l=(w)=>{d(w)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(w){l(w);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)h.params={...h.params,task:s};if(a)h.params={...h.params,_meta:{...h.params?._meta||{},[Qs]:a}};let g=(w)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let A=w instanceof Ae?w:new Ae(Ne.RequestTimeout,String(w));d(A)};this._responseHandlers.set(p,(w)=>{if(r?.signal?.aborted)return;if(w instanceof Error)return d(w);try{let A=Ks(t,w.result);if(!A.success)d(A.error);else c(A.data)}catch(A){d(A)}}),r?.signal?.addEventListener("abort",()=>{g(r?.signal?.reason)});let x=r?.timeout??zQ,_=()=>g(Ae.fromError(Ne.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(p,x,r?.maxTotalTimeout,_,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let w=(A)=>{let T=this._responseHandlers.get(p);if(T)T(A);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(S,{type:"request",message:h,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(p),d(A)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((w)=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Mg,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},zg,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},NO,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Qs]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Qs]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Qs]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=RS(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=OS(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=RS(e);this._notificationHandlers.set(r,(n)=>{let o=OS(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&dS(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Ae(Ne.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Ae(Ne.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new Ae(Ne.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Ae(Ne.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=rf.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Xs(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Ae(Ne.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Xs(s.status))throw new Ae(Ne.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=rf.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Xs(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function wC(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function SC(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(wC(s)&&wC(i))r[o]={...s,...i};else r[o]=i}return r}var o4=Xr(AT(),1),i4=Xr(n4(),1);function oae(){let e=new o4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return i4.default(e),e}class LT{constructor(e){this._ajv=e??oae()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class BT{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((d)=>d.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((d)=>d.type==="tool_use");if(i){if(o.some((d)=>d.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let d=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),l=new Set(o.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(d.size!==l.size||![...d].every((p)=>l.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},sf,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Hu,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function s4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function a4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class DT extends CS{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(of.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new LT,this.setRequestHandler(fS,(r)=>this._oninitialize(r)),this.setNotificationHandler(mS,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(wS,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=of.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new BT(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=SC(this._capabilities,e)}setRequestHandler(e,t){let n=Ys(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(Wn(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let d=Ks(qu,a);if(!d.success){let g=d.error instanceof Error?d.error.message:String(d.error);throw new Ae(Ne.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:l}=d.data,p=await Promise.resolve(t(a,c));if(l.task){let g=Ks(Uu,p);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new Ae(Ne.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let h=Ks(Hg,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new Ae(Ne.InvalidParams,`Invalid tools/call result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);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 ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){a4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;s4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:vO.includes(t)?t:cS,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"},Ig)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((l)=>l.type==="tool_use").map((l)=>l.id)),d=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==d.size||![...c].every((l)=>d.has(l)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},SS,t);return this.request({method:"sampling/createMessage",params:e},sf,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},Hu,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},Hu,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Ae(Ne.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ae)throw i;throw new Ae(Ne.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){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:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},TS,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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 u4=Symbol.for("mcp.completable");function FT(e){return!!e&&typeof e==="object"&&u4 in e}function d4(e){return e[u4]?.complete}var c4;(function(e){e.Completable="McpCompletable"})(c4||(c4={}));var iae=/^[A-Za-z0-9._-]{1,128}$/;function sae(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!iae.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function aae(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);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 UT(e){let t=sae(e);return aae(e,t.warnings),t.isValid}class jT{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class HT{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new DT(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new jT(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(aa(qg)),this.server.assertCanSetRequestHandler(aa(qu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(qg,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Bu(t.inputSchema);return n?kS(n,{strictUnions:!0,pipeStrategy:"input"}):cae})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Bu(t.outputSchema);if(n)r.outputSchema=kS(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(qu,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ae(Ne.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ae(Ne.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Ae(Ne.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Ae(Ne.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ae){if(r.code===Ne.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let o=Bu(e.inputSchema)??e.inputSchema,i=await xg(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=_g(s);throw new Ae(Ne.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ae(Ne.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Bu(e.outputSchema),o=await xg(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=_g(i);throw new Ae(Ne.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,d=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,d));let l=await r.taskStore.getTask(a);if(!l)throw new Ae(Ne.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(aa(Gg)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Gg,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return FO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return UO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ae(Ne.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ae(Ne.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ae(Ne.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return Of;let o=Ys(r.argsSchema)?.[e.params.argument.name];if(!FT(o))return Of;let i=d4(o);if(!i)return Of;let s=await i(e.params.argument.value,e.params.context);return p4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return Of;throw new Ae(Ne.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Of;let o=await n(e.params.argument.value,e.params.context);return p4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(aa(Bg)),this.server.assertCanSetRequestHandler(aa(Dg)),this.server.assertCanSetRequestHandler(aa(Fg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Bg,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Dg,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Fg,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Ae(Ne.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Ae(Ne.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(aa(Ug)),this.server.assertCanSetRequestHandler(aa(jg)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ug,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?uae(t.argsSchema):void 0}))})),this.server.setRequestHandler(jg,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ae(Ne.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ae(Ne.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Bu(r.argsSchema),o=await xg(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=_g(a);throw new Ae(Ne.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:dc(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=dc(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof vg?a._def?.innerType:a;return FT(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){UT(e);let d={title:t,description:r,inputSchema:l4(n),outputSchema:l4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")UT(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=d}if(typeof l.title<"u")d.title=l.title;if(typeof l.description<"u")d.description=l.description;if(typeof l.paramsSchema<"u")d.inputSchema=dc(l.paramsSchema);if(typeof l.outputSchema<"u")d.outputSchema=dc(l.outputSchema);if(typeof l.callback<"u")d.handler=l.callback;if(typeof l.annotations<"u")d.annotations=l.annotations;if(typeof l._meta<"u")d._meta=l._meta;if(typeof l.enabled<"u")d.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(qT(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!qT(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var cae={type:"object",properties:{}};function f4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function m4(e){return"_def"in e||"_zod"in e||f4(e)}function qT(e){if(typeof e!=="object"||e===null)return!1;if(m4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(f4)}function l4(e){if(!e)return;if(qT(e))return dc(e);if(!m4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function uae(e){let t=Ys(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=U5(n),i=j5(n);return{name:r,description:o,required:!i}})}function aa(e){let r=Ys(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=wg(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function p4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Of={completion:{values:[],hasMore:!1}};import g4 from"node:process";class GT{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
135
135
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),dae(t)}clear(){this._buffer=void 0}}function dae(e){return CO.parse(JSON.parse(e))}function h4(e){return JSON.stringify(e)+`
136
- `}class VT{constructor(e=g4.stdin,t=g4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new GT,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise((t)=>{let r=h4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var Cy={name:"@0xmonaco/mcp-server",version:"1.0.73",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",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.73","@0xmonaco/types":"1.0.73","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var My=["read","market-maker","full"],ei=[{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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",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:"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:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",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"}],sTe=ei.map((e)=>e.name),y4=ei.filter((e)=>e.authMode==="public").map((e)=>e.name),aTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),cTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),uTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),dTe=ei.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),b4=ei.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var pae=new Map(ei.map((e)=>[e.name,e.sideEffect]));function x4(e){let t=pae.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var _4={read:0,"market-maker":1,full:2},ZT=y4,WT=Object.fromEntries(ei.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),w4=Object.fromEntries(Object.entries(WT).map(([e,t])=>[e,t.capability])),fTe=new Set(b4);function S4(e){let t=WT[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function T4(e){return S4(e)==="read"}function v4(e,t){if(t.network==="mainnet"&&WT[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(ZT.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return _4[t.capability]>=_4[S4(e)]}var fae=new Set([...ZT,...Object.keys(w4)]),mae={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 E4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function bc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!My.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${My.join(", ")}.`);let c=a||"read",d=E4(e.MONACO_TOOL_ALLOWLIST),l=E4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((x)=>!fae.has(x)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||mae[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let x=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!x)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=x}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:d,deny:l,delegatedOwnerUserId:g}}function hae(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Gr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Gr(r));let t={};for(let[r,n]of Object.entries(e))t[hae(r)]=typeof n==="object"&&n!==null?Gr(n):n;return t}function P4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var KT=(e)=>e?`"${e}" `:"";function gae(e,t=""){if(typeof e!=="number")throw TypeError(KT(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(KT(t)+"expected integer >= 0, got "+e);return e}function Ny(e,t,r=""){if(P4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)gae(t,"length");let n=P4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=KT(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var yae=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},A4=(e,t)=>{yae(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function YT(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function k4(e,t){Ny(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function $y(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Eo(e,t){return e<<32-t|e>>>t}var R4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),bae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gi(e){if(Ny(e),R4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=bae[e[r]];return t}function I4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Cf(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(R4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=I4(e.charCodeAt(i)),a=I4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function xc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{$y(t)}}function xae(e,t,r="opts"){if(A4(e,"defaults"),t!==void 0)A4(t,r);return Object.assign(Object.create(null),e,t)}function O4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=xae({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var C4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});tv();Sc();hv();ud();Df();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ni=BigInt(0),un=BigInt(1),bL=BigInt(2),Lae=BigInt(8),Bae={zip215:!0};function Dae(e){let t=Ff(e);return Ji(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function xL(e){let t=Dae(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=bL<<BigInt(a*8)-un,l=r.create,p=Qi(t.n,t.nBitLength);function h(z,j){let J=r.sqr(z),ve=r.sqr(j),re=r.add(r.mul(t.a,J),ve),$e=r.add(r.ONE,r.mul(t.d,r.mul(J,ve)));return r.eql(re,$e)}if(!h(t.Gx,t.Gy))throw Error("bad curve params: generator point");let g=t.uvRatio||((z,j)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(j))}}catch(J){return{isValid:!1,value:ni}}}),x=t.adjustScalarBytes||((z)=>z),_=t.domain||((z,j,J)=>{if(ri("phflag",J),j.length||J)throw Error("Contexts/pre-hash are not supported");return z});function S(z,j,J=!1){let ve=J?un:ni;zn("coordinate "+z,j,ve,d)}function w(z){if(!(z instanceof v))throw Error("ExtendedPoint expected")}let A=ad((z,j)=>{let{ex:J,ey:ve,ez:re}=z,$e=z.is0();if(j==null)j=$e?Lae:r.inv(re);let Ie=l(J*j),Re=l(ve*j),nt=l(re*j);if($e)return{x:ni,y:un};if(nt!==un)throw Error("invZ was invalid");return{x:Ie,y:Re}}),T=ad((z)=>{let{a:j,d:J}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:ve,ey:re,ez:$e,et:Ie}=z,Re=l(ve*ve),nt=l(re*re),yt=l($e*$e),ft=l(yt*yt),Ct=l(Re*j),qt=l(yt*l(Ct+nt)),ar=l(ft+l(J*l(Re*nt)));if(qt!==ar)throw Error("bad point: equation left != right (1)");let Or=l(ve*re),rr=l($e*Ie);if(Or!==rr)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(z,j,J,ve){S("x",z),S("y",j),S("z",J,!0),S("t",ve),this.ex=z,this.ey=j,this.ez=J,this.et=ve,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof v)throw Error("extended point not allowed");let{x:j,y:J}=z||{};return S("x",j),S("y",J),new v(j,J,un,l(j*J))}static normalizeZ(z){let j=cd(r,z.map((J)=>J.ez));return z.map((J,ve)=>J.toAffine(j[ve])).map(v.fromAffine)}static msm(z,j){return Gy(v,p,z,j)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){T(this)}equals(z){w(z);let{ex:j,ey:J,ez:ve}=this,{ex:re,ey:$e,ez:Ie}=z,Re=l(j*Ie),nt=l(re*ve),yt=l(J*Ie),ft=l($e*ve);return Re===nt&&yt===ft}is0(){return this.equals(v.ZERO)}negate(){return new v(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:j,ey:J,ez:ve}=this,re=l(j*j),$e=l(J*J),Ie=l(bL*l(ve*ve)),Re=l(z*re),nt=j+J,yt=l(l(nt*nt)-re-$e),ft=Re+$e,Ct=ft-Ie,qt=Re-$e,ar=l(yt*Ct),Or=l(ft*qt),rr=l(yt*qt),Jr=l(Ct*ft);return new v(ar,Or,Jr,rr)}add(z){w(z);let{a:j,d:J}=t,{ex:ve,ey:re,ez:$e,et:Ie}=this,{ex:Re,ey:nt,ez:yt,et:ft}=z,Ct=l(ve*Re),qt=l(re*nt),ar=l(Ie*J*ft),Or=l($e*yt),rr=l((ve+re)*(Re+nt)-Ct-qt),Jr=Or-ar,q=Or+ar,ue=l(qt-j*Ct),he=l(rr*Jr),Ee=l(q*ue),ce=l(rr*ue),Me=l(Jr*q);return new v(he,Ee,Me,ce)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,v.normalizeZ)}multiply(z){let j=z;zn("scalar",j,un,n);let{p:J,f:ve}=this.wNAF(j);return v.normalizeZ([J,ve])[0]}multiplyUnsafe(z,j=v.ZERO){let J=z;if(zn("scalar",J,ni,n),J===ni)return R;if(this.is0()||J===un)return this;return O.wNAFCachedUnsafe(this,J,v.normalizeZ,j)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===un)return this;return this.multiplyUnsafe(z)}static fromHex(z,j=!1){let{d:J,a:ve}=t,re=r.BYTES;z=Zt("pointHex",z,re),ri("zip215",j);let $e=z.slice(),Ie=z[re-1];$e[re-1]=Ie&-129;let Re=Ec($e),nt=j?d:r.ORDER;zn("pointHex.y",Re,ni,nt);let yt=l(Re*Re),ft=l(yt-un),Ct=l(J*yt-ve),{isValid:qt,value:ar}=g(ft,Ct);if(!qt)throw Error("Point.fromHex: invalid y coordinate");let Or=(ar&un)===un,rr=(Ie&128)!==0;if(!j&&ar===ni&&rr)throw Error("Point.fromHex: x=0 and x_0=1");if(rr!==Or)ar=l(-ar);return v.fromAffine({x:ar,y:Re})}static fromPrivateKey(z){let{scalar:j}=C(z);return P.multiply(j)}toRawBytes(){let{x:z,y:j}=this.toAffine(),J=sd(j,r.BYTES);return J[J.length-1]|=z&un?128:0,J}toHex(){return la(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,un,l(t.Gx*t.Gy)),v.ZERO=new v(ni,un,un,ni);let{BASE:P,ZERO:R}=v,O=Hy(v,a*8);function L(z){return vt(z,n)}function G(z){return L(Ec(z))}function C(z){let j=r.BYTES;z=Zt("private key",z,j);let J=Zt("hashed private key",i(z),2*j),ve=x(J.slice(0,j)),re=J.slice(j,2*j),$e=G(ve);return{head:ve,prefix:re,scalar:$e}}function Y(z){let{head:j,prefix:J,scalar:ve}=C(z),re=P.multiply(ve),$e=re.toRawBytes();return{head:j,prefix:J,scalar:ve,point:re,pointBytes:$e}}function W(z){return Y(z).pointBytes}function le(z=Uint8Array.of(),...j){let J=pa(...j);return G(i(_(J,Zt("context",z),!!o)))}function fe(z,j,J={}){if(z=Zt("message",z),o)z=o(z);let{prefix:ve,scalar:re,pointBytes:$e}=Y(j),Ie=le(J.context,ve,z),Re=P.multiply(Ie).toRawBytes(),nt=le(J.context,Re,$e,z),yt=L(Ie+nt*re);zn("signature.s",yt,ni,n);let ft=pa(Re,sd(yt,r.BYTES));return Zt("result",ft,r.BYTES*2)}let U=Bae;function ee(z,j,J,ve=U){let{context:re,zip215:$e}=ve,Ie=r.BYTES;if(z=Zt("signature",z,2*Ie),j=Zt("message",j),J=Zt("publicKey",J,Ie),$e!==void 0)ri("zip215",$e);if(o)j=o(j);let Re=Ec(z.slice(Ie,2*Ie)),nt,yt,ft;try{nt=v.fromHex(J,$e),yt=v.fromHex(z.slice(0,Ie),$e),ft=P.multiplyUnsafe(Re)}catch(ar){return!1}if(!$e&&nt.isSmallOrder())return!1;let Ct=le(re,yt.toRawBytes(),nt.toRawBytes(),j);return yt.add(nt.multiplyUnsafe(Ct)).subtract(ft).clearCofactor().equals(v.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:W,sign:fe,verify:ee,ExtendedPoint:v,utils:{getExtendedPublicKey:Y,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,j=v.BASE){return j._setWindowSize(z),j.multiply(BigInt(3)),j}}}}ud();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var gv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_L=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ZTe=BigInt(0),Fae=BigInt(1),wL=BigInt(2),WTe=BigInt(3),Uae=BigInt(5),jae=BigInt(8);function qae(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=gv,a=e*e%i*e%i,c=Wt(a,wL,i)*a%i,d=Wt(c,Fae,i)*e%i,l=Wt(d,Uae,i)*d%i,p=Wt(l,t,i)*l%i,h=Wt(p,r,i)*p%i,g=Wt(h,n,i)*h%i,x=Wt(g,o,i)*g%i,_=Wt(x,o,i)*g%i,S=Wt(_,t,i)*l%i;return{pow_p_5_8:Wt(S,wL,i)*e%i,b2:a}}function Hae(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Gae(e,t){let r=gv,n=vt(t*t*t,r),o=vt(n*n*t,r),i=qae(e*o).pow_p_5_8,s=vt(e*n*i,r),a=vt(t*s*s,r),c=s,d=vt(s*_L,r),l=a===e,p=a===vt(-e,r),h=a===vt(-e*_L,r);if(l)s=c;if(p||h)s=d;if(lL(s,r))s=vt(-s,r);return{isValid:l||p,value:s}}var SL=(()=>Qi(gv,void 0,!0))(),Vae=(()=>({a:SL.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:SL,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:jae,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:X4,randomBytes:Dy,adjustScalarBytes:Hae,uvRatio:Gae}))(),dd=(()=>xL(Vae))();var Zae=(e)=>e/4294967296|0,Wae=(e)=>e>>>0;function TL(e,t,r,n){let o=Zae(r),i=Wae(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function vL(e,t,r){return e&t^~e&r}function EL(e,t,r){return e&t^e&r^t&r}class yv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=zy(this.buffer)}update(e){YT(this),Ny(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=zy(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){YT(this),k4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);TL(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:zy(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var PL=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Kae=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fa=new Uint32Array(64);class AL extends yv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)fa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=fa[l-15],h=fa[l-2],g=Eo(p,7)^Eo(p,18)^p>>>3,x=Eo(h,17)^Eo(h,19)^h>>>10;fa[l]=x+fa[l-7]+g+fa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Eo(s,6)^Eo(s,11)^Eo(s,25),h=d+p+vL(s,a,c)+Kae[l]+fa[l]|0,x=(Eo(r,2)^Eo(r,13)^Eo(r,22))+EL(r,n,o)|0;d=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+x|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){$y(fa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),$y(this.buffer)}}class IL extends AL{constructor(){super(32,PL)}}var Vy=O4(()=>new IL,C4(1));function Zy(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=dd.utils.randomPrivateKey();return{publicKey:dd.getPublicKey(e),privateKey:e}}function Wy(e){return Gi(e.publicKey)}function Ky(e){return Gi(e.privateKey)}function kL(e,t){return{publicKey:Cf(e),privateKey:Cf(t)}}function RL(e){return Gi(Vy(e))}function OL(e,t,r,n){return`${e.toUpperCase()}
136
+ `}class VT{constructor(e=g4.stdin,t=g4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new GT,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise((t)=>{let r=h4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var Cy={name:"@0xmonaco/mcp-server",version:"1.0.74",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",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.74","@0xmonaco/types":"1.0.74","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var My=["read","market-maker","full"],ei=[{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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",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:"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:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",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"}],sTe=ei.map((e)=>e.name),y4=ei.filter((e)=>e.authMode==="public").map((e)=>e.name),aTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),cTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),uTe=ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),dTe=ei.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),b4=ei.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var pae=new Map(ei.map((e)=>[e.name,e.sideEffect]));function x4(e){let t=pae.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var _4={read:0,"market-maker":1,full:2},ZT=y4,WT=Object.fromEntries(ei.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),w4=Object.fromEntries(Object.entries(WT).map(([e,t])=>[e,t.capability])),fTe=new Set(b4);function S4(e){let t=WT[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function T4(e){return S4(e)==="read"}function v4(e,t){if(t.network==="mainnet"&&WT[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(ZT.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return _4[t.capability]>=_4[S4(e)]}var fae=new Set([...ZT,...Object.keys(w4)]),mae={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 E4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function bc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!My.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${My.join(", ")}.`);let c=a||"read",d=E4(e.MONACO_TOOL_ALLOWLIST),l=E4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((x)=>!fae.has(x)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||mae[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let x=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!x)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=x}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:d,deny:l,delegatedOwnerUserId:g}}function hae(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Gr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Gr(r));let t={};for(let[r,n]of Object.entries(e))t[hae(r)]=typeof n==="object"&&n!==null?Gr(n):n;return t}function P4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var KT=(e)=>e?`"${e}" `:"";function gae(e,t=""){if(typeof e!=="number")throw TypeError(KT(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(KT(t)+"expected integer >= 0, got "+e);return e}function Ny(e,t,r=""){if(P4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)gae(t,"length");let n=P4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=KT(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var yae=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},A4=(e,t)=>{yae(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function YT(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function k4(e,t){Ny(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function $y(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Eo(e,t){return e<<32-t|e>>>t}var R4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),bae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gi(e){if(Ny(e),R4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=bae[e[r]];return t}function I4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Cf(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(R4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=I4(e.charCodeAt(i)),a=I4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function xc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{$y(t)}}function xae(e,t,r="opts"){if(A4(e,"defaults"),t!==void 0)A4(t,r);return Object.assign(Object.create(null),e,t)}function O4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=xae({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var C4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});tv();Sc();hv();ud();Df();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ni=BigInt(0),un=BigInt(1),bL=BigInt(2),Lae=BigInt(8),Bae={zip215:!0};function Dae(e){let t=Ff(e);return Ji(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function xL(e){let t=Dae(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=bL<<BigInt(a*8)-un,l=r.create,p=Qi(t.n,t.nBitLength);function h(z,j){let J=r.sqr(z),ve=r.sqr(j),re=r.add(r.mul(t.a,J),ve),$e=r.add(r.ONE,r.mul(t.d,r.mul(J,ve)));return r.eql(re,$e)}if(!h(t.Gx,t.Gy))throw Error("bad curve params: generator point");let g=t.uvRatio||((z,j)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(j))}}catch(J){return{isValid:!1,value:ni}}}),x=t.adjustScalarBytes||((z)=>z),_=t.domain||((z,j,J)=>{if(ri("phflag",J),j.length||J)throw Error("Contexts/pre-hash are not supported");return z});function S(z,j,J=!1){let ve=J?un:ni;zn("coordinate "+z,j,ve,d)}function w(z){if(!(z instanceof v))throw Error("ExtendedPoint expected")}let A=ad((z,j)=>{let{ex:J,ey:ve,ez:re}=z,$e=z.is0();if(j==null)j=$e?Lae:r.inv(re);let Ie=l(J*j),Re=l(ve*j),nt=l(re*j);if($e)return{x:ni,y:un};if(nt!==un)throw Error("invZ was invalid");return{x:Ie,y:Re}}),T=ad((z)=>{let{a:j,d:J}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:ve,ey:re,ez:$e,et:Ie}=z,Re=l(ve*ve),nt=l(re*re),yt=l($e*$e),ft=l(yt*yt),Ct=l(Re*j),qt=l(yt*l(Ct+nt)),ar=l(ft+l(J*l(Re*nt)));if(qt!==ar)throw Error("bad point: equation left != right (1)");let Or=l(ve*re),rr=l($e*Ie);if(Or!==rr)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(z,j,J,ve){S("x",z),S("y",j),S("z",J,!0),S("t",ve),this.ex=z,this.ey=j,this.ez=J,this.et=ve,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof v)throw Error("extended point not allowed");let{x:j,y:J}=z||{};return S("x",j),S("y",J),new v(j,J,un,l(j*J))}static normalizeZ(z){let j=cd(r,z.map((J)=>J.ez));return z.map((J,ve)=>J.toAffine(j[ve])).map(v.fromAffine)}static msm(z,j){return Gy(v,p,z,j)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){T(this)}equals(z){w(z);let{ex:j,ey:J,ez:ve}=this,{ex:re,ey:$e,ez:Ie}=z,Re=l(j*Ie),nt=l(re*ve),yt=l(J*Ie),ft=l($e*ve);return Re===nt&&yt===ft}is0(){return this.equals(v.ZERO)}negate(){return new v(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:j,ey:J,ez:ve}=this,re=l(j*j),$e=l(J*J),Ie=l(bL*l(ve*ve)),Re=l(z*re),nt=j+J,yt=l(l(nt*nt)-re-$e),ft=Re+$e,Ct=ft-Ie,qt=Re-$e,ar=l(yt*Ct),Or=l(ft*qt),rr=l(yt*qt),Jr=l(Ct*ft);return new v(ar,Or,Jr,rr)}add(z){w(z);let{a:j,d:J}=t,{ex:ve,ey:re,ez:$e,et:Ie}=this,{ex:Re,ey:nt,ez:yt,et:ft}=z,Ct=l(ve*Re),qt=l(re*nt),ar=l(Ie*J*ft),Or=l($e*yt),rr=l((ve+re)*(Re+nt)-Ct-qt),Jr=Or-ar,q=Or+ar,ue=l(qt-j*Ct),he=l(rr*Jr),Ee=l(q*ue),ce=l(rr*ue),Me=l(Jr*q);return new v(he,Ee,Me,ce)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,v.normalizeZ)}multiply(z){let j=z;zn("scalar",j,un,n);let{p:J,f:ve}=this.wNAF(j);return v.normalizeZ([J,ve])[0]}multiplyUnsafe(z,j=v.ZERO){let J=z;if(zn("scalar",J,ni,n),J===ni)return R;if(this.is0()||J===un)return this;return O.wNAFCachedUnsafe(this,J,v.normalizeZ,j)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===un)return this;return this.multiplyUnsafe(z)}static fromHex(z,j=!1){let{d:J,a:ve}=t,re=r.BYTES;z=Zt("pointHex",z,re),ri("zip215",j);let $e=z.slice(),Ie=z[re-1];$e[re-1]=Ie&-129;let Re=Ec($e),nt=j?d:r.ORDER;zn("pointHex.y",Re,ni,nt);let yt=l(Re*Re),ft=l(yt-un),Ct=l(J*yt-ve),{isValid:qt,value:ar}=g(ft,Ct);if(!qt)throw Error("Point.fromHex: invalid y coordinate");let Or=(ar&un)===un,rr=(Ie&128)!==0;if(!j&&ar===ni&&rr)throw Error("Point.fromHex: x=0 and x_0=1");if(rr!==Or)ar=l(-ar);return v.fromAffine({x:ar,y:Re})}static fromPrivateKey(z){let{scalar:j}=C(z);return P.multiply(j)}toRawBytes(){let{x:z,y:j}=this.toAffine(),J=sd(j,r.BYTES);return J[J.length-1]|=z&un?128:0,J}toHex(){return la(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,un,l(t.Gx*t.Gy)),v.ZERO=new v(ni,un,un,ni);let{BASE:P,ZERO:R}=v,O=Hy(v,a*8);function L(z){return vt(z,n)}function G(z){return L(Ec(z))}function C(z){let j=r.BYTES;z=Zt("private key",z,j);let J=Zt("hashed private key",i(z),2*j),ve=x(J.slice(0,j)),re=J.slice(j,2*j),$e=G(ve);return{head:ve,prefix:re,scalar:$e}}function Y(z){let{head:j,prefix:J,scalar:ve}=C(z),re=P.multiply(ve),$e=re.toRawBytes();return{head:j,prefix:J,scalar:ve,point:re,pointBytes:$e}}function W(z){return Y(z).pointBytes}function le(z=Uint8Array.of(),...j){let J=pa(...j);return G(i(_(J,Zt("context",z),!!o)))}function fe(z,j,J={}){if(z=Zt("message",z),o)z=o(z);let{prefix:ve,scalar:re,pointBytes:$e}=Y(j),Ie=le(J.context,ve,z),Re=P.multiply(Ie).toRawBytes(),nt=le(J.context,Re,$e,z),yt=L(Ie+nt*re);zn("signature.s",yt,ni,n);let ft=pa(Re,sd(yt,r.BYTES));return Zt("result",ft,r.BYTES*2)}let U=Bae;function ee(z,j,J,ve=U){let{context:re,zip215:$e}=ve,Ie=r.BYTES;if(z=Zt("signature",z,2*Ie),j=Zt("message",j),J=Zt("publicKey",J,Ie),$e!==void 0)ri("zip215",$e);if(o)j=o(j);let Re=Ec(z.slice(Ie,2*Ie)),nt,yt,ft;try{nt=v.fromHex(J,$e),yt=v.fromHex(z.slice(0,Ie),$e),ft=P.multiplyUnsafe(Re)}catch(ar){return!1}if(!$e&&nt.isSmallOrder())return!1;let Ct=le(re,yt.toRawBytes(),nt.toRawBytes(),j);return yt.add(nt.multiplyUnsafe(Ct)).subtract(ft).clearCofactor().equals(v.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:W,sign:fe,verify:ee,ExtendedPoint:v,utils:{getExtendedPublicKey:Y,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,j=v.BASE){return j._setWindowSize(z),j.multiply(BigInt(3)),j}}}}ud();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var gv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_L=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ZTe=BigInt(0),Fae=BigInt(1),wL=BigInt(2),WTe=BigInt(3),Uae=BigInt(5),jae=BigInt(8);function qae(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=gv,a=e*e%i*e%i,c=Wt(a,wL,i)*a%i,d=Wt(c,Fae,i)*e%i,l=Wt(d,Uae,i)*d%i,p=Wt(l,t,i)*l%i,h=Wt(p,r,i)*p%i,g=Wt(h,n,i)*h%i,x=Wt(g,o,i)*g%i,_=Wt(x,o,i)*g%i,S=Wt(_,t,i)*l%i;return{pow_p_5_8:Wt(S,wL,i)*e%i,b2:a}}function Hae(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Gae(e,t){let r=gv,n=vt(t*t*t,r),o=vt(n*n*t,r),i=qae(e*o).pow_p_5_8,s=vt(e*n*i,r),a=vt(t*s*s,r),c=s,d=vt(s*_L,r),l=a===e,p=a===vt(-e,r),h=a===vt(-e*_L,r);if(l)s=c;if(p||h)s=d;if(lL(s,r))s=vt(-s,r);return{isValid:l||p,value:s}}var SL=(()=>Qi(gv,void 0,!0))(),Vae=(()=>({a:SL.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:SL,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:jae,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:X4,randomBytes:Dy,adjustScalarBytes:Hae,uvRatio:Gae}))(),dd=(()=>xL(Vae))();var Zae=(e)=>e/4294967296|0,Wae=(e)=>e>>>0;function TL(e,t,r,n){let o=Zae(r),i=Wae(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function vL(e,t,r){return e&t^~e&r}function EL(e,t,r){return e&t^e&r^t&r}class yv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=zy(this.buffer)}update(e){YT(this),Ny(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=zy(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){YT(this),k4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);TL(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:zy(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var PL=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Kae=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fa=new Uint32Array(64);class AL extends yv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)fa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=fa[l-15],h=fa[l-2],g=Eo(p,7)^Eo(p,18)^p>>>3,x=Eo(h,17)^Eo(h,19)^h>>>10;fa[l]=x+fa[l-7]+g+fa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Eo(s,6)^Eo(s,11)^Eo(s,25),h=d+p+vL(s,a,c)+Kae[l]+fa[l]|0,x=(Eo(r,2)^Eo(r,13)^Eo(r,22))+EL(r,n,o)|0;d=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+x|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){$y(fa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),$y(this.buffer)}}class IL extends AL{constructor(){super(32,PL)}}var Vy=O4(()=>new IL,C4(1));function Zy(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=dd.utils.randomPrivateKey();return{publicKey:dd.getPublicKey(e),privateKey:e}}function Wy(e){return Gi(e.publicKey)}function Ky(e){return Gi(e.privateKey)}function kL(e,t){return{publicKey:Cf(e),privateKey:Cf(t)}}function RL(e){return Gi(Vy(e))}function OL(e,t,r,n){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${n}`}function CL(e,t){return`WS-AUTH
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/mcp-server",
3
- "version": "1.0.73-develop.af0f5d0",
3
+ "version": "1.0.74",
4
4
  "type": "module",
5
5
  "homepage": "https://docs.0xmonaco.com/sdk/typescript",
6
6
  "description": "MCP server for the Monaco SDK",
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "author": "@codebycarson",
23
23
  "dependencies": {
24
- "@0xmonaco/core": "1.0.73-develop.af0f5d0",
25
- "@0xmonaco/types": "1.0.73-develop.af0f5d0",
24
+ "@0xmonaco/core": "1.0.74",
25
+ "@0xmonaco/types": "1.0.74",
26
26
  "@modelcontextprotocol/sdk": "^1.29.0",
27
27
  "node-fetch": "^3.3.2",
28
28
  "viem": "^2.56.3",