@0xmonaco/mcp-server 1.0.41-develop.ebb62ed → 1.0.42

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
  `:`[${o[c]}\r
134
134
  ]`;continue}if(n+=o[c],o[c]==="\\")i=!0;else if(s&&o[c]==="]")s=!1;else if(!s&&o[c]==="[")s=!0}try{new RegExp(n)}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 n}function Jv(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((o,n)=>({...o,[n]:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Wt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Be(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:o,...n}=Kv(e.keyType._def,t);return{...r,propertyNames:n}}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:o,...n}=Wv(e.keyType._def,t);return{...r,propertyNames:n}}return r}function PD(e,t){if(t.mapStrategy==="record")return Jv(e,t);let r=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Wt(t),o=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Wt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function kD(e){let t=e.values,o=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),n=Array.from(new Set(o.map((i)=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function AD(e){return e.target==="openAi"?void 0:{not:Wt({...e,currentPath:[...e.currentPath,"not"]})}}function $D(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $h={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function OD(e,t){if(t.target==="openApi3")return RD(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((o)=>(o._def.typeName in $h)&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let s=$h[i._def.typeName];return s&&!n.includes(s)?[...n,s]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every((o)=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...n,s];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){let n=o.filter((i,s,a)=>a.indexOf(i)===s);return{type:n.length>1?n:n[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((o)=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter((i)=>!o.includes(i))],[])};return RD(e,t)}var RD=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>Be(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter((o)=>!!o&&(!t.strictUnions||typeof o==="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function CD(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:$h[e.innerType._def.typeName],nullable:!0};return{type:[$h[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let o=Be(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(o&&"$ref"in o)return{allOf:[o],nullable:!0};return o&&{...o,nullable:!0}}let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function zD(e,t){let r={type:"number"};if(!e.checks)return r;for(let o of e.checks)switch(o.kind){case"int":r.type="integer",HA(r,"type",o.message,t);break;case"min":if(t.target==="jsonSchema7")if(o.inclusive)at(r,"minimum",o.value,o.message,t);else at(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)at(r,"maximum",o.value,o.message,t);else at(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",o.value,o.message,t)}break;case"multipleOf":at(r,"multipleOf",o.value,o.message,t);break}return r}function ND(e,t){let r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=rse(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let d=Be(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(o.properties[a]=d,!u)n.push(a)}if(n.length)o.required=n;let s=tse(e,t);if(s!==void 0)o.additionalProperties=s;return o}function tse(e,t){if(e.catchall._def.typeName!=="ZodNever")return Be(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 rse(e){try{return e.isOptional()}catch{return!0}}var MD=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Be(e.innerType._def,t);let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Wt(t)},r]}:Wt(t)};var BD=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);else if(t.pipeStrategy==="output")return Be(e.out._def,t);let r=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter((n)=>n!==void 0)}};function DD(e,t){return Be(e.type._def,t)}function UD(e,t){let o={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)at(o,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)at(o,"maxItems",e.maxSize.value,e.maxSize.message,t);return o}function LD(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:Be(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,o)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function jD(e){return{not:Wt(e)}}function FD(e){return Wt(e)}var qD=(e,t)=>Be(e.innerType._def,t);var HD=(e,t,r)=>{switch(t){case se.ZodString:return Kv(e,r);case se.ZodNumber:return zD(e,r);case se.ZodObject:return ND(e,r);case se.ZodBigInt:return bD(e,r);case se.ZodBoolean:return xD();case se.ZodDate:return GA(e,r);case se.ZodUndefined:return jD(r);case se.ZodNull:return $D(r);case se.ZodArray:return yD(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return OD(e,r);case se.ZodIntersection:return TD(e,r);case se.ZodTuple:return LD(e,r);case se.ZodRecord:return Jv(e,r);case se.ZodLiteral:return ED(e,r);case se.ZodEnum:return SD(e);case se.ZodNativeEnum:return kD(e);case se.ZodNullable:return CD(e,r);case se.ZodOptional:return MD(e,r);case se.ZodMap:return PD(e,r);case se.ZodSet:return UD(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return DD(e,r);case se.ZodNaN:case se.ZodNever:return AD(r);case se.ZodEffects:return wD(e,r);case se.ZodAny:return Wt(r);case se.ZodUnknown:return FD(r);case se.ZodDefault:return _D(e,r);case se.ZodBranded:return Wv(e,r);case se.ZodReadonly:return qD(e,r);case se.ZodCatch:return vD(e,r);case se.ZodPipeline:return BD(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return((o)=>{return})(t)}};function Be(e,t,r=!1){let o=t.seen.get(e);if(t.override){let a=t.override?.(e,t,o,r);if(a!==mD)return a}if(o&&!r){let a=nse(o,t);if(a!==void 0)return a}let n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);let i=HD(e,e.typeName,t),s=typeof i==="function"?Be(i(),t):i;if(s)ose(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var nse=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Zv(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Wt(t);return t.$refStrategy==="seen"?Wt(t):void 0}}},ose=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var WA=(e,t)=>{let r=gD(t),o=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:Be(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Wt(r)}),{}):void 0,n=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Be(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Wt(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(!o)o={};if(!o[r.openAiAnyTypeName])o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]: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 ise(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 KA(e,t){if(io(e))return Yc(e,{target:ise(t?.target),io:t?.pipeStrategy??"input"});return WA(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function JA(e){let r=Ia(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Jx(r);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function YA(e,t){let r=Ea(e,t);if(!r.success)throw r.error;return r.data}var sse=60000;class QA{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($v,(t)=>{this._oncancel(t)}),this.setNotificationHandler(Ov,(t)=>{this._onprogress(t)}),this.setRequestHandler(Rv,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Cv,async(t,r)=>{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ee(Re.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Nv,async(t,r)=>{let o=async()=>{let n=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(n,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(a);else{let d=a,p=new Ee(d.error.code,d.error.message,d.error.data);u(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(n,r.sessionId);if(!i)throw new Ee(Re.InvalidParams,`Task not found: ${n}`);if(!Aa(i.status))return await this._waitForTaskUpdate(n,r.signal),await o();if(Aa(i.status)){let s=await this._taskStore.getTaskResult(n,r.sessionId);return this._clearTaskQueue(n),{...s,_meta:{...s._meta,[ka]:{taskId:n}}}}return await o()};return await o()}),this.setRequestHandler(Mv,async(t,r)=>{try{let{tasks:o,nextCursor:n}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:o,nextCursor:n,_meta:{}}}catch(o){throw new Ee(Re.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Dv,async(t,r)=>{try{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ee(Re.InvalidParams,`Task not found: ${t.params.taskId}`);if(Aa(o.status))throw new Ee(Re.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ee(Re.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...n}}catch(o){if(o instanceof Ee)throw o;throw new Ee(Re.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_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),Ee.fromError(Re.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=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),_h(n)||tD(n))this._onresponse(n);else if($A(n))this._onrequest(n,i);else if(eD(n))this._onnotification(n);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},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=Ee.fromError(Re.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,o=this._transport,n=e.params?._meta?.[ka]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Re.MethodNotFound,message:"Method not found"}};if(n&&this._taskMessageQueue)this._enqueueTaskMessage(n,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=YB(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};if(n)d.relatedTask={taskId:n};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(i.signal.aborted)throw new Ee(Re.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(n&&!m.relatedTask)m.relatedTask={taskId:n};let h=m.relatedTask?.taskId??n;if(h&&a)await a.updateTaskStatus(h,"input_required");return await this.request(u,d,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,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(u)=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Re.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),_h(e))r(e);else{let i=new Ee(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(t);if(o===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 n=!1;if(_h(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")n=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!n)this._progressHandlers.delete(t);if(_h(e))o(e);else{let i=Ee.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ee?i:new Ee(Re.InternalError,String(i))}}return}let n;try{let i=await this.request(e,wd,r);if(i.task)n=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ee(Re.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:s},Aa(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:n},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ee(Re.InternalError,`Task ${n} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ee(Re.InternalError,`Task ${n} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:n},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 Ee?i:new Ee(Re.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,u)=>{let d=(v)=>{u(v)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(v){d(v);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[ka]:a}};let h=(v)=>{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(v)}},{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((w)=>this._onerror(Error(`Failed to send cancellation: ${w}`)));let E=v instanceof Ee?v:new Ee(Re.RequestTimeout,String(v));u(E)};this._responseHandlers.set(p,(v)=>{if(r?.signal?.aborted)return;if(v instanceof Error)return u(v);try{let E=Ea(t,v.result);if(!E.success)u(E.error);else c(E.data)}catch(E){u(E)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let y=r?.timeout??sse,x=()=>h(Ee.fromError(Re.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let v=(E)=>{let w=this._responseHandlers.get(p);if(w)w(E);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(p),u(E)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((v)=>{this._cleanupTimeout(p),u(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},zv,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},Bv,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},oD,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||{},[ka]: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||{},[ka]: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||{},[ka]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=JA(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,n)=>{let i=YA(e,o);return Promise.resolve(t(i,n))})}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=JA(e);this._notificationHandlers.set(r,(o)=>{let n=YA(e,o);return Promise.resolve(t(n))})}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 o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let o of r)if(o.type==="request"&&$A(o.message)){let n=o.message.id,i=this._requestResolvers.get(n);if(i)i(new Ee(Re.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n);else this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e);if(o?.pollInterval)r=o.pollInterval}catch{}return new Promise((o,n)=>{if(t.aborted){n(new Ee(Re.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);t.addEventListener("abort",()=>{clearTimeout(i),n(new Ee(Re.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(o)=>{if(!e)throw Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async(o)=>{let n=await r.getTask(o,t);if(!n)throw new Ee(Re.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(o,n,i)=>{await r.storeTaskResult(o,n,i,t);let s=await r.getTask(o,t);if(s){let a=Ih.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Aa(s.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>r.getTaskResult(o,t),updateTaskStatus:async(o,n,i)=>{let s=await r.getTask(o,t);if(!s)throw new Ee(Re.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Aa(s.status))throw new Ee(Re.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,n,i,t);let a=await r.getTask(o,t);if(a){let c=Ih.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Aa(a.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>r.listTasks(o,t)}}}function GD(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function VD(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];if(GD(s)&&GD(i))r[n]={...s,...i};else r[n]=i}return r}var k3=rn(Z6(),1),A3=rn(P3(),1);function kme(){let e=new k3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return A3.default(e),e}class n${constructor(e){this._ajv=e??kme()}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 o${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 o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.some((u)=>u.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((u)=>u.type==="tool_use");if(i){if(n.some((u)=>u.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 u=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),d=new Set(n.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(u.size!==d.size||![...u].every((p)=>d.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},Ah,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){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 n=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:n},Ed,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 $3(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 R3(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 i$ extends QA{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(kh.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let n=this._loggingLevels.get(o);return n?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new n$,this.setRequestHandler(CA,(r)=>this._oninitialize(r)),this.setNotificationHandler(zA,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(jA,async(r,o)=>{let n=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=kh.safeParse(i);if(s.success)this._loggingLevels.set(n,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new o$(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=VD(this._capabilities,e)}setRequestHandler(e,t){let o=Ia(e)?.method;if(!o)throw Error("Schema is missing a method literal");let n;if(io(o)){let s=o;n=s._zod?.def?.value??s.value}else{let s=o;n=s._def?.value??s.value}if(typeof n!=="string")throw Error("Schema method literal must be a string");if(n==="tools/call"){let s=async(a,c)=>{let u=Ea(Td,a);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new Ee(Re.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=u.data,p=await Promise.resolve(t(a,c));if(d.task){let h=Ea(wd,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new Ee(Re.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let m=Ea(Gv,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Ee(Re.InvalidParams,`Invalid tools/call result: ${h}`)}return m.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){R3(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;$3(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:WB.includes(t)?t:kA,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"},Av)}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],o=Array.isArray(r.content)?r.content:[r.content],n=o.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(n){if(o.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((d)=>d.type==="tool_use").map((d)=>d.id)),u=new Set(o.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==u.size||![...c].every((d)=>u.has(d)))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},FA,t);return this.request({method:"sampling/createMessage",params:e},Ah,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 o=e;return this.request({method:"elicitation/create",params:o},Ed,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},n=await this.request({method:"elicitation/create",params:o},Ed,t);if(n.action==="accept"&&n.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(n.content);if(!s.valid)throw new Ee(Re.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ee)throw i;throw new Ee(Re.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return n}}}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},qA,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 C3=Symbol.for("mcp.completable");function s$(e){return!!e&&typeof e==="object"&&C3 in e}function z3(e){return e[C3]?.complete}var O3;(function(e){e.Completable="McpCompletable"})(O3||(O3={}));var Ame=/^[A-Za-z0-9._-]{1,128}$/;function $me(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(!Ame.test(e)){let r=e.split("").filter((o)=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return t.push(`Tool name contains invalid characters: ${r.map((o)=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Rme(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 a$(e){let t=$me(e);return Rme(e,t.warnings),t.isValid}class c${constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let o={taskSupport:"required",...t.execution};if(o.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,o,t._meta,r)}}class l${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 i$(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new c$(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(Ba(Hv)),this.server.assertCanSetRequestHandler(Ba(Td)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Hv,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=dd(t.inputSchema);return o?KA(o,{strictUnions:!0,pipeStrategy:"input"}):Ome})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=dd(t.outputSchema);if(o)r.outputSchema=KA(o,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Td,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ee(Re.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ee(Re.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,n=r.execution?.taskSupport,i="createTask"in r.handler;if((n==="required"||n==="optional")&&!i)throw new Ee(Re.InternalError,`Tool ${e.params.name} has taskSupport '${n}' but was not registered with registerToolTask`);if(n==="required"&&!o)throw new Ee(Re.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(n==="optional"&&!o&&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(o)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ee){if(r.code===Re.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 n=dd(e.inputSchema)??e.inputSchema,i=await Wx(n,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=Kx(s);throw new Ee(Re.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 Ee(Re.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=dd(e.outputSchema),n=await Wx(o,t.structuredContent);if(!n.success){let i="error"in n?n.error:"Unknown error",s=Kx(i);throw new Ee(Re.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(o.createTask(t,i));else return await Promise.resolve(o.createTask(i))}if(e.inputSchema)return await Promise.resolve(o(t,r));else return await Promise.resolve(o(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),n=e.handler,i={...r,taskStore:r.taskStore},s=o?await Promise.resolve(n.createTask(o,i)):await Promise.resolve(n.createTask(i)),a=s.task.taskId,c=s.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,u));let d=await r.taskStore.getTask(a);if(!d)throw new Ee(Re.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Ba(Vv)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Vv,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return lD(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return dD(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ee(Re.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ee(Re.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ee(Re.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return eg;let n=Ia(r.argsSchema)?.[e.params.argument.name];if(!s$(n))return eg;let i=z3(n);if(!i)return eg;let s=await i(e.params.argument.value,e.params.context);return M3(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 eg;throw new Ee(Re.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return eg;let n=await o(e.params.argument.value,e.params.context);return M3(n)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Ba(Uv)),this.server.assertCanSetRequestHandler(Ba(Lv)),this.server.assertCanSetRequestHandler(Ba(jv)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Uv,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([n,i])=>i.enabled).map(([n,i])=>({uri:n,name:i.name,...i.metadata})),o=[];for(let n of Object.values(this._registeredResourceTemplates)){if(!n.resourceTemplate.listCallback)continue;let i=await n.resourceTemplate.listCallback(t);for(let s of i.resources)o.push({...n.metadata,...s})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Lv,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(jv,async(e,t)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Ee(Re.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,t)}for(let n of Object.values(this._registeredResourceTemplates)){let i=n.resourceTemplate.uriTemplate.match(r.toString());if(i)return n.readCallback(r,i,t)}throw new Ee(Re.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Ba(Fv)),this.server.assertCanSetRequestHandler(Ba(qv)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Fv,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Cme(t.argsSchema):void 0}))})),this.server.setRequestHandler(qv,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ee(Re.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ee(Re.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=dd(r.argsSchema),n=await Wx(o,e.params.arguments);if(!n.success){let a="error"in n?n.error:"Unknown error",c=Kx(a);throw new Ee(Re.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=n.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let o=r.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let o;if(typeof r[0]==="object")o=r.shift();let n=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,o,n);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,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,o){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}_createRegisteredResource(e,t,r,o,n){let i={name:e,title:t,metadata:o,readCallback:n,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,o,n){let i={resourceTemplate:r,title:t,metadata:o,readCallback:n,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,o,n){let i={title:t,description:r,argsSchema:o===void 0?void 0:Qc(o),callback:n,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=Qc(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,o){if(Object.values(o).some((a)=>{let c=a instanceof vd?a._def?.innerType:a;return s$(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,o,n,i,s,a,c){a$(e);let u={title:t,description:r,inputSchema:N3(o),outputSchema:N3(n),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")a$(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=u}if(typeof d.title<"u")u.title=d.title;if(typeof d.description<"u")u.description=d.description;if(typeof d.paramsSchema<"u")u.inputSchema=Qc(d.paramsSchema);if(typeof d.outputSchema<"u")u.outputSchema=Qc(d.outputSchema);if(typeof d.callback<"u")u.handler=d.callback;if(typeof d.annotations<"u")u.annotations=d.annotations;if(typeof d._meta<"u")u._meta=d._meta;if(typeof d.enabled<"u")u.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,o,n,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(u$(a)){if(o=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!u$(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,o,n,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:o,description:n,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,o,n,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 o;if(t.length>1)o=t.shift();let n=t[0],i=this._createRegisteredPrompt(e,void 0,r,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:o,description:n,argsSchema:i}=t,s=this._createRegisteredPrompt(e,o,n,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 Ome={type:"object",properties:{}};function B3(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function D3(e){return"_def"in e||"_zod"in e||B3(e)}function u$(e){if(typeof e!=="object"||e===null)return!1;if(D3(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(B3)}function N3(e){if(!e)return;if(u$(e))return Qc(e);if(!D3(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Cme(e){let t=Ia(e);if(!t)return[];return Object.entries(t).map(([r,o])=>{let n=C4(o),i=z4(o);return{name:r,description:n,required:!i}})}function Ba(e){let r=Ia(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Jx(r);if(typeof o==="string")return o;throw Error("Schema method literal must be a string")}function M3(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var eg={completion:{values:[],hasMore:!1}};import L3 from"node:process";class d${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),zme(t)}clear(){this._buffer=void 0}}function zme(e){return rD.parse(JSON.parse(e))}function U3(e){return JSON.stringify(e)+`
136
- `}class p${constructor(e=L3.stdin,t=L3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new d$,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=U3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.41",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.41","@0xmonaco/types":"1.0.41","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var z_=["read","market-maker","full"],Ti=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],t$e=Ti.map((e)=>e.name),j3=Ti.filter((e)=>e.authMode==="public").map((e)=>e.name),r$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),n$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),o$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),i$e=Ti.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),F3=Ti.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Mme=new Map(Ti.map((e)=>[e.name,e.sideEffect]));function q3(e){let t=Mme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var H3={read:0,"market-maker":1,full:2},f$=j3,m$=Object.fromEntries(Ti.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),G3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),c$e=new Set(F3);function V3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Z3(e){return V3(e)==="read"}function W3(e,t){if(t.network==="mainnet"&&m$[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(f$.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return H3[t.capability]>=H3[V3(e)]}var Bme=new Set([...f$,...Object.keys(G3)]),Dme={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 K3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function au(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 o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!z_.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${z_.join(", ")}.`);let c=a||"read",u=K3(e.MONACO_TOOL_ALLOWLIST),d=K3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Bme.has(y)).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 m=e.MONACO_RPC_URL||Dme[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)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).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function Ume(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function jo(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>jo(r));let t={};for(let[r,o]of Object.entries(e))t[Ume(r)]=typeof o==="object"&&o!==null?jo(o):o;return t}po();ig();po();O$();vu();bu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ki=BigInt(0),mn=BigInt(1),MF=BigInt(2),ahe=BigInt(8),che={zip215:!0};function uhe(e){let t=cg(e);return Ho(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function BF(e){let t=uhe(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=MF<<BigInt(a*8)-mn,d=r.create,p=ws(t.n,t.nBitLength);function m(C,D){let Z=r.sqr(C),_e=r.sqr(D),Pe=r.add(r.mul(t.a,Z),_e),V=r.add(r.ONE,r.mul(t.d,r.mul(Z,_e)));return r.eql(Pe,V)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,D)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(D))}}catch(Z){return{isValid:!1,value:ki}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,D,Z)=>{if(Ii("phflag",Z),D.length||Z)throw Error("Contexts/pre-hash are not supported");return C});function S(C,D,Z=!1){let _e=Z?mn:ki;pn("coordinate "+C,D,_e,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=qd((C,D)=>{let{ex:Z,ey:_e,ez:Pe}=C,V=C.is0();if(D==null)D=V?ahe:r.inv(Pe);let te=d(Z*D),Q=d(_e*D),me=d(Pe*D);if(V)return{x:ki,y:mn};if(me!==mn)throw Error("invZ was invalid");return{x:te,y:Q}}),w=qd((C)=>{let{a:D,d:Z}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:_e,ey:Pe,ez:V,et:te}=C,Q=d(_e*_e),me=d(Pe*Pe),ne=d(V*V),Ae=d(ne*ne),tt=d(Q*D),Qe=d(ne*d(tt+me)),st=d(Ae+d(Z*d(Q*me)));if(Qe!==st)throw Error("bad point: equation left != right (1)");let br=d(_e*Pe),Et=d(V*te);if(br!==Et)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,D,Z,_e){S("x",C),S("y",D),S("z",Z,!0),S("t",_e),this.ex=C,this.ey=D,this.ez=Z,this.et=_e,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:D,y:Z}=C||{};return S("x",D),S("y",Z),new _(D,Z,mn,d(D*Z))}static normalizeZ(C){let D=_s(r,C.map((Z)=>Z.ez));return C.map((Z,_e)=>Z.toAffine(D[_e])).map(_.fromAffine)}static msm(C,D){return H_(_,p,C,D)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:D,ey:Z,ez:_e}=this,{ex:Pe,ey:V,ez:te}=C,Q=d(D*te),me=d(Pe*_e),ne=d(Z*te),Ae=d(V*_e);return Q===me&&ne===Ae}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:D,ey:Z,ez:_e}=this,Pe=d(D*D),V=d(Z*Z),te=d(MF*d(_e*_e)),Q=d(C*Pe),me=D+Z,ne=d(d(me*me)-Pe-V),Ae=Q+V,tt=Ae-te,Qe=Q-V,st=d(ne*tt),br=d(Ae*Qe),Et=d(ne*Qe),En=d(tt*Ae);return new _(st,br,En,Et)}add(C){v(C);let{a:D,d:Z}=t,{ex:_e,ey:Pe,ez:V,et:te}=this,{ex:Q,ey:me,ez:ne,et:Ae}=C,tt=d(_e*Q),Qe=d(Pe*me),st=d(te*Z*Ae),br=d(V*ne),Et=d((_e+Pe)*(Q+me)-tt-Qe),En=br-st,Wr=br+st,Js=d(Qe-D*tt),Cf=d(Et*En),al=d(Wr*Js),Dy=d(Et*Js),Eo=d(En*Wr);return new _(Cf,al,Eo,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let D=C;pn("scalar",D,mn,o);let{p:Z,f:_e}=this.wNAF(D);return _.normalizeZ([Z,_e])[0]}multiplyUnsafe(C,D=_.ZERO){let Z=C;if(pn("scalar",Z,ki,o),Z===ki)return P;if(this.is0()||Z===mn)return this;return O.wNAFCachedUnsafe(this,Z,_.normalizeZ,D)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===mn)return this;return this.multiplyUnsafe(C)}static fromHex(C,D=!1){let{d:Z,a:_e}=t,Pe=r.BYTES;C=wt("pointHex",C,Pe),Ii("zip215",D);let V=C.slice(),te=C[Pe-1];V[Pe-1]=te&-129;let Q=hu(V),me=D?u:r.ORDER;pn("pointHex.y",Q,ki,me);let ne=d(Q*Q),Ae=d(ne-mn),tt=d(Z*ne-_e),{isValid:Qe,value:st}=h(Ae,tt);if(!Qe)throw Error("Point.fromHex: invalid y coordinate");let br=(st&mn)===mn,Et=(te&128)!==0;if(!D&&st===ki&&Et)throw Error("Point.fromHex: x=0 and x_0=1");if(Et!==br)st=d(-st);return _.fromAffine({x:st,y:Q})}static fromPrivateKey(C){let{scalar:D}=k(C);return T.multiply(D)}toRawBytes(){let{x:C,y:D}=this.toAffine(),Z=Fd(D,r.BYTES);return Z[Z.length-1]|=C&mn?128:0,Z}toHex(){return ja(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(ki,mn,mn,ki);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return ht(C,o)}function M(C){return z(hu(C))}function k(C){let D=r.BYTES;C=wt("private key",C,D);let Z=wt("hashed private key",i(C),2*D),_e=y(Z.slice(0,D)),Pe=Z.slice(D,2*D),V=M(_e);return{head:_e,prefix:Pe,scalar:V}}function H(C){let{head:D,prefix:Z,scalar:_e}=k(C),Pe=T.multiply(_e),V=Pe.toRawBytes();return{head:D,prefix:Z,scalar:_e,point:Pe,pointBytes:V}}function G(C){return H(C).pointBytes}function ue(C=Uint8Array.of(),...D){let Z=_r(...D);return M(i(x(Z,wt("context",C),!!n)))}function W(C,D,Z={}){if(C=wt("message",C),n)C=n(C);let{prefix:_e,scalar:Pe,pointBytes:V}=H(D),te=ue(Z.context,_e,C),Q=T.multiply(te).toRawBytes(),me=ue(Z.context,Q,V,C),ne=z(te+me*Pe);pn("signature.s",ne,ki,o);let Ae=_r(Q,Fd(ne,r.BYTES));return wt("result",Ae,r.BYTES*2)}let q=che;function fe(C,D,Z,_e=q){let{context:Pe,zip215:V}=_e,te=r.BYTES;if(C=wt("signature",C,2*te),D=wt("message",D),Z=wt("publicKey",Z,te),V!==void 0)Ii("zip215",V);if(n)D=n(D);let Q=hu(C.slice(te,2*te)),me,ne,Ae;try{me=_.fromHex(Z,V),ne=_.fromHex(C.slice(0,te),V),Ae=T.multiplyUnsafe(Q)}catch(st){return!1}if(!V&&me.isSmallOrder())return!1;let tt=ue(Pe,ne.toRawBytes(),me.toRawBytes(),D);return ne.add(me.multiplyUnsafe(tt)).subtract(Ae).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:G,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:H,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,D=_.BASE){return D._setWindowSize(C),D.multiply(BigInt(3)),D}}}}vu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),H$e=BigInt(0),mhe=BigInt(1),qF=BigInt(2),G$e=BigInt(3),hhe=BigInt(5),ghe=BigInt(8);function yhe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Kt(a,qF,i)*a%i,u=Kt(c,mhe,i)*e%i,d=Kt(u,hhe,i)*u%i,p=Kt(d,t,i)*d%i,m=Kt(p,r,i)*p%i,h=Kt(m,o,i)*m%i,y=Kt(h,n,i)*h%i,x=Kt(y,n,i)*h%i,S=Kt(x,t,i)*d%i;return{pow_p_5_8:Kt(S,qF,i)*e%i,b2:a}}function bhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function xhe(e,t){let r=C$,o=ht(t*t*t,r),n=ht(o*o*t,r),i=yhe(e*n).pow_p_5_8,s=ht(e*o*i,r),a=ht(t*s*s,r),c=s,u=ht(s*FF,r),d=a===e,p=a===ht(-e,r),m=a===ht(-e*FF,r);if(d)s=c;if(p||m)s=u;if(AF(s,r))s=ht(-s,r);return{isValid:d||p,value:s}}var HF=(()=>ws(C$,void 0,!0))(),vhe=(()=>({a:HF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:HF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ghe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:yF,randomBytes:Ld,adjustScalarBytes:bhe,uvRatio:xhe}))(),G_=(()=>BF(vhe))();ig();po();function V_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=G_.utils.randomPrivateKey();return{publicKey:G_.getPublicKey(e),privateKey:e}}function Z_(e){return lu(e.publicKey)}function W_(e){return lu(e.privateKey)}function GF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function VF(e){return lu(bs(e))}function ZF(e,t,r,o){return`${e.toUpperCase()}
136
+ `}class p${constructor(e=L3.stdin,t=L3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new d$,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=U3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.42",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.42","@0xmonaco/types":"1.0.42","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var z_=["read","market-maker","full"],Ti=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],t$e=Ti.map((e)=>e.name),j3=Ti.filter((e)=>e.authMode==="public").map((e)=>e.name),r$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),n$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),o$e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),i$e=Ti.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),F3=Ti.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Mme=new Map(Ti.map((e)=>[e.name,e.sideEffect]));function q3(e){let t=Mme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var H3={read:0,"market-maker":1,full:2},f$=j3,m$=Object.fromEntries(Ti.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),G3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),c$e=new Set(F3);function V3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Z3(e){return V3(e)==="read"}function W3(e,t){if(t.network==="mainnet"&&m$[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(f$.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return H3[t.capability]>=H3[V3(e)]}var Bme=new Set([...f$,...Object.keys(G3)]),Dme={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 K3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function au(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 o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!z_.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${z_.join(", ")}.`);let c=a||"read",u=K3(e.MONACO_TOOL_ALLOWLIST),d=K3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Bme.has(y)).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 m=e.MONACO_RPC_URL||Dme[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)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).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function Ume(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function jo(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>jo(r));let t={};for(let[r,o]of Object.entries(e))t[Ume(r)]=typeof o==="object"&&o!==null?jo(o):o;return t}po();ig();po();O$();vu();bu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ki=BigInt(0),mn=BigInt(1),MF=BigInt(2),ahe=BigInt(8),che={zip215:!0};function uhe(e){let t=cg(e);return Ho(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function BF(e){let t=uhe(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=MF<<BigInt(a*8)-mn,d=r.create,p=ws(t.n,t.nBitLength);function m(C,D){let Z=r.sqr(C),_e=r.sqr(D),Pe=r.add(r.mul(t.a,Z),_e),V=r.add(r.ONE,r.mul(t.d,r.mul(Z,_e)));return r.eql(Pe,V)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,D)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(D))}}catch(Z){return{isValid:!1,value:ki}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,D,Z)=>{if(Ii("phflag",Z),D.length||Z)throw Error("Contexts/pre-hash are not supported");return C});function S(C,D,Z=!1){let _e=Z?mn:ki;pn("coordinate "+C,D,_e,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=qd((C,D)=>{let{ex:Z,ey:_e,ez:Pe}=C,V=C.is0();if(D==null)D=V?ahe:r.inv(Pe);let te=d(Z*D),Q=d(_e*D),me=d(Pe*D);if(V)return{x:ki,y:mn};if(me!==mn)throw Error("invZ was invalid");return{x:te,y:Q}}),w=qd((C)=>{let{a:D,d:Z}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:_e,ey:Pe,ez:V,et:te}=C,Q=d(_e*_e),me=d(Pe*Pe),ne=d(V*V),Ae=d(ne*ne),tt=d(Q*D),Qe=d(ne*d(tt+me)),st=d(Ae+d(Z*d(Q*me)));if(Qe!==st)throw Error("bad point: equation left != right (1)");let br=d(_e*Pe),Et=d(V*te);if(br!==Et)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,D,Z,_e){S("x",C),S("y",D),S("z",Z,!0),S("t",_e),this.ex=C,this.ey=D,this.ez=Z,this.et=_e,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:D,y:Z}=C||{};return S("x",D),S("y",Z),new _(D,Z,mn,d(D*Z))}static normalizeZ(C){let D=_s(r,C.map((Z)=>Z.ez));return C.map((Z,_e)=>Z.toAffine(D[_e])).map(_.fromAffine)}static msm(C,D){return H_(_,p,C,D)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:D,ey:Z,ez:_e}=this,{ex:Pe,ey:V,ez:te}=C,Q=d(D*te),me=d(Pe*_e),ne=d(Z*te),Ae=d(V*_e);return Q===me&&ne===Ae}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:D,ey:Z,ez:_e}=this,Pe=d(D*D),V=d(Z*Z),te=d(MF*d(_e*_e)),Q=d(C*Pe),me=D+Z,ne=d(d(me*me)-Pe-V),Ae=Q+V,tt=Ae-te,Qe=Q-V,st=d(ne*tt),br=d(Ae*Qe),Et=d(ne*Qe),En=d(tt*Ae);return new _(st,br,En,Et)}add(C){v(C);let{a:D,d:Z}=t,{ex:_e,ey:Pe,ez:V,et:te}=this,{ex:Q,ey:me,ez:ne,et:Ae}=C,tt=d(_e*Q),Qe=d(Pe*me),st=d(te*Z*Ae),br=d(V*ne),Et=d((_e+Pe)*(Q+me)-tt-Qe),En=br-st,Wr=br+st,Js=d(Qe-D*tt),Cf=d(Et*En),al=d(Wr*Js),Dy=d(Et*Js),Eo=d(En*Wr);return new _(Cf,al,Eo,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let D=C;pn("scalar",D,mn,o);let{p:Z,f:_e}=this.wNAF(D);return _.normalizeZ([Z,_e])[0]}multiplyUnsafe(C,D=_.ZERO){let Z=C;if(pn("scalar",Z,ki,o),Z===ki)return P;if(this.is0()||Z===mn)return this;return O.wNAFCachedUnsafe(this,Z,_.normalizeZ,D)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===mn)return this;return this.multiplyUnsafe(C)}static fromHex(C,D=!1){let{d:Z,a:_e}=t,Pe=r.BYTES;C=wt("pointHex",C,Pe),Ii("zip215",D);let V=C.slice(),te=C[Pe-1];V[Pe-1]=te&-129;let Q=hu(V),me=D?u:r.ORDER;pn("pointHex.y",Q,ki,me);let ne=d(Q*Q),Ae=d(ne-mn),tt=d(Z*ne-_e),{isValid:Qe,value:st}=h(Ae,tt);if(!Qe)throw Error("Point.fromHex: invalid y coordinate");let br=(st&mn)===mn,Et=(te&128)!==0;if(!D&&st===ki&&Et)throw Error("Point.fromHex: x=0 and x_0=1");if(Et!==br)st=d(-st);return _.fromAffine({x:st,y:Q})}static fromPrivateKey(C){let{scalar:D}=k(C);return T.multiply(D)}toRawBytes(){let{x:C,y:D}=this.toAffine(),Z=Fd(D,r.BYTES);return Z[Z.length-1]|=C&mn?128:0,Z}toHex(){return ja(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(ki,mn,mn,ki);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return ht(C,o)}function M(C){return z(hu(C))}function k(C){let D=r.BYTES;C=wt("private key",C,D);let Z=wt("hashed private key",i(C),2*D),_e=y(Z.slice(0,D)),Pe=Z.slice(D,2*D),V=M(_e);return{head:_e,prefix:Pe,scalar:V}}function H(C){let{head:D,prefix:Z,scalar:_e}=k(C),Pe=T.multiply(_e),V=Pe.toRawBytes();return{head:D,prefix:Z,scalar:_e,point:Pe,pointBytes:V}}function G(C){return H(C).pointBytes}function ue(C=Uint8Array.of(),...D){let Z=_r(...D);return M(i(x(Z,wt("context",C),!!n)))}function W(C,D,Z={}){if(C=wt("message",C),n)C=n(C);let{prefix:_e,scalar:Pe,pointBytes:V}=H(D),te=ue(Z.context,_e,C),Q=T.multiply(te).toRawBytes(),me=ue(Z.context,Q,V,C),ne=z(te+me*Pe);pn("signature.s",ne,ki,o);let Ae=_r(Q,Fd(ne,r.BYTES));return wt("result",Ae,r.BYTES*2)}let q=che;function fe(C,D,Z,_e=q){let{context:Pe,zip215:V}=_e,te=r.BYTES;if(C=wt("signature",C,2*te),D=wt("message",D),Z=wt("publicKey",Z,te),V!==void 0)Ii("zip215",V);if(n)D=n(D);let Q=hu(C.slice(te,2*te)),me,ne,Ae;try{me=_.fromHex(Z,V),ne=_.fromHex(C.slice(0,te),V),Ae=T.multiplyUnsafe(Q)}catch(st){return!1}if(!V&&me.isSmallOrder())return!1;let tt=ue(Pe,ne.toRawBytes(),me.toRawBytes(),D);return ne.add(me.multiplyUnsafe(tt)).subtract(Ae).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:G,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:H,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,D=_.BASE){return D._setWindowSize(C),D.multiply(BigInt(3)),D}}}}vu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),H$e=BigInt(0),mhe=BigInt(1),qF=BigInt(2),G$e=BigInt(3),hhe=BigInt(5),ghe=BigInt(8);function yhe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Kt(a,qF,i)*a%i,u=Kt(c,mhe,i)*e%i,d=Kt(u,hhe,i)*u%i,p=Kt(d,t,i)*d%i,m=Kt(p,r,i)*p%i,h=Kt(m,o,i)*m%i,y=Kt(h,n,i)*h%i,x=Kt(y,n,i)*h%i,S=Kt(x,t,i)*d%i;return{pow_p_5_8:Kt(S,qF,i)*e%i,b2:a}}function bhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function xhe(e,t){let r=C$,o=ht(t*t*t,r),n=ht(o*o*t,r),i=yhe(e*n).pow_p_5_8,s=ht(e*o*i,r),a=ht(t*s*s,r),c=s,u=ht(s*FF,r),d=a===e,p=a===ht(-e,r),m=a===ht(-e*FF,r);if(d)s=c;if(p||m)s=u;if(AF(s,r))s=ht(-s,r);return{isValid:d||p,value:s}}var HF=(()=>ws(C$,void 0,!0))(),vhe=(()=>({a:HF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:HF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ghe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:yF,randomBytes:Ld,adjustScalarBytes:bhe,uvRatio:xhe}))(),G_=(()=>BF(vhe))();ig();po();function V_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=G_.utils.randomPrivateKey();return{publicKey:G_.getPublicKey(e),privateKey:e}}function Z_(e){return lu(e.publicKey)}function W_(e){return lu(e.privateKey)}function GF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function VF(e){return lu(bs(e))}function ZF(e,t,r,o){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${o}`}function WF(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.41-develop.ebb62ed",
3
+ "version": "1.0.42",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  },
26
26
  "author": "@codebycarson",
27
27
  "dependencies": {
28
- "@0xmonaco/core": "1.0.41-develop.ebb62ed",
29
- "@0xmonaco/types": "1.0.41-develop.ebb62ed",
28
+ "@0xmonaco/core": "1.0.42",
29
+ "@0xmonaco/types": "1.0.42",
30
30
  "@modelcontextprotocol/sdk": "^1.29.0",
31
31
  "node-fetch": "^3.3.2",
32
32
  "viem": "^2.53.1",