@cyia/mcp-note 1.0.2 → 1.0.3

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
@@ -57,4 +57,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
57
57
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
58
58
  ]))`;continue}}if(r.s&&n[c]==="."){o+=a?`${n[c]}\r
59
59
  `:`[${n[c]}\r
60
- ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Gc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Oe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Hc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Kc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function kb(t,e){if(e.mapStrategy==="record")return Gc(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Oe(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Oe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Sb(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function zb(t){return t.target==="openAi"?void 0:{not:Oe({...t,currentPath:[...t.currentPath,"not"]})}}function Pb(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Eb(t,e){if(e.target==="openApi3")return Ib(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ua&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=ua[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Ib(t,e)}var Ib=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Tb(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ua[t.innerType._def.typeName],nullable:!0}:{type:[ua[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jb(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Vm(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function Ob(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=FT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(n.properties[s]=l,u||o.push(s))}o.length&&(n.required=o);let a=VT(t,e);return a!==void 0&&(n.additionalProperties=a),n}function VT(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function FT(t){try{return t.isOptional()}catch{return!0}}var Nb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Oe(e)},r]}:Oe(e)};var Rb=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Db(t,e){return L(t.type._def,e)}function Cb(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ab(t){return{not:Oe(t)}}function Ub(t){return Oe(t)}var Mb=(t,e)=>L(t.innerType._def,e);var qb=(t,e,r)=>{switch(e){case S.ZodString:return Hc(t,r);case S.ZodNumber:return jb(t,r);case S.ZodObject:return Ob(t,r);case S.ZodBigInt:return hb(t,r);case S.ZodBoolean:return gb();case S.ZodDate:return Fm(t,r);case S.ZodUndefined:return Ab(r);case S.ZodNull:return Pb(r);case S.ZodArray:return mb(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Eb(t,r);case S.ZodIntersection:return bb(t,r);case S.ZodTuple:return Zb(t,r);case S.ZodRecord:return Gc(t,r);case S.ZodLiteral:return xb(t,r);case S.ZodEnum:return $b(t);case S.ZodNativeEnum:return Sb(t);case S.ZodNullable:return Tb(t,r);case S.ZodOptional:return Nb(t,r);case S.ZodMap:return kb(t,r);case S.ZodSet:return Cb(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Db(t,r);case S.ZodNaN:case S.ZodNever:return zb(r);case S.ZodEffects:return _b(t,r);case S.ZodAny:return Oe(r);case S.ZodUnknown:return Ub(r);case S.ZodDefault:return yb(t,r);case S.ZodBranded:return Kc(t,r);case S.ZodReadonly:return Mb(t,r);case S.ZodCatch:return vb(t,r);case S.ZodPipeline:return Rb(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==db)return s}if(n&&!r){let s=JT(n,e);if(s!==void 0)return s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=qb(t,t.typeName,e),a=typeof i=="function"?L(i(),e):i;if(a&&KT(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var JT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Jc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Oe(e)):e.$refStrategy==="seen"?Oe(e):void 0}},KT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Hm=(t,e)=>{let r=pb(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Oe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Oe(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function HT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Gm(t,e){return jt(t)?Ri(t,{target:HT(e?.target),io:e?.pipeStrategy??"input"}):Hm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Bm(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wm(t,e){let r=Mr(t,e);if(!r.success)throw r.error;return r.data}var GT=6e4,Bc=class{constructor(e){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($c,r=>{this._oncancel(r)}),this.setNotificationHandler(xc,r=>{this._onprogress(r)}),this.setRequestHandler(bc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Sc,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,f=new N(d.error.code,d.error.message,d.error.data);l(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new N(Z.InvalidParams,`Task not found: ${i}`);if(!Lr(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Lr(a.status)){let s=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Cr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(zc,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new N(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ic,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Lr(o.status))throw new N(Z.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new N(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof N?o:new N(Z.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,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),N.fromError(Z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){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=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),Li(i)||L$(i)?this._onresponse(i):$m(i)?this._onrequest(i,a):q$(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=N.fromError(Z.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Cr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=A$(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(a.signal.aborted)throw new N(Z.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Z.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()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Li(e))n(e);else{let a=new N(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Li(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Li(e))o(e);else{let a=N.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof N?a:new N(Z.InternalError,String(a))}}return}let i;try{let a=await this.request(e,ro,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new N(Z.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:s},Lr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:s.status==="failed"?yield{type:"error",error:new N(Z.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new N(Z.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof N?a:new N(Z.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=z=>{l(z)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(z){d(z);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Cr]:c}});let m=z=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(z)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let x=z instanceof N?z:new N(Z.RequestTimeout,String(z));l(x)};this._responseHandlers.set(f,z=>{if(!n?.signal?.aborted){if(z instanceof Error)return l(z);try{let x=Mr(r,z.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??GT,v=()=>m(N.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let z=x=>{let E=this._responseHandlers.get(f);E?E(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,z),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(z=>{this._cleanupTimeout(f),l(z)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},kc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Pc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},J$,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Cr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.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"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Cr]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Cr]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=Bm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=Wm(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Bm(e);this._notificationHandlers.set(n,o=>{let i=Wm(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&$m(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new N(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new N(Z.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new N(Z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new N(Z.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let s=await n.getTask(o,r);if(s){let c=Hi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Lr(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let s=await n.getTask(o,r);if(!s)throw new N(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Lr(s.status))throw new N(Z.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=Hi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Lr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Lb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vb(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];Lb(a)&&Lb(i)?r[o]={...a,...i}:r[o]=i}return r}var VS=qn(hk(),1),FS=qn(LS(),1);function RU(){let t=new VS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,FS.default)(t),t}var sl=class{constructor(e){this._ajv=e??RU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var cl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],a=i.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){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(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))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:e},Wi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},io,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function JS(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function KS(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ul=class extends Bc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Bi.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new sl,this.setRequestHandler(wm,n=>this._oninitialize(n)),this.setNotificationHandler(km,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(jm,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=Bi.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new cl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vb(this._capabilities,e)}setRequestHandler(e,r){let o=qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(jt(o)){let s=o;i=s._zod?.def?.value??s.value}else{let s=o;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(c,u)=>{let l=Mr(oo,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new N(Z.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=Mr(ro,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new N(Z.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=Mr(Dc,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new N(Z.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new 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 new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new 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 new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){KS(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&JS(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:D$.includes(r)?r:ym,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"},_c)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(i){if(o.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(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.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 e.tools?this.request({method:"sampling/createMessage",params:e},Om,r):this.request({method:"sampling/createMessage",params:e},Wi,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},io,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},io,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!s.valid)throw new N(Z.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof N?a:new N(Z.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,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:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Nm,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 GS=Symbol.for("mcp.completable");function $y(t){return!!t&&typeof t=="object"&&GS in t}function BS(t){return t[GS]?.complete}var HS;(function(t){t.Completable="McpCompletable"})(HS||(HS={}));var DU=/^[A-Za-z0-9._-]{1,128}$/;function CU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!DU.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ZU(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)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 by(t){let e=CU(t);return ZU(t,e.warnings),e.isValid}var ll=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var dl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ul(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ll(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Rc)),this.server.assertCanSetRequestHandler(on(oo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Rc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=bo(r.inputSchema);return o?Gm(o,{strictUnions:!0,pipeStrategy:"input"}):AU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=bo(r.outputSchema);o&&(n.outputSchema=Gm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(oo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new N(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,a="createTask"in n.handler;if((i==="required"||i==="optional")&&!a)throw new N(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new N(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,e,r);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof N&&n.code===Z.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=bo(e.inputSchema)??e.inputSchema,a=await Lc(i,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Vc(s);throw new N(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new N(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=bo(e.outputSchema),i=await Lc(o,r.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=Vc(a);throw new N(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${s}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let a={...n,taskStore:n.taskStore};if(e.inputSchema){let s=o;return await Promise.resolve(s.createTask(r,a))}else{let s=o;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=o;return await Promise.resolve(a(r,n))}else{let a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,a={...n,taskStore:n.taskStore},s=o?await Promise.resolve(i.createTask(o,a)):await Promise.resolve(i.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new N(Z.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(on(Cc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cc,async e=>{switch(e.params.ref.type){case"ref/prompt":return X$(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Y$(e),this.handleResourceCompletion(e,e.params.ref);default:throw new N(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new N(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ps;let i=qr(n.argsSchema)?.[e.params.argument.name];if(!$y(i))return ps;let a=BS(i);if(!a)return ps;let s=await a(e.params.argument.value,e.params.context);return XS(s)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ps;throw new N(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ps;let i=await o(e.params.argument.value,e.params.context);return XS(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Ec)),this.server.assertCanSetRequestHandler(on(Tc)),this.server.assertCanSetRequestHandler(on(jc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ec,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(r);for(let s of a.resources)o.push({...i.metadata,...s})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Tc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(jc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new N(Z.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(n.toString());if(a)return i.readCallback(n,a,r)}throw new N(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Oc)),this.server.assertCanSetRequestHandler(on(Nc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?UU(r.argsSchema):void 0}))})),this.server.setRequestHandler(Nc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new N(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=bo(n.argsSchema),i=await Lc(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Vc(c);throw new N(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=i.data,s=n.callback;return await Promise.resolve(s(a,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let a={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,o,i){let a={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,n,o,i){let a={title:r,description:n,argsSchema:o===void 0?void 0:$n(o),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=$n(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,o&&Object.values(o).some(c=>{let u=c instanceof Mi?c._def?.innerType:c;return $y(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,n,o,i,a,s,c,u){by(e);let l={title:r,description:n,inputSchema:WS(o),outputSchema:WS(i),annotations:a,execution:s,_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!==e&&(typeof d.name=="string"&&by(d.name),delete this._registeredTools[e],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=$n(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=$n(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[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(xy(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!xy(r[0])&&(a=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,n,o,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,i,a,s,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],a=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:a}=r,s=this._createRegisteredPrompt(e,o,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var AU={type:"object",properties:{}};function YS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function QS(t){return"_def"in t||"_zod"in t||YS(t)}function xy(t){return typeof t!="object"||t===null||QS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(YS)}function WS(t){if(t){if(xy(t))return $n(t);if(!QS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function UU(t){let e=qr(t);return e?Object.entries(e).map(([r,n])=>{let o=cb(n),i=ub(n);return{name:r,description:o,required:!i}}):[]}function on(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function XS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ps={completion:{values:[],hasMore:!1}};var ez=qn(require("fs")),wy=qn(require("path")),ky=(t,e)=>{let r=[];try{let n=ez.default.readdirSync(t,{withFileTypes:!0});for(let o of n){let i=wy.default.join(t,o.name);if(o.isDirectory())r=r.concat(ky(i,e));else if(o.isFile()&&o.name.endsWith(".js")){let a=wy.default.relative(e,i);r.push(a)}}}catch{}return r};var fl="@cyia/mcp-note",pl="1.0.2";var Sy=qn(require("path")),rz=async()=>{let t=new dl({name:fl,version:pl},{capabilities:{logging:{}}}),e=process.env.SCRIPT_DIR;return ky(e,e).forEach(n=>{console.error("\u811A\u672C",n,Sy.default.join(e,n)),import(Sy.default.join(e,n)).then(o=>{let i="default"in o?o.default:o;t.registerTool(i.name,i.config,i.cb)})}),t};async function MU(){console.error(`\u542F\u52A8\u670D\u52A1\u5668 ${fl} ${pl}`);let t=process.env.SCRIPT_DIR;console.log("dir",t),console.log("cwd",process.cwd()),console.log("__dirname",__dirname);let e=new Ac;await rz().then(r=>r.connect(e))}MU();
60
+ ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Gc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Oe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Hc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Kc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function kb(t,e){if(e.mapStrategy==="record")return Gc(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Oe(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Oe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Sb(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function zb(t){return t.target==="openAi"?void 0:{not:Oe({...t,currentPath:[...t.currentPath,"not"]})}}function Pb(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Eb(t,e){if(e.target==="openApi3")return Ib(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ua&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=ua[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Ib(t,e)}var Ib=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Tb(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ua[t.innerType._def.typeName],nullable:!0}:{type:[ua[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jb(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Vm(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function Ob(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=FT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(n.properties[s]=l,u||o.push(s))}o.length&&(n.required=o);let a=VT(t,e);return a!==void 0&&(n.additionalProperties=a),n}function VT(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function FT(t){try{return t.isOptional()}catch{return!0}}var Nb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Oe(e)},r]}:Oe(e)};var Rb=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Db(t,e){return L(t.type._def,e)}function Cb(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ab(t){return{not:Oe(t)}}function Ub(t){return Oe(t)}var Mb=(t,e)=>L(t.innerType._def,e);var qb=(t,e,r)=>{switch(e){case S.ZodString:return Hc(t,r);case S.ZodNumber:return jb(t,r);case S.ZodObject:return Ob(t,r);case S.ZodBigInt:return hb(t,r);case S.ZodBoolean:return gb();case S.ZodDate:return Fm(t,r);case S.ZodUndefined:return Ab(r);case S.ZodNull:return Pb(r);case S.ZodArray:return mb(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Eb(t,r);case S.ZodIntersection:return bb(t,r);case S.ZodTuple:return Zb(t,r);case S.ZodRecord:return Gc(t,r);case S.ZodLiteral:return xb(t,r);case S.ZodEnum:return $b(t);case S.ZodNativeEnum:return Sb(t);case S.ZodNullable:return Tb(t,r);case S.ZodOptional:return Nb(t,r);case S.ZodMap:return kb(t,r);case S.ZodSet:return Cb(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Db(t,r);case S.ZodNaN:case S.ZodNever:return zb(r);case S.ZodEffects:return _b(t,r);case S.ZodAny:return Oe(r);case S.ZodUnknown:return Ub(r);case S.ZodDefault:return yb(t,r);case S.ZodBranded:return Kc(t,r);case S.ZodReadonly:return Mb(t,r);case S.ZodCatch:return vb(t,r);case S.ZodPipeline:return Rb(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==db)return s}if(n&&!r){let s=JT(n,e);if(s!==void 0)return s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=qb(t,t.typeName,e),a=typeof i=="function"?L(i(),e):i;if(a&&KT(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var JT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Jc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Oe(e)):e.$refStrategy==="seen"?Oe(e):void 0}},KT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Hm=(t,e)=>{let r=pb(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Oe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Oe(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function HT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Gm(t,e){return jt(t)?Ri(t,{target:HT(e?.target),io:e?.pipeStrategy??"input"}):Hm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Bm(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wm(t,e){let r=Mr(t,e);if(!r.success)throw r.error;return r.data}var GT=6e4,Bc=class{constructor(e){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($c,r=>{this._oncancel(r)}),this.setNotificationHandler(xc,r=>{this._onprogress(r)}),this.setRequestHandler(bc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Sc,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,f=new N(d.error.code,d.error.message,d.error.data);l(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new N(Z.InvalidParams,`Task not found: ${i}`);if(!Lr(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Lr(a.status)){let s=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Cr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(zc,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new N(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ic,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Lr(o.status))throw new N(Z.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new N(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof N?o:new N(Z.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,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),N.fromError(Z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){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=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),Li(i)||L$(i)?this._onresponse(i):$m(i)?this._onrequest(i,a):q$(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=N.fromError(Z.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Cr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=A$(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(a.signal.aborted)throw new N(Z.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Z.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()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Li(e))n(e);else{let a=new N(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Li(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Li(e))o(e);else{let a=N.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof N?a:new N(Z.InternalError,String(a))}}return}let i;try{let a=await this.request(e,ro,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new N(Z.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:s},Lr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:s.status==="failed"?yield{type:"error",error:new N(Z.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new N(Z.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof N?a:new N(Z.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=z=>{l(z)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(z){d(z);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Cr]:c}});let m=z=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(z)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let x=z instanceof N?z:new N(Z.RequestTimeout,String(z));l(x)};this._responseHandlers.set(f,z=>{if(!n?.signal?.aborted){if(z instanceof Error)return l(z);try{let x=Mr(r,z.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??GT,v=()=>m(N.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let z=x=>{let E=this._responseHandlers.get(f);E?E(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,z),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(z=>{this._cleanupTimeout(f),l(z)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},kc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Pc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},J$,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Cr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.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"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Cr]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Cr]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=Bm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=Wm(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Bm(e);this._notificationHandlers.set(n,o=>{let i=Wm(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&$m(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new N(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new N(Z.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new N(Z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new N(Z.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let s=await n.getTask(o,r);if(s){let c=Hi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Lr(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let s=await n.getTask(o,r);if(!s)throw new N(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Lr(s.status))throw new N(Z.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=Hi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Lr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Lb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vb(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];Lb(a)&&Lb(i)?r[o]={...a,...i}:r[o]=i}return r}var VS=qn(hk(),1),FS=qn(LS(),1);function RU(){let t=new VS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,FS.default)(t),t}var sl=class{constructor(e){this._ajv=e??RU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var cl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],a=i.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){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(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))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:e},Wi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},io,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function JS(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function KS(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ul=class extends Bc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Bi.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new sl,this.setRequestHandler(wm,n=>this._oninitialize(n)),this.setNotificationHandler(km,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(jm,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=Bi.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new cl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vb(this._capabilities,e)}setRequestHandler(e,r){let o=qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(jt(o)){let s=o;i=s._zod?.def?.value??s.value}else{let s=o;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(c,u)=>{let l=Mr(oo,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new N(Z.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=Mr(ro,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new N(Z.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=Mr(Dc,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new N(Z.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new 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 new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new 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 new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){KS(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&JS(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:D$.includes(r)?r:ym,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"},_c)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(i){if(o.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(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.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 e.tools?this.request({method:"sampling/createMessage",params:e},Om,r):this.request({method:"sampling/createMessage",params:e},Wi,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},io,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},io,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!s.valid)throw new N(Z.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof N?a:new N(Z.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,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:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Nm,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 GS=Symbol.for("mcp.completable");function $y(t){return!!t&&typeof t=="object"&&GS in t}function BS(t){return t[GS]?.complete}var HS;(function(t){t.Completable="McpCompletable"})(HS||(HS={}));var DU=/^[A-Za-z0-9._-]{1,128}$/;function CU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!DU.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ZU(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)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 by(t){let e=CU(t);return ZU(t,e.warnings),e.isValid}var ll=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var dl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ul(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ll(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Rc)),this.server.assertCanSetRequestHandler(on(oo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Rc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=bo(r.inputSchema);return o?Gm(o,{strictUnions:!0,pipeStrategy:"input"}):AU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=bo(r.outputSchema);o&&(n.outputSchema=Gm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(oo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new N(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,a="createTask"in n.handler;if((i==="required"||i==="optional")&&!a)throw new N(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new N(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,e,r);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof N&&n.code===Z.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=bo(e.inputSchema)??e.inputSchema,a=await Lc(i,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Vc(s);throw new N(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new N(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=bo(e.outputSchema),i=await Lc(o,r.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=Vc(a);throw new N(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${s}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let a={...n,taskStore:n.taskStore};if(e.inputSchema){let s=o;return await Promise.resolve(s.createTask(r,a))}else{let s=o;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=o;return await Promise.resolve(a(r,n))}else{let a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,a={...n,taskStore:n.taskStore},s=o?await Promise.resolve(i.createTask(o,a)):await Promise.resolve(i.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new N(Z.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(on(Cc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cc,async e=>{switch(e.params.ref.type){case"ref/prompt":return X$(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Y$(e),this.handleResourceCompletion(e,e.params.ref);default:throw new N(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new N(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ps;let i=qr(n.argsSchema)?.[e.params.argument.name];if(!$y(i))return ps;let a=BS(i);if(!a)return ps;let s=await a(e.params.argument.value,e.params.context);return XS(s)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ps;throw new N(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ps;let i=await o(e.params.argument.value,e.params.context);return XS(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Ec)),this.server.assertCanSetRequestHandler(on(Tc)),this.server.assertCanSetRequestHandler(on(jc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ec,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(r);for(let s of a.resources)o.push({...i.metadata,...s})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Tc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(jc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new N(Z.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(n.toString());if(a)return i.readCallback(n,a,r)}throw new N(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Oc)),this.server.assertCanSetRequestHandler(on(Nc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?UU(r.argsSchema):void 0}))})),this.server.setRequestHandler(Nc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new N(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new N(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=bo(n.argsSchema),i=await Lc(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Vc(c);throw new N(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=i.data,s=n.callback;return await Promise.resolve(s(a,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let a={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,o,i){let a={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,n,o,i){let a={title:r,description:n,argsSchema:o===void 0?void 0:$n(o),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=$n(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,o&&Object.values(o).some(c=>{let u=c instanceof Mi?c._def?.innerType:c;return $y(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,n,o,i,a,s,c,u){by(e);let l={title:r,description:n,inputSchema:WS(o),outputSchema:WS(i),annotations:a,execution:s,_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!==e&&(typeof d.name=="string"&&by(d.name),delete this._registeredTools[e],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=$n(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=$n(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[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(xy(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!xy(r[0])&&(a=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,n,o,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,i,a,s,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],a=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:a}=r,s=this._createRegisteredPrompt(e,o,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var AU={type:"object",properties:{}};function YS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function QS(t){return"_def"in t||"_zod"in t||YS(t)}function xy(t){return typeof t!="object"||t===null||QS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(YS)}function WS(t){if(t){if(xy(t))return $n(t);if(!QS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function UU(t){let e=qr(t);return e?Object.entries(e).map(([r,n])=>{let o=cb(n),i=ub(n);return{name:r,description:o,required:!i}}):[]}function on(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function XS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ps={completion:{values:[],hasMore:!1}};var ez=qn(require("fs")),wy=qn(require("path")),ky=(t,e)=>{let r=[];try{let n=ez.default.readdirSync(t,{withFileTypes:!0});for(let o of n){let i=wy.default.join(t,o.name);if(o.isDirectory())r=r.concat(ky(i,e));else if(o.isFile()&&o.name.endsWith(".js")){let a=wy.default.relative(e,i);r.push(a)}}}catch{}return r};var fl="@cyia/mcp-note",pl="1.0.3";var Sy=qn(require("path")),rz=async()=>{let t=new dl({name:fl,version:pl},{capabilities:{logging:{}}}),e=process.env.SCRIPT_DIR;return ky(e,e).forEach(n=>{console.error("\u811A\u672C",n,Sy.default.join(e,n)),import(Sy.default.join(e,n)).then(o=>{let i="default"in o?o.default:o;t.registerTool(i.name,i.config,i.cb)})}),t};async function MU(){console.error(`\u542F\u52A8\u670D\u52A1\u5668 ${fl} ${pl}`);let t=process.env.SCRIPT_DIR;console.log("dir",t),console.log("cwd",process.cwd()),console.log("__dirname",__dirname);let e=new Ac;await rz().then(r=>r.connect(e))}MU();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cyia/mcp-note",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "author": {
5
5
  "name": "wszgrcy",
6
6
  "email": "wszgrcy@gmail.com"
@@ -0,0 +1,15 @@
1
+ import { ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { AnySchema, ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
3
+ import { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
4
+ export type MCP_OBJECT<OutputArgs extends ZodRawShapeCompat | AnySchema, InputArgs extends undefined | ZodRawShapeCompat | AnySchema = undefined> = {
5
+ name: string;
6
+ config: {
7
+ title?: string;
8
+ description?: string;
9
+ inputSchema?: InputArgs;
10
+ outputSchema?: OutputArgs;
11
+ annotations?: ToolAnnotations;
12
+ _meta?: Record<string, unknown>;
13
+ };
14
+ cb: ToolCallback<InputArgs>;
15
+ };
@@ -0,0 +1,3 @@
1
+ import { MCP_OBJECT } from '../type/fn.type';
2
+ export * from 'zod';
3
+ export { MCP_OBJECT };