@0xmonaco/mcp-server 1.0.39-prerelease.19d492d → 1.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/package.json +3 -3
package/dist/bin.js
CHANGED
|
@@ -133,7 +133,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
133
133
|
`:`[${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===ie.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Gt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ie.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===ie.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ie.ZodBranded&&e.keyType._def.type._def.typeName===ie.ZodString&&e.keyType._def.type._def.checks?.length){let{type:o,...n}=Wv(e.keyType._def,t);return{...r,propertyNames:n}}return r}function ID(e,t){if(t.mapStrategy==="record")return Jv(e,t);let r=Ce(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(t),o=Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function PD(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 kD(e){return e.target==="openAi"?void 0:{not:Gt({...e,currentPath:[...e.currentPath,"not"]})}}function AD(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $h={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function RD(e,t){if(t.target==="openApi3")return $D(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 $D(e,t)}var $D=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>Ce(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 OD(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=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(o&&"$ref"in o)return{allOf:[o],nullable:!0};return o&&{...o,nullable:!0}}let r=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function CD(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)rt(r,"minimum",o.value,o.message,t);else rt(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;rt(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"maximum",o.value,o.message,t);else rt(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;rt(r,"maximum",o.value,o.message,t)}break;case"multipleOf":rt(r,"multipleOf",o.value,o.message,t);break}return r}function zD(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=tse(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let d=Ce(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=ese(e,t);if(s!==void 0)o.additionalProperties=s;return o}function ese(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ce(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 tse(e){try{return e.isOptional()}catch{return!0}}var ND=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ce(e.innerType._def,t);let r=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Gt(t)},r]}:Gt(t)};var MD=(e,t)=>{if(t.pipeStrategy==="input")return Ce(e.in._def,t);else if(t.pipeStrategy==="output")return Ce(e.out._def,t);let r=Ce(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=Ce(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter((n)=>n!==void 0)}};function BD(e,t){return Ce(e.type._def,t)}function DD(e,t){let o={type:"array",uniqueItems:!0,items:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)rt(o,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)rt(o,"maxItems",e.maxSize.value,e.maxSize.message,t);return o}function UD(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>Ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:Ce(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)=>Ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function LD(e){return{not:Gt(e)}}function jD(e){return Gt(e)}var FD=(e,t)=>Ce(e.innerType._def,t);var qD=(e,t,r)=>{switch(t){case ie.ZodString:return Kv(e,r);case ie.ZodNumber:return CD(e,r);case ie.ZodObject:return zD(e,r);case ie.ZodBigInt:return yD(e,r);case ie.ZodBoolean:return bD();case ie.ZodDate:return GA(e,r);case ie.ZodUndefined:return LD(r);case ie.ZodNull:return AD(r);case ie.ZodArray:return gD(e,r);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return RD(e,r);case ie.ZodIntersection:return SD(e,r);case ie.ZodTuple:return UD(e,r);case ie.ZodRecord:return Jv(e,r);case ie.ZodLiteral:return TD(e,r);case ie.ZodEnum:return wD(e);case ie.ZodNativeEnum:return PD(e);case ie.ZodNullable:return OD(e,r);case ie.ZodOptional:return ND(e,r);case ie.ZodMap:return ID(e,r);case ie.ZodSet:return DD(e,r);case ie.ZodLazy:return()=>e.getter()._def;case ie.ZodPromise:return BD(e,r);case ie.ZodNaN:case ie.ZodNever:return kD(r);case ie.ZodEffects:return _D(e,r);case ie.ZodAny:return Gt(r);case ie.ZodUnknown:return jD(r);case ie.ZodDefault:return vD(e,r);case ie.ZodBranded:return Wv(e,r);case ie.ZodReadonly:return FD(e,r);case ie.ZodCatch:return xD(e,r);case ie.ZodPipeline:return MD(e,r);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return((o)=>{return})(t)}};function Ce(e,t,r=!1){let o=t.seen.get(e);if(t.override){let a=t.override?.(e,t,o,r);if(a!==fD)return a}if(o&&!r){let a=rse(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=qD(e,e.typeName,t),s=typeof i==="function"?Ce(i(),t):i;if(s)nse(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var rse=(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`),Gt(t);return t.$refStrategy==="seen"?Gt(t):void 0}}},nse=(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=hD(t),o=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:Ce(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Gt(r)}),{}):void 0,n=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Ce(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Gt(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 ose(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(oo(e))return Jc(e,{target:ose(t?.target),io:t?.pipeStrategy??"input"});return WA(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function JA(e){let r=Ta(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=Sa(e,t);if(!r.success)throw r.error;return r.data}var ise=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 Te(ke.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 Te(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 Te(ke.InvalidParams,`Task not found: ${n}`);if(!Pa(i.status))return await this._waitForTaskUpdate(n,r.signal),await o();if(Pa(i.status)){let s=await this._taskStore.getTaskResult(n,r.sessionId);return this._clearTaskQueue(n),{...s,_meta:{...s._meta,[Ia]:{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 Te(ke.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 Te(ke.InvalidParams,`Task not found: ${t.params.taskId}`);if(Pa(o.status))throw new Te(ke.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 Te(ke.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...n}}catch(o){if(o instanceof Te)throw o;throw new Te(ke.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),Te.fromError(ke.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)||eD(n))this._onresponse(n);else if($A(n))this._onrequest(n,i);else if(XB(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=Te.fromError(ke.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?.[Ia]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ke.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=JB(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 Te(ke.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:ke.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 Te(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=Te.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 Te?i:new Te(ke.InternalError,String(i))}}return}let n;try{let i=await this.request(e,_d,r);if(i.task)n=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Te(ke.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:s},Pa(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 Te(ke.InternalError,`Task ${n} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Te(ke.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 Te?i:new Te(ke.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||{},[Ia]: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 Te?v:new Te(ke.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=Sa(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??ise,x=()=>h(Te.fromError(ke.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},nD,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||{},[Ia]: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||{},[Ia]: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||{},[Ia]: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 Te(ke.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 Te(ke.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);t.addEventListener("abort",()=>{clearTimeout(i),n(new Te(ke.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 Te(ke.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),Pa(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 Te(ke.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Pa(s.status))throw new Te(ke.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),Pa(a.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>r.listTasks(o,t)}}}function HD(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function GD(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(HD(s)&&HD(i))r[n]={...s,...i};else r[n]=i}return r}var P3=rn(Z6(),1),k3=rn(I3(),1);function Pme(){let e=new P3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return k3.default(e),e}class n${constructor(e){this._ajv=e??Pme()}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},Td,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 A3(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 $3(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=GD(this._capabilities,e)}setRequestHandler(e,t){let o=Ta(e)?.method;if(!o)throw Error("Schema is missing a method literal");let n;if(oo(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=Sa(Sd,a);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new Te(ke.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=u.data,p=await Promise.resolve(t(a,c));if(d.task){let h=Sa(_d,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new Te(ke.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let m=Sa(Gv,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Te(ke.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){$3(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;A3(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:ZB.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},Td,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},Td,t);if(n.action==="accept"&&n.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(n.content);if(!s.valid)throw new Te(ke.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Te)throw i;throw new Te(ke.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 O3=Symbol.for("mcp.completable");function s$(e){return!!e&&typeof e==="object"&&O3 in e}function C3(e){return e[O3]?.complete}var R3;(function(e){e.Completable="McpCompletable"})(R3||(R3={}));var kme=/^[A-Za-z0-9._-]{1,128}$/;function Ame(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(!kme.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 $me(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=Ame(e);return $me(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(Na(Hv)),this.server.assertCanSetRequestHandler(Na(Sd)),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=ld(t.inputSchema);return o?KA(o,{strictUnions:!0,pipeStrategy:"input"}):Rme})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=ld(t.outputSchema);if(o)r.outputSchema=KA(o,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Sd,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Te(ke.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Te(ke.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 Te(ke.InternalError,`Tool ${e.params.name} has taskSupport '${n}' but was not registered with registerToolTask`);if(n==="required"&&!o)throw new Te(ke.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 Te){if(r.code===ke.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=ld(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 Te(ke.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 Te(ke.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=ld(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 Te(ke.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 Te(ke.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Na(Vv)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Vv,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return uD(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return lD(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Te(ke.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Te(ke.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Te(ke.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return eg;let n=Ta(r.argsSchema)?.[e.params.argument.name];if(!s$(n))return eg;let i=C3(n);if(!i)return eg;let s=await i(e.params.argument.value,e.params.context);return N3(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 Te(ke.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 N3(n)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Na(Uv)),this.server.assertCanSetRequestHandler(Na(Lv)),this.server.assertCanSetRequestHandler(Na(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 Te(ke.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 Te(ke.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Na(Fv)),this.server.assertCanSetRequestHandler(Na(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?Ome(t.argsSchema):void 0}))})),this.server.setRequestHandler(qv,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Te(ke.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Te(ke.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=ld(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 Te(ke.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:Yc(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=Yc(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 xd?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:z3(o),outputSchema:z3(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=Yc(d.paramsSchema);if(typeof d.outputSchema<"u")u.outputSchema=Yc(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 Rme={type:"object",properties:{}};function M3(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function B3(e){return"_def"in e||"_zod"in e||M3(e)}function u$(e){if(typeof e!=="object"||e===null)return!1;if(B3(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(M3)}function z3(e){if(!e)return;if(u$(e))return Yc(e);if(!B3(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Ome(e){let t=Ta(e);if(!t)return[];return Object.entries(t).map(([r,o])=>{let n=O4(o),i=C4(o);return{name:r,description:n,required:!i}})}function Na(e){let r=Ta(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 N3(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var eg={completion:{values:[],hasMore:!1}};import U3 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),Cme(t)}clear(){this._buffer=void 0}}function Cme(e){return tD.parse(JSON.parse(e))}function D3(e){return JSON.stringify(e)+`
|
|
136
|
-
`}class p${constructor(e=U3.stdin,t=U3.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=D3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.39",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.39","@0xmonaco/types":"1.0.39","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var z_=["read","market-maker","full"],_i=[{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"}],J6e=_i.map((e)=>e.name),L3=_i.filter((e)=>e.authMode==="public").map((e)=>e.name),Y6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),Q6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),X6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),e$e=_i.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),j3=_i.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Nme=new Map(_i.map((e)=>[e.name,e.sideEffect]));function F3(e){let t=Nme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var q3={read:0,"market-maker":1,full:2},f$=L3,m$=Object.fromEntries(_i.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),H3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),n$e=new Set(j3);function G3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function V3(e){return G3(e)==="read"}function Z3(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 q3[t.capability]>=q3[G3(e)]}var Mme=new Set([...f$,...Object.keys(H3)]),Bme={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 W3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(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=W3(e.MONACO_TOOL_ALLOWLIST),d=W3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Mme.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||Bme[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 Dme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Ma(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Ma(r));let t={};for(let[r,o]of Object.entries(e))t[Dme(r)]=typeof o==="object"&&o!==null?Ma(o):o;return t}lo();ig();lo();O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ei=BigInt(0),mn=BigInt(1),NF=BigInt(2),she=BigInt(8),ahe={zip215:!0};function che(e){let t=cg(e);return Fo(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function MF(e){let t=che(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=NF<<BigInt(a*8)-mn,d=r.create,p=vs(t.n,t.nBitLength);function m(C,U){let N=r.sqr(C),Y=r.sqr(U),X=r.add(r.mul(t.a,N),Y),ce=r.add(r.ONE,r.mul(t.d,r.mul(N,Y)));return r.eql(X,ce)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,U)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(U))}}catch(N){return{isValid:!1,value:Ei}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,U,N)=>{if(Si("phflag",N),U.length||N)throw Error("Contexts/pre-hash are not supported");return C});function S(C,U,N=!1){let Y=N?mn:Ei;pn("coordinate "+C,U,Y,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Fd((C,U)=>{let{ex:N,ey:Y,ez:X}=C,ce=C.is0();if(U==null)U=ce?she:r.inv(X);let Z=d(N*U),me=d(Y*U),Me=d(X*U);if(ce)return{x:Ei,y:mn};if(Me!==mn)throw Error("invZ was invalid");return{x:Z,y:me}}),w=Fd((C)=>{let{a:U,d:N}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:Y,ey:X,ez:ce,et:Z}=C,me=d(Y*Y),Me=d(X*X),Be=d(ce*ce),Le=d(Be*Be),Ut=d(me*U),bt=d(Be*d(Ut+Me)),cr=d(Le+d(N*d(me*Me)));if(bt!==cr)throw Error("bad point: equation left != right (1)");let Zr=d(Y*X),tr=d(ce*Z);if(Zr!==tr)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,U,N,Y){S("x",C),S("y",U),S("z",N,!0),S("t",Y),this.ex=C,this.ey=U,this.ez=N,this.et=Y,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:U,y:N}=C||{};return S("x",U),S("y",N),new _(U,N,mn,d(U*N))}static normalizeZ(C){let U=xs(r,C.map((N)=>N.ez));return C.map((N,Y)=>N.toAffine(U[Y])).map(_.fromAffine)}static msm(C,U){return H_(_,p,C,U)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:U,ey:N,ez:Y}=this,{ex:X,ey:ce,ez:Z}=C,me=d(U*Z),Me=d(X*Y),Be=d(N*Z),Le=d(ce*Y);return me===Me&&Be===Le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:U,ey:N,ez:Y}=this,X=d(U*U),ce=d(N*N),Z=d(NF*d(Y*Y)),me=d(C*X),Me=U+N,Be=d(d(Me*Me)-X-ce),Le=me+ce,Ut=Le-Z,bt=me-ce,cr=d(Be*Ut),Zr=d(Le*bt),tr=d(Be*bt),En=d(Ut*Le);return new _(cr,Zr,En,tr)}add(C){v(C);let{a:U,d:N}=t,{ex:Y,ey:X,ez:ce,et:Z}=this,{ex:me,ey:Me,ez:Be,et:Le}=C,Ut=d(Y*me),bt=d(X*Me),cr=d(Z*N*Le),Zr=d(ce*Be),tr=d((Y+X)*(me+Me)-Ut-bt),En=Zr-cr,Wr=Zr+cr,Ws=d(bt-U*Ut),Cf=d(tr*En),sl=d(Wr*Ws),Dy=d(tr*Ws),To=d(En*Wr);return new _(Cf,sl,To,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let U=C;pn("scalar",U,mn,o);let{p:N,f:Y}=this.wNAF(U);return _.normalizeZ([N,Y])[0]}multiplyUnsafe(C,U=_.ZERO){let N=C;if(pn("scalar",N,Ei,o),N===Ei)return P;if(this.is0()||N===mn)return this;return O.wNAFCachedUnsafe(this,N,_.normalizeZ,U)}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,U=!1){let{d:N,a:Y}=t,X=r.BYTES;C=yt("pointHex",C,X),Si("zip215",U);let ce=C.slice(),Z=C[X-1];ce[X-1]=Z&-129;let me=mu(ce),Me=U?u:r.ORDER;pn("pointHex.y",me,Ei,Me);let Be=d(me*me),Le=d(Be-mn),Ut=d(N*Be-Y),{isValid:bt,value:cr}=h(Le,Ut);if(!bt)throw Error("Point.fromHex: invalid y coordinate");let Zr=(cr&mn)===mn,tr=(Z&128)!==0;if(!U&&cr===Ei&&tr)throw Error("Point.fromHex: x=0 and x_0=1");if(tr!==Zr)cr=d(-cr);return _.fromAffine({x:cr,y:me})}static fromPrivateKey(C){let{scalar:U}=k(C);return T.multiply(U)}toRawBytes(){let{x:C,y:U}=this.toAffine(),N=jd(U,r.BYTES);return N[N.length-1]|=C&mn?128:0,N}toHex(){return La(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(Ei,mn,mn,Ei);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return lt(C,o)}function B(C){return z(mu(C))}function k(C){let U=r.BYTES;C=yt("private key",C,U);let N=yt("hashed private key",i(C),2*U),Y=y(N.slice(0,U)),X=N.slice(U,2*U),ce=B(Y);return{head:Y,prefix:X,scalar:ce}}function G(C){let{head:U,prefix:N,scalar:Y}=k(C),X=T.multiply(Y),ce=X.toRawBytes();return{head:U,prefix:N,scalar:Y,point:X,pointBytes:ce}}function V(C){return G(C).pointBytes}function ue(C=Uint8Array.of(),...U){let N=vr(...U);return B(i(x(N,yt("context",C),!!n)))}function W(C,U,N={}){if(C=yt("message",C),n)C=n(C);let{prefix:Y,scalar:X,pointBytes:ce}=G(U),Z=ue(N.context,Y,C),me=T.multiply(Z).toRawBytes(),Me=ue(N.context,me,ce,C),Be=z(Z+Me*X);pn("signature.s",Be,Ei,o);let Le=vr(me,jd(Be,r.BYTES));return yt("result",Le,r.BYTES*2)}let H=ahe;function fe(C,U,N,Y=H){let{context:X,zip215:ce}=Y,Z=r.BYTES;if(C=yt("signature",C,2*Z),U=yt("message",U),N=yt("publicKey",N,Z),ce!==void 0)Si("zip215",ce);if(n)U=n(U);let me=mu(C.slice(Z,2*Z)),Me,Be,Le;try{Me=_.fromHex(N,ce),Be=_.fromHex(C.slice(0,Z),ce),Le=T.multiplyUnsafe(me)}catch(cr){return!1}if(!ce&&Me.isSmallOrder())return!1;let Ut=ue(X,Be.toRawBytes(),Me.toRawBytes(),U);return Be.add(Me.multiplyUnsafe(Ut)).subtract(Le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:G,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,U=_.BASE){return U._setWindowSize(C),U.multiply(BigInt(3)),U}}}}xu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),U$e=BigInt(0),fhe=BigInt(1),FF=BigInt(2),L$e=BigInt(3),mhe=BigInt(5),hhe=BigInt(8);function ghe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Vt(a,FF,i)*a%i,u=Vt(c,fhe,i)*e%i,d=Vt(u,mhe,i)*u%i,p=Vt(d,t,i)*d%i,m=Vt(p,r,i)*p%i,h=Vt(m,o,i)*m%i,y=Vt(h,n,i)*h%i,x=Vt(y,n,i)*h%i,S=Vt(x,t,i)*d%i;return{pow_p_5_8:Vt(S,FF,i)*e%i,b2:a}}function yhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function bhe(e,t){let r=C$,o=lt(t*t*t,r),n=lt(o*o*t,r),i=ghe(e*n).pow_p_5_8,s=lt(e*o*i,r),a=lt(t*s*s,r),c=s,u=lt(s*jF,r),d=a===e,p=a===lt(-e,r),m=a===lt(-e*jF,r);if(d)s=c;if(p||m)s=u;if(kF(s,r))s=lt(-s,r);return{isValid:d||p,value:s}}var qF=(()=>vs(C$,void 0,!0))(),xhe=(()=>({a:qF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:qF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:hhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gF,randomBytes:Ud,adjustScalarBytes:yhe,uvRatio:bhe}))(),G_=(()=>MF(xhe))();ig();lo();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 uu(e.publicKey)}function W_(e){return uu(e.privateKey)}function HF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function GF(e){return uu(gs(e))}function VF(e,t,r,o){return`${e.toUpperCase()}
|
|
136
|
+
`}class p${constructor(e=U3.stdin,t=U3.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=D3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.40",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.40","@0xmonaco/types":"1.0.40","@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"],_i=[{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"}],J6e=_i.map((e)=>e.name),L3=_i.filter((e)=>e.authMode==="public").map((e)=>e.name),Y6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),Q6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),X6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),e$e=_i.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),j3=_i.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Nme=new Map(_i.map((e)=>[e.name,e.sideEffect]));function F3(e){let t=Nme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var q3={read:0,"market-maker":1,full:2},f$=L3,m$=Object.fromEntries(_i.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),H3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),n$e=new Set(j3);function G3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function V3(e){return G3(e)==="read"}function Z3(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 q3[t.capability]>=q3[G3(e)]}var Mme=new Set([...f$,...Object.keys(H3)]),Bme={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 W3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(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=W3(e.MONACO_TOOL_ALLOWLIST),d=W3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Mme.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||Bme[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 Dme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Ma(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Ma(r));let t={};for(let[r,o]of Object.entries(e))t[Dme(r)]=typeof o==="object"&&o!==null?Ma(o):o;return t}lo();ig();lo();O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ei=BigInt(0),mn=BigInt(1),NF=BigInt(2),she=BigInt(8),ahe={zip215:!0};function che(e){let t=cg(e);return Fo(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function MF(e){let t=che(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=NF<<BigInt(a*8)-mn,d=r.create,p=vs(t.n,t.nBitLength);function m(C,U){let N=r.sqr(C),Y=r.sqr(U),X=r.add(r.mul(t.a,N),Y),ce=r.add(r.ONE,r.mul(t.d,r.mul(N,Y)));return r.eql(X,ce)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,U)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(U))}}catch(N){return{isValid:!1,value:Ei}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,U,N)=>{if(Si("phflag",N),U.length||N)throw Error("Contexts/pre-hash are not supported");return C});function S(C,U,N=!1){let Y=N?mn:Ei;pn("coordinate "+C,U,Y,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Fd((C,U)=>{let{ex:N,ey:Y,ez:X}=C,ce=C.is0();if(U==null)U=ce?she:r.inv(X);let Z=d(N*U),me=d(Y*U),Me=d(X*U);if(ce)return{x:Ei,y:mn};if(Me!==mn)throw Error("invZ was invalid");return{x:Z,y:me}}),w=Fd((C)=>{let{a:U,d:N}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:Y,ey:X,ez:ce,et:Z}=C,me=d(Y*Y),Me=d(X*X),Be=d(ce*ce),Le=d(Be*Be),Ut=d(me*U),bt=d(Be*d(Ut+Me)),cr=d(Le+d(N*d(me*Me)));if(bt!==cr)throw Error("bad point: equation left != right (1)");let Zr=d(Y*X),tr=d(ce*Z);if(Zr!==tr)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,U,N,Y){S("x",C),S("y",U),S("z",N,!0),S("t",Y),this.ex=C,this.ey=U,this.ez=N,this.et=Y,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:U,y:N}=C||{};return S("x",U),S("y",N),new _(U,N,mn,d(U*N))}static normalizeZ(C){let U=xs(r,C.map((N)=>N.ez));return C.map((N,Y)=>N.toAffine(U[Y])).map(_.fromAffine)}static msm(C,U){return H_(_,p,C,U)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:U,ey:N,ez:Y}=this,{ex:X,ey:ce,ez:Z}=C,me=d(U*Z),Me=d(X*Y),Be=d(N*Z),Le=d(ce*Y);return me===Me&&Be===Le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:U,ey:N,ez:Y}=this,X=d(U*U),ce=d(N*N),Z=d(NF*d(Y*Y)),me=d(C*X),Me=U+N,Be=d(d(Me*Me)-X-ce),Le=me+ce,Ut=Le-Z,bt=me-ce,cr=d(Be*Ut),Zr=d(Le*bt),tr=d(Be*bt),En=d(Ut*Le);return new _(cr,Zr,En,tr)}add(C){v(C);let{a:U,d:N}=t,{ex:Y,ey:X,ez:ce,et:Z}=this,{ex:me,ey:Me,ez:Be,et:Le}=C,Ut=d(Y*me),bt=d(X*Me),cr=d(Z*N*Le),Zr=d(ce*Be),tr=d((Y+X)*(me+Me)-Ut-bt),En=Zr-cr,Wr=Zr+cr,Ws=d(bt-U*Ut),Cf=d(tr*En),sl=d(Wr*Ws),Dy=d(tr*Ws),To=d(En*Wr);return new _(Cf,sl,To,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let U=C;pn("scalar",U,mn,o);let{p:N,f:Y}=this.wNAF(U);return _.normalizeZ([N,Y])[0]}multiplyUnsafe(C,U=_.ZERO){let N=C;if(pn("scalar",N,Ei,o),N===Ei)return P;if(this.is0()||N===mn)return this;return O.wNAFCachedUnsafe(this,N,_.normalizeZ,U)}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,U=!1){let{d:N,a:Y}=t,X=r.BYTES;C=yt("pointHex",C,X),Si("zip215",U);let ce=C.slice(),Z=C[X-1];ce[X-1]=Z&-129;let me=mu(ce),Me=U?u:r.ORDER;pn("pointHex.y",me,Ei,Me);let Be=d(me*me),Le=d(Be-mn),Ut=d(N*Be-Y),{isValid:bt,value:cr}=h(Le,Ut);if(!bt)throw Error("Point.fromHex: invalid y coordinate");let Zr=(cr&mn)===mn,tr=(Z&128)!==0;if(!U&&cr===Ei&&tr)throw Error("Point.fromHex: x=0 and x_0=1");if(tr!==Zr)cr=d(-cr);return _.fromAffine({x:cr,y:me})}static fromPrivateKey(C){let{scalar:U}=k(C);return T.multiply(U)}toRawBytes(){let{x:C,y:U}=this.toAffine(),N=jd(U,r.BYTES);return N[N.length-1]|=C&mn?128:0,N}toHex(){return La(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(Ei,mn,mn,Ei);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return lt(C,o)}function B(C){return z(mu(C))}function k(C){let U=r.BYTES;C=yt("private key",C,U);let N=yt("hashed private key",i(C),2*U),Y=y(N.slice(0,U)),X=N.slice(U,2*U),ce=B(Y);return{head:Y,prefix:X,scalar:ce}}function G(C){let{head:U,prefix:N,scalar:Y}=k(C),X=T.multiply(Y),ce=X.toRawBytes();return{head:U,prefix:N,scalar:Y,point:X,pointBytes:ce}}function V(C){return G(C).pointBytes}function ue(C=Uint8Array.of(),...U){let N=vr(...U);return B(i(x(N,yt("context",C),!!n)))}function W(C,U,N={}){if(C=yt("message",C),n)C=n(C);let{prefix:Y,scalar:X,pointBytes:ce}=G(U),Z=ue(N.context,Y,C),me=T.multiply(Z).toRawBytes(),Me=ue(N.context,me,ce,C),Be=z(Z+Me*X);pn("signature.s",Be,Ei,o);let Le=vr(me,jd(Be,r.BYTES));return yt("result",Le,r.BYTES*2)}let H=ahe;function fe(C,U,N,Y=H){let{context:X,zip215:ce}=Y,Z=r.BYTES;if(C=yt("signature",C,2*Z),U=yt("message",U),N=yt("publicKey",N,Z),ce!==void 0)Si("zip215",ce);if(n)U=n(U);let me=mu(C.slice(Z,2*Z)),Me,Be,Le;try{Me=_.fromHex(N,ce),Be=_.fromHex(C.slice(0,Z),ce),Le=T.multiplyUnsafe(me)}catch(cr){return!1}if(!ce&&Me.isSmallOrder())return!1;let Ut=ue(X,Be.toRawBytes(),Me.toRawBytes(),U);return Be.add(Me.multiplyUnsafe(Ut)).subtract(Le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:G,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,U=_.BASE){return U._setWindowSize(C),U.multiply(BigInt(3)),U}}}}xu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),U$e=BigInt(0),fhe=BigInt(1),FF=BigInt(2),L$e=BigInt(3),mhe=BigInt(5),hhe=BigInt(8);function ghe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Vt(a,FF,i)*a%i,u=Vt(c,fhe,i)*e%i,d=Vt(u,mhe,i)*u%i,p=Vt(d,t,i)*d%i,m=Vt(p,r,i)*p%i,h=Vt(m,o,i)*m%i,y=Vt(h,n,i)*h%i,x=Vt(y,n,i)*h%i,S=Vt(x,t,i)*d%i;return{pow_p_5_8:Vt(S,FF,i)*e%i,b2:a}}function yhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function bhe(e,t){let r=C$,o=lt(t*t*t,r),n=lt(o*o*t,r),i=ghe(e*n).pow_p_5_8,s=lt(e*o*i,r),a=lt(t*s*s,r),c=s,u=lt(s*jF,r),d=a===e,p=a===lt(-e,r),m=a===lt(-e*jF,r);if(d)s=c;if(p||m)s=u;if(kF(s,r))s=lt(-s,r);return{isValid:d||p,value:s}}var qF=(()=>vs(C$,void 0,!0))(),xhe=(()=>({a:qF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:qF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:hhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gF,randomBytes:Ud,adjustScalarBytes:yhe,uvRatio:bhe}))(),G_=(()=>MF(xhe))();ig();lo();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 uu(e.publicKey)}function W_(e){return uu(e.privateKey)}function HF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function GF(e){return uu(gs(e))}function VF(e,t,r,o){return`${e.toUpperCase()}
|
|
137
137
|
${t}
|
|
138
138
|
${r}
|
|
139
139
|
${o}`}function ZF(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.
|
|
3
|
+
"version": "1.0.40",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
},
|
|
26
26
|
"author": "@codebycarson",
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@0xmonaco/core": "1.0.
|
|
29
|
-
"@0xmonaco/types": "1.0.
|
|
28
|
+
"@0xmonaco/core": "1.0.40",
|
|
29
|
+
"@0xmonaco/types": "1.0.40",
|
|
30
30
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
31
31
|
"node-fetch": "^3.3.2",
|
|
32
32
|
"viem": "^2.53.1",
|