@cyia/mcp-note 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -58,7 +58,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
58
58
  ]))`;continue}else if(o[c]==="$"){n+=`($|(?=[\r
59
59
  ]))`;continue}}if(r.s&&o[c]==="."){n+=a?`${o[c]}\r
60
60
  `:`[${o[c]}\r
61
- ]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Yd(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===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let{type:o,...n}=Xd(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&t.keyType._def.type._def.checks?.length){let{type:o,...n}=Wd(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function uk(t,e){if(e.mapStrategy==="record")return Yd(t,e);let r=V(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),o=V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function lk(t){let e=t.values,o=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function dk(t){return t.target==="openAi"?void 0:{not:Ne({...t,currentPath:[...t.currentPath,"not"]})}}function fk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var fs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function mk(t,e){if(e.target==="openApi3")return pk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in fs&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let a=fs[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return pk(t,e)}var pk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>V(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function hk(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:fs[t.innerType._def.typeName],nullable:!0}:{type:[fs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=V(t.innerType._def,{...e,currentPath:[...e.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function gk(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",Lg(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?se(r,"minimum",o.value,o.message,e):se(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),se(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?se(r,"maximum",o.value,o.message,e):se(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),se(r,"maximum",o.value,o.message,e));break;case"multipleOf":se(r,"multipleOf",o.value,o.message,e);break}return r}function vk(t,e){let r=e.target==="openAi",o={type:"object",properties:{}},n=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=CN(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=V(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);let a=DN(t,e);return a!==void 0&&(o.additionalProperties=a),o}function DN(t,e){if(t.catchall._def.typeName!=="ZodNever")return V(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 CN(t){try{return t.isOptional()}catch{return!0}}var yk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return V(t.innerType._def,e);let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ne(e)},r]}:Ne(e)};var _k=(t,e)=>{if(e.pipeStrategy==="input")return V(t.in._def,e);if(e.pipeStrategy==="output")return V(t.out._def,e);let r=V(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=V(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function $k(t,e){return V(t.type._def,e)}function bk(t,e){let o={type:"array",uniqueItems:!0,items:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&se(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&se(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function xk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:V(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function wk(t){return{not:Ne(t)}}function kk(t){return Ne(t)}var Sk=(t,e)=>V(t.innerType._def,e);var zk=(t,e,r)=>{switch(e){case E.ZodString:return Xd(t,r);case E.ZodNumber:return gk(t,r);case E.ZodObject:return vk(t,r);case E.ZodBigInt:return ek(t,r);case E.ZodBoolean:return tk();case E.ZodDate:return Vg(t,r);case E.ZodUndefined:return wk(r);case E.ZodNull:return fk(r);case E.ZodArray:return Qw(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return mk(t,r);case E.ZodIntersection:return ak(t,r);case E.ZodTuple:return xk(t,r);case E.ZodRecord:return Yd(t,r);case E.ZodLiteral:return sk(t,r);case E.ZodEnum:return ik(t);case E.ZodNativeEnum:return lk(t);case E.ZodNullable:return hk(t,r);case E.ZodOptional:return yk(t,r);case E.ZodMap:return uk(t,r);case E.ZodSet:return bk(t,r);case E.ZodLazy:return()=>t.getter()._def;case E.ZodPromise:return $k(t,r);case E.ZodNaN:case E.ZodNever:return dk(r);case E.ZodEffects:return ok(t,r);case E.ZodAny:return Ne(r);case E.ZodUnknown:return kk(r);case E.ZodDefault:return nk(t,r);case E.ZodBranded:return Wd(t,r);case E.ZodReadonly:return Sk(t,r);case E.ZodCatch:return rk(t,r);case E.ZodPipeline:return _k(t,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(o=>{})(e)}};function V(t,e,r=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,r);if(s!==Ww)return s}if(o&&!r){let s=AN(o,e);if(s!==void 0)return s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let i=zk(t,t.typeName,e),a=typeof i=="function"?V(i(),e):i;if(a&&ZN(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var AN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Bd(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,o)=>e.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},ZN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Kg=(t,e)=>{let r=Yw(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:V(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ne(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=V(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ne(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&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?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 UN(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hg(t,e){return Ct(t)?Vn(t,{target:UN(e?.target),io:e?.pipeStrategy??"input"}):Kg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gg(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Gd(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Bg(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var MN=6e4,Qd=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(kd,r=>{this._oncancel(r)}),this.setNotificationHandler(zd,r=>{this._onprogress(r)}),this.setRequestHandler(Sd,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pd,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new Z(q.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ed,async(r,o)=>{let n=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.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 Z(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:o.requestId})}}let a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new Z(q.InvalidParams,`Task not found: ${i}`);if(!sn(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(sn(a.status)){let s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[en]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(Td,async(r,o)=>{try{let{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new Z(q.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Od,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new Z(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(sn(n.status))throw new Z(q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new Z(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof Z?n:new Z(q.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});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 o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};let n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Ja(i)||Pw(i)?this._onresponse(i):_g(i)?this._onrequest(i,a):zw(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 o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(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(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,i=e.params?._meta?.[en]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=ww(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.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 Z(q.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(()=>o(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()},n?.sessionId):await n?.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:q.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Ja(e))o(e);else{let a=new Z(e.error.code,e.error.message,e.error.data);o(a)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Ja(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),Ja(e))n(e);else{let a=Z.fromError(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(q.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Fo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new Z(q.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},sn(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new Z(q.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Z(q.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(q.InternalError,String(a))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=T=>{l(T)};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(T){d(T);return}o?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};o?.onprogress&&(this._progressHandlers.set(f,o.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||{},[en]:c}});let m=T=>{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(T)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(N=>this._onerror(new Error(`Failed to send cancellation: ${N}`)));let k=T instanceof Z?T:new Z(q.RequestTimeout,String(T));l(k)};this._responseHandlers.set(f,T=>{if(!o?.signal?.aborted){if(T instanceof Error)return l(T);try{let k=on(r,T.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),o?.signal?.addEventListener("abort",()=>{m(o?.signal?.reason)});let h=o?.timeout??MN,v=()=>m(Z.fromError(q.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,o?.maxTotalTimeout,v,o?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let T=k=>{let N=this._responseHandlers.get(f);N?N(k):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,T),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(f),l(k)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(T=>{this._cleanupTimeout(f),l(T)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Id,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},jd,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Tw,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[en]:r.relatedTask}}};await this._enqueueTaskMessage(o,{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||{},[en]: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||{},[en]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let o=Gg(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{let a=Bg(e,n);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 o=Gg(e);this._notificationHandlers.set(o,n=>{let i=Bg(e,n);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,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&_g(n.message)){let i=n.message.id,a=this._requestResolvers.get(i);a?(a(new Z(q.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 o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new Z(q.InvalidRequest,"Request cancelled"));return}let a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new Z(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let i=await o.getTask(n,r);if(!i)throw new Z(q.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);let s=await o.getTask(n,r);if(s){let c=Wa.parse({method:"notifications/tasks/status",params:s});await this.notification(c),sn(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{let s=await o.getTask(n,r);if(!s)throw new Z(q.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(sn(s.status))throw new Z(q.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);let c=await o.getTask(n,r);if(c){let u=Wa.parse({method:"notifications/tasks/status",params:c});await this.notification(u),sn(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Pk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ik(t,e){let r={...t};for(let o in e){let n=o,i=e[n];if(i===void 0)continue;let a=r[n];Pk(a)&&Pk(i)?r[n]={...a,...i}:r[n]=i}return r}var II=vc(ez(),1),EI=vc(PI(),1);function zq(){let t=new II.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,EI.default)(t),t}var fp=class{constructor(e){this._ajv=e??zq()}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 o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var pp=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.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],i=Array.isArray(n.content)?n.content:[n.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},Qa,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ho,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}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 TI(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 jI(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 mp=class extends Qd{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ya.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let i=this._loggingLevels.get(n);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fp,this.setRequestHandler(xg,o=>this._oninitialize(o)),this.setNotificationHandler(wg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Tg,async(o,n)=>{let i=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=o.params,s=Ya.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pp(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ik(this._capabilities,e)}setRequestHandler(e,r){let n=an(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i;if(Ct(n)){let s=n;i=s._zod?.def?.value??s.value}else{let s=n;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=on(Ko,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(q.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=on(Fo,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Z(q.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=on(Ud,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new Z(q.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){jI(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&TI(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:$w.includes(r)?r:vg,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"},wd)}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 o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.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(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},jg,r):this.request({method:"sampling/createMessage",params:e},Qa,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 n=e;return this.request({method:"elicitation/create",params:n},Ho,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:n},Ho,r);if(i.action==="accept"&&i.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(i.content);if(!s.valid)throw new Z(q.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof Z?a:new Z(q.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},Og,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 NI=Symbol.for("mcp.completable");function _$(t){return!!t&&typeof t=="object"&&NI in t}function RI(t){return t[NI]?.complete}var OI;(function(t){t.Completable="McpCompletable"})(OI||(OI={}));var Pq=/^[A-Za-z0-9._-]{1,128}$/;function Iq(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"),!Pq.test(t)){let r=t.split("").filter(o=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return e.push(`Tool name contains invalid characters: ${r.map(o=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Eq(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 $$(t){let e=Iq(t);return Eq(t,e.warnings),e.isValid}var hp=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,o){let n={taskSupport:"required",...r.execution};if(n.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,n,r._meta,o)}};var ur=_d;var gp=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 mp(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new hp(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Zd)),this.server.assertCanSetRequestHandler(wn(Ko)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zd,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let o={name:e,title:r.title,description:r.description,inputSchema:(()=>{let n=ci(r.inputSchema);return n?Hg(n,{strictUnions:!0,pipeStrategy:"input"}):Tq})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=ci(r.outputSchema);n&&(o.outputSchema=Hg(n,{strictUnions:!0,pipeStrategy:"output"}))}return o})})),this.server.setRequestHandler(Ko,async(e,r)=>{try{let o=this._registeredTools[e.params.name];if(!o)throw new Z(q.InvalidParams,`Tool ${e.params.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,i=o.execution?.taskSupport,a="createTask"in o.handler;if((i==="required"||i==="optional")&&!a)throw new Z(q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!n)throw new Z(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!n&&a)return await this.handleAutomaticTaskPolling(o,e,r);let s=await this.validateToolInput(o,e.params.arguments,e.params.name),c=await this.executeToolHandler(o,s,r);return n||await this.validateToolOutput(o,c,e.params.name),c}catch(o){if(o instanceof Z&&o.code===q.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,o){if(!e.inputSchema)return;let i=ci(e.inputSchema)??e.inputSchema,a=await Kd(i,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Hd(s);throw new Z(q.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${c}`)}return a.data}async validateToolOutput(e,r,o){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(q.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);let n=ci(e.outputSchema),i=await Kd(n,r.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=Hd(a);throw new Z(q.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${s}`)}}async executeToolHandler(e,r,o){let n=e.handler;if("createTask"in n){if(!o.taskStore)throw new Error("No task store provided.");let a={...o,taskStore:o.taskStore};if(e.inputSchema){let s=n;return await Promise.resolve(s.createTask(r,a))}else{let s=n;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=n;return await Promise.resolve(a(r,o))}else{let a=n;return await Promise.resolve(a(o))}}async handleAutomaticTaskPolling(e,r,o){if(!o.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,a={...o,taskStore:o.taskStore},s=n?await Promise.resolve(i.createTask(n,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 o.taskStore.getTask(c);if(!d)throw new Z(q.InternalError,`Task ${c} not found during polling`);u=d}return await o.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(wn(Md)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Md,async e=>{switch(e.params.ref.type){case"ref/prompt":return Cw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Aw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let o=this._registeredPrompts[r.name];if(!o)throw new Z(q.InvalidParams,`Prompt ${r.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Prompt ${r.name} disabled`);if(!o.argsSchema)return gc;let i=an(o.argsSchema)?.[e.params.argument.name];if(!_$(i))return gc;let a=RI(i);if(!a)return gc;let s=await a(e.params.argument.value,e.params.context);return CI(s)}async handleResourceCompletion(e,r){let o=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!o){if(this._registeredResources[r.uri])return gc;throw new Z(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=o.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return gc;let i=await n(e.params.argument.value,e.params.context);return CI(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Nd)),this.server.assertCanSetRequestHandler(wn(Rd)),this.server.assertCanSetRequestHandler(wn(Dd)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Nd,async(e,r)=>{let o=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),n=[];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)n.push({...i.metadata,...s})}return{resources:[...o,...n]}}),this.server.setRequestHandler(Rd,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,o])=>({name:r,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler(Dd,async(e,r)=>{let o=new URL(e.params.uri),n=this._registeredResources[o.toString()];if(n){if(!n.enabled)throw new Z(q.InvalidParams,`Resource ${o} disabled`);return n.readCallback(o,r)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(o.toString());if(a)return i.readCallback(o,a,r)}throw new Z(q.InvalidParams,`Resource ${o} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Cd)),this.server.assertCanSetRequestHandler(wn(Ad)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Cd,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?jq(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ad,async(e,r)=>{let o=this._registeredPrompts[e.params.name];if(!o)throw new Z(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(o.argsSchema){let n=ci(o.argsSchema),i=await Kd(n,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Hd(c);throw new Z(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=i.data,s=o.callback;return await Promise.resolve(s(a,r))}else{let n=o.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...o){let n;typeof o[0]=="object"&&(n=o.shift());let i=o[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,n,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,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,o,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,o.title,r,o,n);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,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,o,n,i){let a={name:e,title:r,metadata:n,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!==o&&(delete this._registeredResources[o],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[o]=a,a}_createRegisteredResourceTemplate(e,r,o,n,i){let a={resourceTemplate:o,title:r,metadata:n,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=o.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!o.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,o,n,i){let a={title:r,description:o,argsSchema:n===void 0?void 0:Hn(n),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=Hn(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,n&&Object.values(n).some(c=>{let u=c instanceof Lo?c._def?.innerType:c;return _$(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,o,n,i,a,s,c,u){$$(e);let l={title:r,description:o,inputSchema:DI(n),outputSchema:DI(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"&&$$(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=Hn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hn(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 o,n,i,a;if(typeof r[0]=="string"&&(o=r.shift()),r.length>1){let c=r[0];if(b$(c))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!b$(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,o,n,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,o){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,n,i,a,s,c,{taskSupport:"forbidden"},u,o)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let o;typeof r[0]=="string"&&(o=r.shift());let n;r.length>1&&(n=r.shift());let i=r[0],a=this._createRegisteredPrompt(e,void 0,o,n,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,o){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:i,argsSchema:a}=r,s=this._createRegisteredPrompt(e,n,i,a,o);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 Tq={type:"object",properties:{}};function AI(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function ZI(t){return"_def"in t||"_zod"in t||AI(t)}function b$(t){return typeof t!="object"||t===null||ZI(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(AI)}function DI(t){if(t){if(b$(t))return Hn(t);if(!ZI(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function jq(t){let e=an(t);return e?Object.entries(e).map(([r,o])=>{let n=Hw(o),i=Gw(o);return{name:r,description:n,required:!i}}):[]}function wn(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Gd(r);if(typeof o=="string")return o;throw new Error("Schema method literal must be a string")}function CI(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gc={completion:{values:[],hasMore:!1}};var vp="@cyia/mcp-note",yp="1.1.0";var MI=vc(require("path")),_p=process.env.SCRIPT_DIR??MI.default.join(process.cwd(),".vscode/mcp-note");function qI(t){return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()}var Oq=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function LI(t){return Array.from(t.match(Oq)??[])}function x$(t){let e=LI(t);if(e.length===0)return"";let[r,...o]=e;return`${r.toLowerCase()}${o.map(n=>qI(n)).join("")}`}function w$(t){return t.substring(0,1).toUpperCase()+t.substring(1)}var VI=ur.object({selector:ur.string().describe("\u7EC4\u4EF6\u9009\u62E9\u5668\u7684\u540D\u5B57"),inputs:ur.object({type:ur.string(),name:ur.string()}).describe("\u7EC4\u4EF6\u4E2D\u7684\u8F93\u5165\u5C5E\u6027").array(),outputs:ur.object({type:ur.string(),name:ur.string()}).describe("\u7EC4\u4EF6\u4E2D\u7684\u8F93\u51FA\u5C5E\u6027(\u4E8B\u4EF6,\u53D1\u5C04)").array(),slots:ur.string().describe("\u7EC4\u4EF6\u4E2D\u7684\u6295\u5F71,\u69FD\u7B49").array(),type:ur.enum(["fcc","nfcc","fgc"]).describe("fcc: \u8868\u5355\u63A7\u4EF6;nfcc: \u975E\u8868\u5355\u63A7\u4EF6(\u5E38\u89C4);fgc: \u8868\u5355\u5206\u7EC4(\u5BB9\u5668)")});function FI(t){let e=t.inputs.map(({name:n})=>`[${n}]="${n}"`).join(" "),r=t.outputs.map(({name:n})=>`(${n})="${n}($event)"`).join(" "),o=t.slots.map(n=>`<ng-container *ngTemplateOutlet="slot().${n}" ngProjectAs="${n}"></ng-container>`).join(`
61
+ ]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Yd(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===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let{type:o,...n}=Xd(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&t.keyType._def.type._def.checks?.length){let{type:o,...n}=Wd(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function uk(t,e){if(e.mapStrategy==="record")return Yd(t,e);let r=V(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),o=V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function lk(t){let e=t.values,o=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function dk(t){return t.target==="openAi"?void 0:{not:Ne({...t,currentPath:[...t.currentPath,"not"]})}}function fk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var fs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function mk(t,e){if(e.target==="openApi3")return pk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in fs&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let a=fs[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return pk(t,e)}var pk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>V(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function hk(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:fs[t.innerType._def.typeName],nullable:!0}:{type:[fs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=V(t.innerType._def,{...e,currentPath:[...e.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function gk(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",Lg(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?se(r,"minimum",o.value,o.message,e):se(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),se(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?se(r,"maximum",o.value,o.message,e):se(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),se(r,"maximum",o.value,o.message,e));break;case"multipleOf":se(r,"multipleOf",o.value,o.message,e);break}return r}function vk(t,e){let r=e.target==="openAi",o={type:"object",properties:{}},n=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=CN(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=V(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);let a=DN(t,e);return a!==void 0&&(o.additionalProperties=a),o}function DN(t,e){if(t.catchall._def.typeName!=="ZodNever")return V(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 CN(t){try{return t.isOptional()}catch{return!0}}var yk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return V(t.innerType._def,e);let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ne(e)},r]}:Ne(e)};var _k=(t,e)=>{if(e.pipeStrategy==="input")return V(t.in._def,e);if(e.pipeStrategy==="output")return V(t.out._def,e);let r=V(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=V(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function $k(t,e){return V(t.type._def,e)}function bk(t,e){let o={type:"array",uniqueItems:!0,items:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&se(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&se(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function xk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:V(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function wk(t){return{not:Ne(t)}}function kk(t){return Ne(t)}var Sk=(t,e)=>V(t.innerType._def,e);var zk=(t,e,r)=>{switch(e){case E.ZodString:return Xd(t,r);case E.ZodNumber:return gk(t,r);case E.ZodObject:return vk(t,r);case E.ZodBigInt:return ek(t,r);case E.ZodBoolean:return tk();case E.ZodDate:return Vg(t,r);case E.ZodUndefined:return wk(r);case E.ZodNull:return fk(r);case E.ZodArray:return Qw(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return mk(t,r);case E.ZodIntersection:return ak(t,r);case E.ZodTuple:return xk(t,r);case E.ZodRecord:return Yd(t,r);case E.ZodLiteral:return sk(t,r);case E.ZodEnum:return ik(t);case E.ZodNativeEnum:return lk(t);case E.ZodNullable:return hk(t,r);case E.ZodOptional:return yk(t,r);case E.ZodMap:return uk(t,r);case E.ZodSet:return bk(t,r);case E.ZodLazy:return()=>t.getter()._def;case E.ZodPromise:return $k(t,r);case E.ZodNaN:case E.ZodNever:return dk(r);case E.ZodEffects:return ok(t,r);case E.ZodAny:return Ne(r);case E.ZodUnknown:return kk(r);case E.ZodDefault:return nk(t,r);case E.ZodBranded:return Wd(t,r);case E.ZodReadonly:return Sk(t,r);case E.ZodCatch:return rk(t,r);case E.ZodPipeline:return _k(t,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(o=>{})(e)}};function V(t,e,r=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,r);if(s!==Ww)return s}if(o&&!r){let s=AN(o,e);if(s!==void 0)return s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let i=zk(t,t.typeName,e),a=typeof i=="function"?V(i(),e):i;if(a&&ZN(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var AN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Bd(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,o)=>e.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},ZN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Kg=(t,e)=>{let r=Yw(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:V(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ne(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=V(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ne(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&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?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 UN(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hg(t,e){return Ct(t)?Vn(t,{target:UN(e?.target),io:e?.pipeStrategy??"input"}):Kg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gg(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Gd(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Bg(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var MN=6e4,Qd=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(kd,r=>{this._oncancel(r)}),this.setNotificationHandler(zd,r=>{this._onprogress(r)}),this.setRequestHandler(Sd,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pd,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new Z(q.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ed,async(r,o)=>{let n=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.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 Z(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:o.requestId})}}let a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new Z(q.InvalidParams,`Task not found: ${i}`);if(!sn(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(sn(a.status)){let s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[en]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(Td,async(r,o)=>{try{let{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new Z(q.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Od,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new Z(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(sn(n.status))throw new Z(q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new Z(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof Z?n:new Z(q.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});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 o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};let n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Ja(i)||Pw(i)?this._onresponse(i):_g(i)?this._onrequest(i,a):zw(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 o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(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(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,i=e.params?._meta?.[en]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=ww(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.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 Z(q.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(()=>o(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()},n?.sessionId):await n?.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:q.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Ja(e))o(e);else{let a=new Z(e.error.code,e.error.message,e.error.data);o(a)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Ja(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),Ja(e))n(e);else{let a=Z.fromError(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(q.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Fo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new Z(q.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},sn(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new Z(q.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Z(q.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(q.InternalError,String(a))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=T=>{l(T)};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(T){d(T);return}o?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};o?.onprogress&&(this._progressHandlers.set(f,o.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||{},[en]:c}});let m=T=>{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(T)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(N=>this._onerror(new Error(`Failed to send cancellation: ${N}`)));let k=T instanceof Z?T:new Z(q.RequestTimeout,String(T));l(k)};this._responseHandlers.set(f,T=>{if(!o?.signal?.aborted){if(T instanceof Error)return l(T);try{let k=on(r,T.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),o?.signal?.addEventListener("abort",()=>{m(o?.signal?.reason)});let h=o?.timeout??MN,v=()=>m(Z.fromError(q.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,o?.maxTotalTimeout,v,o?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let T=k=>{let N=this._responseHandlers.get(f);N?N(k):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,T),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(f),l(k)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(T=>{this._cleanupTimeout(f),l(T)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Id,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},jd,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Tw,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[en]:r.relatedTask}}};await this._enqueueTaskMessage(o,{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||{},[en]: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||{},[en]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let o=Gg(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{let a=Bg(e,n);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 o=Gg(e);this._notificationHandlers.set(o,n=>{let i=Bg(e,n);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,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&_g(n.message)){let i=n.message.id,a=this._requestResolvers.get(i);a?(a(new Z(q.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 o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new Z(q.InvalidRequest,"Request cancelled"));return}let a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new Z(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let i=await o.getTask(n,r);if(!i)throw new Z(q.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);let s=await o.getTask(n,r);if(s){let c=Wa.parse({method:"notifications/tasks/status",params:s});await this.notification(c),sn(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{let s=await o.getTask(n,r);if(!s)throw new Z(q.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(sn(s.status))throw new Z(q.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);let c=await o.getTask(n,r);if(c){let u=Wa.parse({method:"notifications/tasks/status",params:c});await this.notification(u),sn(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Pk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ik(t,e){let r={...t};for(let o in e){let n=o,i=e[n];if(i===void 0)continue;let a=r[n];Pk(a)&&Pk(i)?r[n]={...a,...i}:r[n]=i}return r}var II=vc(ez(),1),EI=vc(PI(),1);function zq(){let t=new II.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,EI.default)(t),t}var fp=class{constructor(e){this._ajv=e??zq()}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 o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var pp=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.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],i=Array.isArray(n.content)?n.content:[n.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},Qa,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ho,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}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 TI(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 jI(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 mp=class extends Qd{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ya.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let i=this._loggingLevels.get(n);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fp,this.setRequestHandler(xg,o=>this._oninitialize(o)),this.setNotificationHandler(wg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Tg,async(o,n)=>{let i=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=o.params,s=Ya.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pp(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ik(this._capabilities,e)}setRequestHandler(e,r){let n=an(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i;if(Ct(n)){let s=n;i=s._zod?.def?.value??s.value}else{let s=n;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=on(Ko,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(q.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=on(Fo,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Z(q.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=on(Ud,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new Z(q.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){jI(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&TI(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:$w.includes(r)?r:vg,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"},wd)}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 o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.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(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},jg,r):this.request({method:"sampling/createMessage",params:e},Qa,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 n=e;return this.request({method:"elicitation/create",params:n},Ho,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:n},Ho,r);if(i.action==="accept"&&i.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(i.content);if(!s.valid)throw new Z(q.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof Z?a:new Z(q.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},Og,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 NI=Symbol.for("mcp.completable");function _$(t){return!!t&&typeof t=="object"&&NI in t}function RI(t){return t[NI]?.complete}var OI;(function(t){t.Completable="McpCompletable"})(OI||(OI={}));var Pq=/^[A-Za-z0-9._-]{1,128}$/;function Iq(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"),!Pq.test(t)){let r=t.split("").filter(o=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return e.push(`Tool name contains invalid characters: ${r.map(o=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Eq(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 $$(t){let e=Iq(t);return Eq(t,e.warnings),e.isValid}var hp=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,o){let n={taskSupport:"required",...r.execution};if(n.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,n,r._meta,o)}};var ur=_d;var gp=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 mp(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new hp(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Zd)),this.server.assertCanSetRequestHandler(wn(Ko)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zd,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let o={name:e,title:r.title,description:r.description,inputSchema:(()=>{let n=ci(r.inputSchema);return n?Hg(n,{strictUnions:!0,pipeStrategy:"input"}):Tq})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=ci(r.outputSchema);n&&(o.outputSchema=Hg(n,{strictUnions:!0,pipeStrategy:"output"}))}return o})})),this.server.setRequestHandler(Ko,async(e,r)=>{try{let o=this._registeredTools[e.params.name];if(!o)throw new Z(q.InvalidParams,`Tool ${e.params.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,i=o.execution?.taskSupport,a="createTask"in o.handler;if((i==="required"||i==="optional")&&!a)throw new Z(q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!n)throw new Z(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!n&&a)return await this.handleAutomaticTaskPolling(o,e,r);let s=await this.validateToolInput(o,e.params.arguments,e.params.name),c=await this.executeToolHandler(o,s,r);return n||await this.validateToolOutput(o,c,e.params.name),c}catch(o){if(o instanceof Z&&o.code===q.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,o){if(!e.inputSchema)return;let i=ci(e.inputSchema)??e.inputSchema,a=await Kd(i,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Hd(s);throw new Z(q.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${c}`)}return a.data}async validateToolOutput(e,r,o){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(q.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);let n=ci(e.outputSchema),i=await Kd(n,r.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=Hd(a);throw new Z(q.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${s}`)}}async executeToolHandler(e,r,o){let n=e.handler;if("createTask"in n){if(!o.taskStore)throw new Error("No task store provided.");let a={...o,taskStore:o.taskStore};if(e.inputSchema){let s=n;return await Promise.resolve(s.createTask(r,a))}else{let s=n;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=n;return await Promise.resolve(a(r,o))}else{let a=n;return await Promise.resolve(a(o))}}async handleAutomaticTaskPolling(e,r,o){if(!o.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,a={...o,taskStore:o.taskStore},s=n?await Promise.resolve(i.createTask(n,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 o.taskStore.getTask(c);if(!d)throw new Z(q.InternalError,`Task ${c} not found during polling`);u=d}return await o.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(wn(Md)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Md,async e=>{switch(e.params.ref.type){case"ref/prompt":return Cw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Aw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let o=this._registeredPrompts[r.name];if(!o)throw new Z(q.InvalidParams,`Prompt ${r.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Prompt ${r.name} disabled`);if(!o.argsSchema)return gc;let i=an(o.argsSchema)?.[e.params.argument.name];if(!_$(i))return gc;let a=RI(i);if(!a)return gc;let s=await a(e.params.argument.value,e.params.context);return CI(s)}async handleResourceCompletion(e,r){let o=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!o){if(this._registeredResources[r.uri])return gc;throw new Z(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=o.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return gc;let i=await n(e.params.argument.value,e.params.context);return CI(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Nd)),this.server.assertCanSetRequestHandler(wn(Rd)),this.server.assertCanSetRequestHandler(wn(Dd)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Nd,async(e,r)=>{let o=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),n=[];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)n.push({...i.metadata,...s})}return{resources:[...o,...n]}}),this.server.setRequestHandler(Rd,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,o])=>({name:r,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler(Dd,async(e,r)=>{let o=new URL(e.params.uri),n=this._registeredResources[o.toString()];if(n){if(!n.enabled)throw new Z(q.InvalidParams,`Resource ${o} disabled`);return n.readCallback(o,r)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(o.toString());if(a)return i.readCallback(o,a,r)}throw new Z(q.InvalidParams,`Resource ${o} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Cd)),this.server.assertCanSetRequestHandler(wn(Ad)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Cd,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?jq(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ad,async(e,r)=>{let o=this._registeredPrompts[e.params.name];if(!o)throw new Z(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!o.enabled)throw new Z(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(o.argsSchema){let n=ci(o.argsSchema),i=await Kd(n,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Hd(c);throw new Z(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=i.data,s=o.callback;return await Promise.resolve(s(a,r))}else{let n=o.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...o){let n;typeof o[0]=="object"&&(n=o.shift());let i=o[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,n,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,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,o,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,o.title,r,o,n);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,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,o,n,i){let a={name:e,title:r,metadata:n,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!==o&&(delete this._registeredResources[o],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[o]=a,a}_createRegisteredResourceTemplate(e,r,o,n,i){let a={resourceTemplate:o,title:r,metadata:n,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=o.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!o.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,o,n,i){let a={title:r,description:o,argsSchema:n===void 0?void 0:Hn(n),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=Hn(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,n&&Object.values(n).some(c=>{let u=c instanceof Lo?c._def?.innerType:c;return _$(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,o,n,i,a,s,c,u){$$(e);let l={title:r,description:o,inputSchema:DI(n),outputSchema:DI(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"&&$$(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=Hn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hn(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 o,n,i,a;if(typeof r[0]=="string"&&(o=r.shift()),r.length>1){let c=r[0];if(b$(c))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!b$(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,o,n,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,o){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,n,i,a,s,c,{taskSupport:"forbidden"},u,o)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let o;typeof r[0]=="string"&&(o=r.shift());let n;r.length>1&&(n=r.shift());let i=r[0],a=this._createRegisteredPrompt(e,void 0,o,n,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,o){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:i,argsSchema:a}=r,s=this._createRegisteredPrompt(e,n,i,a,o);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 Tq={type:"object",properties:{}};function AI(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function ZI(t){return"_def"in t||"_zod"in t||AI(t)}function b$(t){return typeof t!="object"||t===null||ZI(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(AI)}function DI(t){if(t){if(b$(t))return Hn(t);if(!ZI(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function jq(t){let e=an(t);return e?Object.entries(e).map(([r,o])=>{let n=Hw(o),i=Gw(o);return{name:r,description:n,required:!i}}):[]}function wn(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Gd(r);if(typeof o=="string")return o;throw new Error("Schema method literal must be a string")}function CI(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gc={completion:{values:[],hasMore:!1}};var vp="@cyia/mcp-note",yp="1.1.1";var MI=vc(require("path")),_p=process.env.SCRIPT_DIR??MI.default.join(process.cwd(),".vscode/mcp-note");function qI(t){return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()}var Oq=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function LI(t){return Array.from(t.match(Oq)??[])}function x$(t){let e=LI(t);if(e.length===0)return"";let[r,...o]=e;return`${r.toLowerCase()}${o.map(n=>qI(n)).join("")}`}function w$(t){return t.substring(0,1).toUpperCase()+t.substring(1)}var VI=ur.object({selector:ur.string().describe("\u7EC4\u4EF6\u9009\u62E9\u5668\u7684\u540D\u5B57"),inputs:ur.object({type:ur.string(),name:ur.string()}).describe("\u7EC4\u4EF6\u4E2D\u7684\u8F93\u5165\u5C5E\u6027").array(),outputs:ur.object({type:ur.string(),name:ur.string()}).describe("\u7EC4\u4EF6\u4E2D\u7684\u8F93\u51FA\u5C5E\u6027(\u4E8B\u4EF6,\u53D1\u5C04)").array(),slots:ur.string().describe("\u7EC4\u4EF6\u4E2D\u7684\u6295\u5F71,\u69FD\u7B49").array(),type:ur.enum(["fcc","nfcc","fgc"]).describe("fcc: \u8868\u5355\u63A7\u4EF6;nfcc: \u975E\u8868\u5355\u63A7\u4EF6(\u5E38\u89C4);fgc: \u8868\u5355\u5206\u7EC4(\u5BB9\u5668)")});function FI(t){let e=t.inputs.map(({name:n})=>`[${n}]="${n}"`).join(" "),r=t.outputs.map(({name:n})=>`(${n})="${n}($event)"`).join(" "),o=t.slots.map(n=>`<ng-container *ngTemplateOutlet="slot().${n}" ngProjectAs="${n}"></ng-container>`).join(`
62
62
  `);return t.type==="fcc"?`<ng-template #templateRef let-attr="attributes">
63
63
  <${t.selector} ${e} ${r} [class]="attr()?.class" [attributes]="attr()" [excludes]="['class']" [ngModel]="value$()" (ngModelChange)="valueChange($event)" (blur)="touchedChange()" [disabled]="disabled$()">${o}</${t.selector}>
64
64
  </ng-template>
@@ -124,7 +124,7 @@ ${r}
124
124
  ${o}
125
125
  ${i}
126
126
  }
127
- `;default:break}}var KI=async()=>{let t=new gp({name:vp,version:yp},{capabilities:{logging:{}}}),e=_p;return t.registerTool("extract-props",{description:"\u63D0\u53D6\u8F93\u5165\u5185\u5BB9\u4E2D\u7684selector,inputs,outputs,slots,type\u7B49\u76F8\u5173\u5C5E\u6027\u540D",inputSchema:VI},r=>({content:[{type:"text",text:`## html\u5185\u5BB9
127
+ `;default:break}}var KI=async()=>{let t=new gp({name:vp,version:yp},{capabilities:{logging:{}}}),e=_p;return t.registerTool("extract-props",{description:"\u63D0\u53D6\u8F93\u5165\u5185\u5BB9\u4E2D\u7684selector,inputs,outputs,slots,type\u7B49\u76F8\u5173\u5C5E\u6027\u540D,\u5E76\u751F\u6210angular\u7EC4\u4EF6",inputSchema:VI},r=>({content:[{type:"text",text:`## html\u5185\u5BB9
128
128
  ${FI(r)}
129
129
  ## ts\u5185\u5BB9
130
130
  ${JI(r)}`}]})),t};async function Nq(){console.error(`\u542F\u52A8\u670D\u52A1\u5668 ${vp} ${yp}`),console.log("dir",_p),console.log("__dirname",__dirname);let t=new Ld;await KI().then(e=>e.connect(t))}Nq();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cyia/mcp-note",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "author": {
5
5
  "name": "wszgrcy",
6
6
  "email": "wszgrcy@gmail.com"