vantage-mcp-server 2.6.0 → 2.6.1

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/index.js CHANGED
@@ -47,7 +47,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
47
47
  `:`[${o[c]}\r
48
48
  ]`;continue}n+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!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 yl(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===z.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??qe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===z.ZodString&&e.keyType._def.checks?.length){let{type:o,...n}=_l(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===z.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===z.ZodBranded&&e.keyType._def.type._def.typeName===z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:o,...n}=vl(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function Gb(e,t){if(t.mapStrategy==="record")return yl(e,t);let r=G(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||qe(t),o=G(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||qe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function Wb(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 Kb(e){return e.target==="openAi"?void 0:{not:qe({...e,currentPath:[...e.currentPath,"not"]})}}function Hb(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ds={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Bb(e,t){if(t.target==="openApi3")return Jb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in Ds&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let s=Ds[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 Jb(e,t)}var Jb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>G(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 Yb(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ds[e.innerType._def.typeName],nullable:!0}:{type:[Ds[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let o=G(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=G(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Xb(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",Tm(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ue(r,"minimum",o.value,o.message,t):ue(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ue(r,"maximum",o.value,o.message,t):ue(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",o.value,o.message,t));break;case"multipleOf":ue(r,"multipleOf",o.value,o.message,t);break}return r}function Qb(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=FI(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=G(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(o.properties[a]=l,u||n.push(a))}n.length&&(o.required=n);let s=LI(e,t);return s!==void 0&&(o.additionalProperties=s),o}function LI(e,t){if(e.catchall._def.typeName!=="ZodNever")return G(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 FI(e){try{return e.isOptional()}catch{return!0}}var e$=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return G(e.innerType._def,t);let r=G(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:qe(t)},r]}:qe(t)};var t$=(e,t)=>{if(t.pipeStrategy==="input")return G(e.in._def,t);if(t.pipeStrategy==="output")return G(e.out._def,t);let r=G(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=G(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function r$(e,t){return G(e.type._def,t)}function n$(e,t){let o={type:"array",uniqueItems:!0,items:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ue(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ue(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function o$(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>G(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:G(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>G(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function i$(e){return{not:qe(e)}}function s$(e){return qe(e)}var a$=(e,t)=>G(e.innerType._def,t);var c$=(e,t,r)=>{switch(t){case z.ZodString:return _l(e,r);case z.ZodNumber:return Xb(e,r);case z.ZodObject:return Qb(e,r);case z.ZodBigInt:return Ab(e,r);case z.ZodBoolean:return Db();case z.ZodDate:return Pm(e,r);case z.ZodUndefined:return i$(r);case z.ZodNull:return Hb(r);case z.ZodArray:return Cb(e,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return Bb(e,r);case z.ZodIntersection:return Vb(e,r);case z.ZodTuple:return o$(e,r);case z.ZodRecord:return yl(e,r);case z.ZodLiteral:return Lb(e,r);case z.ZodEnum:return Zb(e);case z.ZodNativeEnum:return Wb(e);case z.ZodNullable:return Yb(e,r);case z.ZodOptional:return e$(e,r);case z.ZodMap:return Gb(e,r);case z.ZodSet:return n$(e,r);case z.ZodLazy:return()=>e.getter()._def;case z.ZodPromise:return r$(e,r);case z.ZodNaN:case z.ZodNever:return Kb(r);case z.ZodEffects:return Ub(e,r);case z.ZodAny:return qe(r);case z.ZodUnknown:return s$(r);case z.ZodDefault:return Mb(e,r);case z.ZodBranded:return vl(e,r);case z.ZodReadonly:return a$(e,r);case z.ZodCatch:return qb(e,r);case z.ZodPipeline:return t$(e,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(o=>{})(t)}};function G(e,t,r=!1){let o=t.seen.get(e);if(t.override){let a=t.override?.(e,t,o,r);if(a!==jb)return a}if(o&&!r){let a=GI(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=c$(e,e.typeName,t),s=typeof i=="function"?G(i(),t):i;if(s&&WI(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var GI=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:gl(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),qe(t)):t.$refStrategy==="seen"?qe(t):void 0}},WI=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var Im=(e,t)=>{let r=Rb(t),o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:G(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??qe(r)}),{}):void 0,n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=G(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??qe(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),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}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),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."),a};function KI(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Om(e,t){return Nt(e)?xo(e,{target:KI(t?.target),io:t?.pipeStrategy??"input"}):Im(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function jm(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Cu(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Nm(e,t){let r=Gr(e,t);if(!r.success)throw r.error;return r.data}var HI=6e4,bl=class{constructor(t){this._options=t,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(Qu,r=>{this._oncancel(r)}),this.setNotificationHandler(tl,r=>{this._onprogress(r)}),this.setRequestHandler(el,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(rl,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new U(L.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(ol,async(r,o)=>{let n=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,h=new U(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let s=await this._taskStore.getTask(i,o.sessionId);if(!s)throw new U(L.InvalidParams,`Task not found: ${i}`);if(!Hr(s.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Hr(s.status)){let a=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Kr]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(il,async(r,o)=>{try{let{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new U(L.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(al,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new U(L.InvalidParams,`Task not found: ${r.params.taskId}`);if(Hr(n.status))throw new U(L.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new U(L.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof U?n:new U(L.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),U.fromError(L.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};let n=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{n?.(i,s),zs(i)||bb(i)?this._onresponse(i):pm(i)?this._onrequest(i,s):yb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=U.fromError(L.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of t.values())o(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){let o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Kr]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:L.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=gb(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:s.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(s.signal.aborted)throw new U(L.ConnectionClosed,"Request was cancelled");let m={...h,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let p=m.relatedTask?.taskId??i;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:L.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(c);return}i(o)}_onresponse(t){let r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),zs(t))o(t);else{let s=new U(t.error.code,t.error.message,t.error.data);o(s)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(zs(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),zs(t))n(t);else{let s=U.fromError(t.error.code,t.error.message,t.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(s){yield{type:"error",error:s instanceof U?s:new U(L.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Io,o);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new U(L.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:a},Hr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:a.status==="failed"?yield{type:"error",error:new U(L.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new U(L.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof U?s:new U(L.InternalError,String(s))}}}request(t,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=w=>{l(w)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(w){d(w);return}o?.signal?.throwIfAborted();let h=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:h};o?.onprogress&&(this._progressHandlers.set(h,o.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Kr]:c}});let p=w=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(w)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let k=w instanceof U?w:new U(L.RequestTimeout,String(w));l(k)};this._responseHandlers.set(h,w=>{if(!o?.signal?.aborted){if(w instanceof Error)return l(w);try{let k=Gr(r,w.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),o?.signal?.addEventListener("abort",()=>{p(o?.signal?.reason)});let f=o?.timeout??HI,v=()=>p(U.fromError(L.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(h,f,o?.maxTotalTimeout,v,o?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let w=k=>{let E=this._responseHandlers.get(h);E?E(k):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,w),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(h),l(k)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(h),l(w)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},nl,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},sl,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},kb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let o=r?.relatedTask?.taskId;if(o){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Kr]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Kr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Kr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let o=jm(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{let s=Nm(t,n);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let o=jm(t);this._notificationHandlers.set(o,n=>{let i=Nm(t,n);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(t,r);for(let n of o)if(n.type==="request"&&pm(n.message)){let i=n.message.id,s=this._requestResolvers.get(i);s?(s(new U(L.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new U(L.InvalidRequest,"Request cancelled"));return}let s=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(s),i(new U(L.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{let i=await o.getTask(n,r);if(!i)throw new U(L.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,s)=>{await o.storeTaskResult(n,i,s,r);let a=await o.getTask(n,r);if(a){let c=Ns.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Hr(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,s)=>{let a=await o.getTask(n,r);if(!a)throw new U(L.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Hr(a.status))throw new U(L.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,s,r);let c=await o.getTask(n,r);if(c){let u=Ns.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Hr(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function u$(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function l$(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];u$(s)&&u$(i)?r[n]={...s,...i}:r[n]=i}return r}var lS=Ge(Ak(),1),dS=Ge(uS(),1);function j4(){let e=new lS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dS.default)(e),e}var Rd=class{constructor(t){this._ajv=t??j4()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Cd=class{constructor(t){this._server=t}requestStream(t,r,o){return this._server.requestStream(t,r,o)}createMessageStream(t,r){let o=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},As,r)}elicitInputStream(t,r){let o=this._server.getClientCapabilities(),n=t.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=n==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},No,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,o){return this._server.getTaskResult({taskId:t},r,o)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function pS(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function fS(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Ad=class extends bl{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Cs.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let i=this._loggingLevels.get(n);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Rd,this.setRequestHandler(hm,o=>this._oninitialize(o)),this.setNotificationHandler(gm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(km,async(o,n)=>{let i=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=o.params,a=Cs.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Cd(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=l$(this._capabilities,t)}setRequestHandler(t,r){let n=Wr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i;if(Nt(n)){let a=n;i=a._zod?.def?.value??a.value}else{let a=n;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Gr(jo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new U(L.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(c,u));if(d.task){let p=Gr(Io,h);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new U(L.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let m=Gr(ml,h);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new U(L.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){fS(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&pS(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:fb.includes(r)?r:lm,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"},Xu)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.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 new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},xm,r):this.request({method:"sampling/createMessage",params:t},As,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=t;return this.request({method:"elicitation/create",params:n},No,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:n},No,r);if(i.action==="accept"&&i.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(i.content);if(!a.valid)throw new U(L.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof U?s:new U(L.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Sm,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 hS=Symbol.for("mcp.completable");function n_(e){return!!e&&typeof e=="object"&&hS in e}function gS(e){return e[hS]?.complete}var mS;(function(e){e.Completable="McpCompletable"})(mS||(mS={}));var N4=/^[A-Za-z0-9._-]{1,128}$/;function R4(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"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!N4.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 C4(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 o_(e){let t=R4(e);return C4(e,t.warnings),t.isValid}var Dd=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,o){let n={taskSupport:"required",...r.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,n,r._meta,o)}};var qd=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ad(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Dd(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(fl)),this.server.assertCanSetRequestHandler(dn(jo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(fl,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let o={name:t,title:r.title,description:r.description,inputSchema:(()=>{let n=So(r.inputSchema);return n?Om(n,{strictUnions:!0,pipeStrategy:"input"}):A4})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=So(r.outputSchema);n&&(o.outputSchema=Om(n,{strictUnions:!0,pipeStrategy:"output"}))}return o})})),this.server.setRequestHandler(jo,async(t,r)=>{try{let o=this._registeredTools[t.params.name];if(!o)throw new U(L.InvalidParams,`Tool ${t.params.name} not found`);if(!o.enabled)throw new U(L.InvalidParams,`Tool ${t.params.name} disabled`);let n=!!t.params.task,i=o.execution?.taskSupport,s="createTask"in o.handler;if((i==="required"||i==="optional")&&!s)throw new U(L.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!n)throw new U(L.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(o,t,r);let a=await this.validateToolInput(o,t.params.arguments,t.params.name),c=await this.executeToolHandler(o,a,r);return n||await this.validateToolOutput(o,c,t.params.name),c}catch(o){if(o instanceof U&&o.code===L.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,o){if(!t.inputSchema)return;let i=So(t.inputSchema)??t.inputSchema,s=await Nu(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=Ru(a);throw new U(L.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${c}`)}return s.data}async validateToolOutput(t,r,o){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new U(L.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);let n=So(t.outputSchema),i=await Nu(n,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=Ru(s);throw new U(L.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${a}`)}}async executeToolHandler(t,r,o){let n=t.handler;if("createTask"in n){if(!o.taskStore)throw new Error("No task store provided.");let s={...o,taskStore:o.taskStore};if(t.inputSchema){let a=n;return await Promise.resolve(a.createTask(r,s))}else{let a=n;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=n;return await Promise.resolve(s(r,o))}else{let s=n;return await Promise.resolve(s(o))}}async handleAutomaticTaskPolling(t,r,o){if(!o.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...o,taskStore:o.taskStore},a=n?await Promise.resolve(i.createTask(n,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await o.taskStore.getTask(c);if(!d)throw new U(L.InternalError,`Task ${c} not found during polling`);u=d}return await o.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(dn(hl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(hl,async t=>{switch(t.params.ref.type){case"ref/prompt":return Eb(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Ib(t),this.handleResourceCompletion(t,t.params.ref);default:throw new U(L.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let o=this._registeredPrompts[r.name];if(!o)throw new U(L.InvalidParams,`Prompt ${r.name} not found`);if(!o.enabled)throw new U(L.InvalidParams,`Prompt ${r.name} disabled`);if(!o.argsSchema)return Za;let i=Wr(o.argsSchema)?.[t.params.argument.name];if(!n_(i))return Za;let s=gS(i);if(!s)return Za;let a=await s(t.params.argument.value,t.params.context);return _S(a)}async handleResourceCompletion(t,r){let o=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!o){if(this._registeredResources[r.uri])return Za;throw new U(L.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=o.resourceTemplate.completeCallback(t.params.argument.name);if(!n)return Za;let i=await n(t.params.argument.value,t.params.context);return _S(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(cl)),this.server.assertCanSetRequestHandler(dn(ul)),this.server.assertCanSetRequestHandler(dn(ll)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(cl,async(t,r)=>{let o=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),n=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)n.push({...i.metadata,...a})}return{resources:[...o,...n]}}),this.server.setRequestHandler(ul,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,o])=>({name:r,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler(ll,async(t,r)=>{let o=new URL(t.params.uri),n=this._registeredResources[o.toString()];if(n){if(!n.enabled)throw new U(L.InvalidParams,`Resource ${o} disabled`);return n.readCallback(o,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(o.toString());if(s)return i.readCallback(o,s,r)}throw new U(L.InvalidParams,`Resource ${o} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(dl)),this.server.assertCanSetRequestHandler(dn(pl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(dl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?q4(r.argsSchema):void 0}))})),this.server.setRequestHandler(pl,async(t,r)=>{let o=this._registeredPrompts[t.params.name];if(!o)throw new U(L.InvalidParams,`Prompt ${t.params.name} not found`);if(!o.enabled)throw new U(L.InvalidParams,`Prompt ${t.params.name} disabled`);if(o.argsSchema){let n=So(o.argsSchema),i=await Nu(n,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Ru(c);throw new U(L.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let s=i.data,a=o.callback;return await Promise.resolve(a(s,r))}else{let n=o.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...o){let n;typeof o[0]=="object"&&(n=o.shift());let i=o[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,o,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,o,n,i){let s={name:t,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==o&&(delete this._registeredResources[o],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[o]=s,s}_createRegisteredResourceTemplate(t,r,o,n,i){let s={resourceTemplate:o,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=o.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!o.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,o,n,i){let s={title:r,description:o,argsSchema:n===void 0?void 0:Tn(n),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Tn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,n&&Object.values(n).some(c=>{let u=c instanceof Pt?c._def?.innerType:c;return n_(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,o,n,i,s,a,c,u){o_(t);let l={title:r,description:o,inputSchema:vS(n),outputSchema:vS(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&o_(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Tn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Tn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let o,n,i,s;if(typeof r[0]=="string"&&(o=r.shift()),r.length>1){let c=r[0];i_(c)?(n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!i_(r[0])&&(s=r.shift())):typeof c=="object"&&c!==null&&(s=r.shift())}let a=r[0];return this._createRegisteredTool(t,void 0,o,n,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,o){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:n,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,n,i,s,a,c,{taskSupport:"forbidden"},u,o)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let o;typeof r[0]=="string"&&(o=r.shift());let n;r.length>1&&(n=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,o,n,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,o){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:n,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,n,i,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var A4={type:"object",properties:{}};function yS(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function D4(e){return"_def"in e||"_zod"in e||yS(e)}function i_(e){return typeof e!="object"||e===null||D4(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(yS)}function vS(e){if(e)return i_(e)?Tn(e):e}function q4(e){let t=Wr(e);return t?Object.entries(t).map(([r,o])=>{let n=Py(o),i=zy(o);return{name:r,description:n,required:!i}}):[]}function dn(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Cu(r);if(typeof o=="string")return o;throw new Error("Schema method literal must be a string")}function _S(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Za={completion:{values:[],hasMore:!1}};var s_=Ge(require("node:process"),1);var Md=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
49
49
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),M4(r)}clear(){this._buffer=void 0}};function M4(e){return $b.parse(JSON.parse(e))}function bS(e){return JSON.stringify(e)+`
50
- `}var Ud=class{constructor(t=s_.default.stdin,r=s_.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Md,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new 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(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){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(t){return new Promise(r=>{let o=bS(t);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var $S="2.6.0";var a_={name:"Vantage Cloud Costs Helper",version:$S};async function wS(e,t,r,o,n){t["User-Agent"]=`vantage-mcp-server/${a_.version}`;let i=new URL(n,e);o==="GET"?Object.entries(r).forEach(([u,l])=>{l!=null&&i.searchParams.append(u,Array.isArray(l)?l.join(","):String(l))}):t["Content-Type"]="application/json";let s={method:o,headers:t,body:o!=="GET"?JSON.stringify(r):void 0},a=await fetch(i.toString(),s);if(!a.ok){let u=await a.text();try{let l=JSON.parse(u);if(Array.isArray(l.errors))return{errors:l.errors,ok:!1}}catch{}return{errors:[{message:"Vantage API request failed",status:a.status,endpoint:n,details:u}],ok:!1}}return a.status===204?{data:void 0,ok:!0}:{data:await a.json(),ok:!0}}var I=class{constructor(t){this.exception=t}};var c_=new Map;function j(e){let t=(r,o)=>{r.tool(e.name,e.description,e.args,{readOnlyHint:e.annotations.readOnly??!1,openWorldHint:e.annotations.openWorld??!1,destructiveHint:e.annotations.destructive??!0},async n=>{try{let i=await e.execute(n,o());return{content:[{type:"text",text:JSON.stringify(i,null,2)}],isError:!1}}catch(i){if(i instanceof I)return{content:[{type:"text",text:JSON.stringify(i.exception,null,2)}],isError:!0};throw i}})};if(c_.has(e.name))throw new Error(`Tool ${e.name} is already registered`);return c_.set(e.name,t),e}function kS(e,t){for(let r of c_.values())r(e,t)}var U4="Invalid date input, must be YYYY-MM-DD format and a reasonable date.";function Z4(e){let t="2030-01-01",r="2010-01-01";if(!e||e===""||typeof e!="string"||e<r||e>t)return!1;let o=Date.parse(e);return!(Number.isNaN(o)||o<=Date.parse(r)||o>=Date.parse(t))}function $e(e){return g.string().refine(Z4,{error:U4}).describe(e)}var V4=`
50
+ `}var Ud=class{constructor(t=s_.default.stdin,r=s_.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Md,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new 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(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){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(t){return new Promise(r=>{let o=bS(t);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var $S="2.6.1";var a_={name:"Vantage Cloud Costs Helper",version:$S};async function wS(e,t,r,o,n){t["User-Agent"]=`vantage-mcp-server/${a_.version}`;let i=new URL(n,e);o==="GET"?Object.entries(r).forEach(([u,l])=>{l!=null&&i.searchParams.append(u,Array.isArray(l)?l.join(","):String(l))}):t["Content-Type"]="application/json";let s={method:o,headers:t,body:o!=="GET"?JSON.stringify(r):void 0},a=await fetch(i.toString(),s);if(!a.ok){let u=await a.text();try{let l=JSON.parse(u);if(Array.isArray(l.errors))return{errors:l.errors,ok:!1}}catch{}return{errors:[{message:"Vantage API request failed",status:a.status,endpoint:n,details:u}],ok:!1}}return a.status===204?{data:void 0,ok:!0}:{data:await a.json(),ok:!0}}var I=class{constructor(t){this.exception=t}};var c_=new Map;function j(e){let t=(r,o)=>{r.tool(e.name,e.description,e.args,{readOnlyHint:e.annotations.readOnly,openWorldHint:e.annotations.openWorld,destructiveHint:e.annotations.destructive},async n=>{try{let i=await e.execute(n,o());return{content:[{type:"text",text:JSON.stringify(i,null,2)}],isError:!1}}catch(i){if(i instanceof I)return{content:[{type:"text",text:JSON.stringify(i.exception,null,2)}],isError:!0};throw i}})};if(c_.has(e.name))throw new Error(`Tool ${e.name} is already registered`);return c_.set(e.name,t),e}function kS(e,t){for(let r of c_.values())r(e,t)}var U4="Invalid date input, must be YYYY-MM-DD format and a reasonable date.";function Z4(e){let t="2030-01-01",r="2010-01-01";if(!e||e===""||typeof e!="string"||e<r||e>t)return!1;let o=Date.parse(e);return!(Number.isNaN(o)||o<=Date.parse(r)||o>=Date.parse(t))}function $e(e){return g.string().refine(Z4,{error:U4}).describe(e)}var V4=`
51
51
  Creates a budget based on the parameters specified. This is useful if you have been tasked with managing budgets
52
52
  or you are building a cost report with budgets in mind.
53
53
  `.trim(),L4=g.object({start_at:$e("The start date of the period."),end_at:$e("The end date of the period.").optional(),amount:g.number().min(0).describe("The amount of the period.")}),wH=j({name:"create-budget",description:V4,annotations:{destructive:!1,openWorld:!1,readOnly:!1},args:{name:g.string().min(1).describe("The name of the Budget."),workspace_token:g.string().optional().describe("The token of the Workspace to add the Budget to."),cost_report_token:g.string().optional().describe("The CostReport token. Ignored for hierarchical Budgets."),child_budget_tokens:g.array(g.string()).optional().describe("The tokens of any child Budgets when creating a hierarchical Budget."),periods:g.array(L4).optional().describe("The periods for the Budget. The start_at and end_at must be iso8601 formatted e.g. YYYY-MM-DD. Ignored for hierarchical Budgets.")},async execute(e,t){let r=await t.callVantageApi("/v2/budgets",e,"POST");if(!r.ok)throw new I({errors:r.errors});return r.data}});var F4=`