@f2c/mcp 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- function E(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}import{z as o}from"zod";var de="2024-11-05",Ee=[de,"2024-10-07"],L="2.0",Ae=o.union([o.string(),o.number().int()]),je=o.string(),S=o.object({_meta:o.optional(o.object({progressToken:o.optional(Ae)}).passthrough())}).passthrough(),v=o.object({method:o.string(),params:o.optional(S)}),N=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),C=o.object({method:o.string(),params:o.optional(N)}),R=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),D=o.union([o.string(),o.number().int()]),Ie=o.object({jsonrpc:o.literal(L),id:D}).merge(v).strict(),Ne=n=>Ie.safeParse(n).success,Me=o.object({jsonrpc:o.literal(L)}).merge(C).strict(),Oe=n=>Me.safeParse(n).success,Le=o.object({jsonrpc:o.literal(L),id:D,result:R}).strict(),he=n=>Le.safeParse(n).success,b;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(b||(b={}));var De=o.object({jsonrpc:o.literal(L),id:D,error:o.object({code:o.number().int(),message:o.string(),data:o.optional(o.unknown())})}).strict(),qe=n=>De.safeParse(n).success,He=o.union([Ie,Me,Le,De]),q=R.strict(),H=C.extend({method:o.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.string().optional()})}),$e=o.object({name:o.string(),version:o.string()}).passthrough(),Ot=o.object({experimental:o.optional(o.object({}).passthrough()),sampling:o.optional(o.object({}).passthrough()),roots:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),fe=v.extend({method:o.literal("initialize"),params:S.extend({protocolVersion:o.string(),capabilities:Ot,clientInfo:$e})});var Lt=o.object({experimental:o.optional(o.object({}).passthrough()),logging:o.optional(o.object({}).passthrough()),completions:o.optional(o.object({}).passthrough()),prompts:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough()),resources:o.optional(o.object({subscribe:o.optional(o.boolean()),listChanged:o.optional(o.boolean())}).passthrough()),tools:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),Dt=R.extend({protocolVersion:o.string(),capabilities:Lt,serverInfo:$e,instructions:o.optional(o.string())}),ge=C.extend({method:o.literal("notifications/initialized")});var $=v.extend({method:o.literal("ping")}),qt=o.object({progress:o.number(),total:o.optional(o.number())}).passthrough(),Z=C.extend({method:o.literal("notifications/progress"),params:N.merge(qt).extend({progressToken:Ae})}),z=v.extend({params:S.extend({cursor:o.optional(je)}).optional()}),F=R.extend({nextCursor:o.optional(je)}),Ze=o.object({uri:o.string(),mimeType:o.optional(o.string())}).passthrough(),ze=Ze.extend({text:o.string()}),Fe=Ze.extend({blob:o.string().base64()}),Ht=o.object({uri:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),$t=o.object({uriTemplate:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),U=z.extend({method:o.literal("resources/list")}),Zt=F.extend({resources:o.array(Ht)}),V=z.extend({method:o.literal("resources/templates/list")}),zt=F.extend({resourceTemplates:o.array($t)}),J=v.extend({method:o.literal("resources/read"),params:S.extend({uri:o.string()})}),Ft=R.extend({contents:o.array(o.union([ze,Fe]))}),Ut=C.extend({method:o.literal("notifications/resources/list_changed")}),Vt=v.extend({method:o.literal("resources/subscribe"),params:S.extend({uri:o.string()})}),Jt=v.extend({method:o.literal("resources/unsubscribe"),params:S.extend({uri:o.string()})}),Bt=C.extend({method:o.literal("notifications/resources/updated"),params:N.extend({uri:o.string()})}),Gt=o.object({name:o.string(),description:o.optional(o.string()),required:o.optional(o.boolean())}).passthrough(),Kt=o.object({name:o.string(),description:o.optional(o.string()),arguments:o.optional(o.array(Gt))}).passthrough(),B=z.extend({method:o.literal("prompts/list")}),Xt=F.extend({prompts:o.array(Kt)}),G=v.extend({method:o.literal("prompts/get"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.string()))})}),K=o.object({type:o.literal("text"),text:o.string()}).passthrough(),X=o.object({type:o.literal("image"),data:o.string().base64(),mimeType:o.string()}).passthrough(),W=o.object({type:o.literal("audio"),data:o.string().base64(),mimeType:o.string()}).passthrough(),Ue=o.object({type:o.literal("resource"),resource:o.union([ze,Fe])}).passthrough(),Wt=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W,Ue])}).passthrough(),Yt=R.extend({description:o.optional(o.string()),messages:o.array(Wt)}),Qt=C.extend({method:o.literal("notifications/prompts/list_changed")}),er=o.object({name:o.string(),description:o.optional(o.string()),inputSchema:o.object({type:o.literal("object"),properties:o.optional(o.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.literal("tools/list")}),tr=F.extend({tools:o.array(er)}),Ve=R.extend({content:o.array(o.union([K,X,W,Ue])),isError:o.boolean().default(!1).optional()}),Or=Ve.or(R.extend({toolResult:o.unknown()})),Q=v.extend({method:o.literal("tools/call"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.unknown()))})}),rr=C.extend({method:o.literal("notifications/tools/list_changed")}),Je=o.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),nr=v.extend({method:o.literal("logging/setLevel"),params:S.extend({level:Je})}),or=C.extend({method:o.literal("notifications/message"),params:N.extend({level:Je,logger:o.optional(o.string()),data:o.unknown()})}),sr=o.object({name:o.string().optional()}).passthrough(),ar=o.object({hints:o.optional(o.array(sr)),costPriority:o.optional(o.number().min(0).max(1)),speedPriority:o.optional(o.number().min(0).max(1)),intelligencePriority:o.optional(o.number().min(0).max(1))}).passthrough(),ir=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W])}).passthrough(),cr=v.extend({method:o.literal("sampling/createMessage"),params:S.extend({messages:o.array(ir),systemPrompt:o.optional(o.string()),includeContext:o.optional(o.enum(["none","thisServer","allServers"])),temperature:o.optional(o.number()),maxTokens:o.number().int(),stopSequences:o.optional(o.array(o.string())),metadata:o.optional(o.object({}).passthrough()),modelPreferences:o.optional(ar)})}),be=R.extend({model:o.string(),stopReason:o.optional(o.enum(["endTurn","stopSequence","maxTokens"]).or(o.string())),role:o.enum(["user","assistant"]),content:o.discriminatedUnion("type",[K,X,W])}),lr=o.object({type:o.literal("ref/resource"),uri:o.string()}).passthrough(),pr=o.object({type:o.literal("ref/prompt"),name:o.string()}).passthrough(),ee=v.extend({method:o.literal("completion/complete"),params:S.extend({ref:o.union([pr,lr]),argument:o.object({name:o.string(),value:o.string()}).passthrough()})}),ur=R.extend({completion:o.object({values:o.array(o.string()).max(100),total:o.optional(o.number().int()),hasMore:o.optional(o.boolean())}).passthrough()}),mr=o.object({uri:o.string().startsWith("file://"),name:o.optional(o.string())}).passthrough(),dr=v.extend({method:o.literal("roots/list")}),ye=R.extend({roots:o.array(mr)}),hr=C.extend({method:o.literal("notifications/roots/list_changed")}),Lr=o.union([$,fe,ee,nr,G,B,U,V,J,Vt,Jt,Q,Y]),Dr=o.union([H,Z,ge,hr]),qr=o.union([q,be,ye]),Hr=o.union([$,cr,dr]),$r=o.union([H,Z,or,Bt,Ut,rr,Qt]),Zr=o.union([q,Dt,ur,Yt,Xt,Zt,zt,Ft,Ve,tr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var fr=6e4,te=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.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new y(b.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{he(t)||qe(t)?this._onresponse(t):Ne(t)?this._onrequest(t,r):Oe(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new y(b.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:b.MethodNotFound,message:"Method not found"}}).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,g,k)=>this.request(f,g,{...k,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(f=>{var g;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var g,k;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:b.InternalError,message:(k=f.message)!==null&&k!==void 0?k:"Internal error"}})}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),he(e))r(e);else{let s=new y(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var f,g,k,ue,me;if(!this._transport){l(new Error("Not connected"));return}((f=this._options)===null||f===void 0?void 0:f.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(g=r?.signal)===null||g===void 0||g.throwIfAborted();let w=this._requestMessageId++,we={...e,jsonrpc:"2.0",id:w};r?.onprogress&&(this._progressHandlers.set(w,r.onprogress),we.params={...e.params,_meta:{progressToken:w}});let Ce=x=>{var A;this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(x)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(x)};this._responseHandlers.set(w,x=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(x instanceof Error)return l(x);try{let I=t.parse(x.result);i(I)}catch(I){l(I)}}}),(k=r?.signal)===null||k===void 0||k.addEventListener("abort",()=>{var x;Ce((x=r?.signal)===null||x===void 0?void 0:x.reason)});let ke=(ue=r?.timeout)!==null&&ue!==void 0?ue:fr,Mt=()=>Ce(new y(b.RequestTimeout,"Request timed out",{timeout:ke}));this._setupTimeout(w,ke,r?.maxTotalTimeout,Mt,(me=r?.resetTimeoutOnProgress)!==null&&me!==void 0?me:!1),this._transport.send(we,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(w),l(x)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}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,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Be(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(fe,s=>this._oninitialize(s)),this.setNotificationHandler(ge,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Be(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ee.includes(t)?t:de,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"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},be,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},ye,t)}async sendLoggingMessage(e){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 Ke=Symbol("Let zodToJsonSchema decide on which parser to use");var Ge={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Xe=n=>typeof n=="string"?{...Ge,name:n}:{...Ge,...n};var We=n=>{let e=Xe(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function _e(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function h(n,e,t,r,s){n[e]=t,_e(n,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function Ye(){return{}}import{ZodFirstPartyTypeKind as gr}from"zod";function Qe(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==gr.ZodAny&&(t.items=m(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&h(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&h(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(h(t,"minItems",n.exactLength.value,n.exactLength.message,e),h(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function et(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}function tt(){return{type:"boolean"}}function ne(n,e){return m(n.type._def,e)}var rt=(n,e)=>m(n.innerType._def,e);function ve(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>ve(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return br(n,e)}}var br=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":h(t,"minimum",r.value,r.message,e);break;case"max":h(t,"maximum",r.value,r.message,e);break}return t};function nt(n,e){return{...m(n.innerType._def,e),default:n.defaultValue()}}function ot(n,e){return e.effectStrategy==="input"?m(n.schema._def,e):{}}function st(n){return{type:"string",enum:Array.from(n.values)}}var yr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function at(n,e){let t=[m(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(yr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function it(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}import{ZodFirstPartyTypeKind as M}from"zod";var xe,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(xe===void 0&&(xe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xe),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":T(t,"email",r.message,e);break;case"format:idn-email":T(t,"idn-email",r.message,e);break;case"pattern:zod":_(t,P.email,r.message,e);break}break;case"url":T(t,"uri",r.message,e);break;case"uuid":T(t,"uuid",r.message,e);break;case"regex":_(t,r.regex,r.message,e);break;case"cuid":_(t,P.cuid,r.message,e);break;case"cuid2":_(t,P.cuid2,r.message,e);break;case"startsWith":_(t,RegExp(`^${Se(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Se(r.value,e)}$`),r.message,e);break;case"datetime":T(t,"date-time",r.message,e);break;case"date":T(t,"date",r.message,e);break;case"time":T(t,"time",r.message,e);break;case"duration":T(t,"duration",r.message,e);break;case"length":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{_(t,RegExp(Se(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&T(t,"ipv4",r.message,e),r.version!=="v4"&&T(t,"ipv6",r.message,e);break}case"base64url":_(t,P.base64url,r.message,e);break;case"jwt":_(t,P.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&_(t,P.ipv4Cidr,r.message,e),r.version!=="v4"&&_(t,P.ipv6Cidr,r.message,e);break}case"emoji":_(t,P.emoji(),r.message,e);break;case"ulid":{_(t,P.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{T(t,"binary",r.message,e);break}case"contentEncoding:base64":{h(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{_(t,P.base64,r.message,e);break}}break}case"nanoid":_(t,P.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Se(n,e){return e.patternStrategy==="escape"?vr(n):n}var _r=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vr(n){let e="";for(let t=0;t<n.length;t++)_r.has(n[t])||(e+="\\"),e+=n[t];return e}function T(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):h(n,"format",e,t,r)}function _(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ct(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):h(n,"pattern",ct(e,r),t,r)}function ct(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
2
+ function x(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}import{execSync as Nt}from"child_process";import{z as o}from"zod";var fe="2024-11-05",je=[fe,"2024-10-07"],L="2.0",Ie=o.union([o.string(),o.number().int()]),Me=o.string(),R=o.object({_meta:o.optional(o.object({progressToken:o.optional(Ie)}).passthrough())}).passthrough(),v=o.object({method:o.string(),params:o.optional(R)}),M=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),E=o.object({method:o.string(),params:o.optional(M)}),P=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),D=o.union([o.string(),o.number().int()]),Ne=o.object({jsonrpc:o.literal(L),id:D}).merge(v).strict(),Oe=n=>Ne.safeParse(n).success,Le=o.object({jsonrpc:o.literal(L)}).merge(E).strict(),De=n=>Le.safeParse(n).success,$e=o.object({jsonrpc:o.literal(L),id:D,result:P}).strict(),ge=n=>$e.safeParse(n).success,b;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(b||(b={}));var qe=o.object({jsonrpc:o.literal(L),id:D,error:o.object({code:o.number().int(),message:o.string(),data:o.optional(o.unknown())})}).strict(),He=n=>qe.safeParse(n).success,Ze=o.union([Ne,Le,$e,qe]),$=P.strict(),q=E.extend({method:o.literal("notifications/cancelled"),params:M.extend({requestId:D,reason:o.string().optional()})}),ze=o.object({name:o.string(),version:o.string()}).passthrough(),Dt=o.object({experimental:o.optional(o.object({}).passthrough()),sampling:o.optional(o.object({}).passthrough()),roots:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),be=v.extend({method:o.literal("initialize"),params:R.extend({protocolVersion:o.string(),capabilities:Dt,clientInfo:ze})});var $t=o.object({experimental:o.optional(o.object({}).passthrough()),logging:o.optional(o.object({}).passthrough()),completions:o.optional(o.object({}).passthrough()),prompts:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough()),resources:o.optional(o.object({subscribe:o.optional(o.boolean()),listChanged:o.optional(o.boolean())}).passthrough()),tools:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),qt=P.extend({protocolVersion:o.string(),capabilities:$t,serverInfo:ze,instructions:o.optional(o.string())}),ye=E.extend({method:o.literal("notifications/initialized")});var H=v.extend({method:o.literal("ping")}),Ht=o.object({progress:o.number(),total:o.optional(o.number())}).passthrough(),Z=E.extend({method:o.literal("notifications/progress"),params:M.merge(Ht).extend({progressToken:Ie})}),z=v.extend({params:R.extend({cursor:o.optional(Me)}).optional()}),F=P.extend({nextCursor:o.optional(Me)}),Fe=o.object({uri:o.string(),mimeType:o.optional(o.string())}).passthrough(),Ve=Fe.extend({text:o.string()}),Ue=Fe.extend({blob:o.string().base64()}),Zt=o.object({uri:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),zt=o.object({uriTemplate:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),V=z.extend({method:o.literal("resources/list")}),Ft=F.extend({resources:o.array(Zt)}),U=z.extend({method:o.literal("resources/templates/list")}),Vt=F.extend({resourceTemplates:o.array(zt)}),J=v.extend({method:o.literal("resources/read"),params:R.extend({uri:o.string()})}),Ut=P.extend({contents:o.array(o.union([Ve,Ue]))}),Jt=E.extend({method:o.literal("notifications/resources/list_changed")}),Bt=v.extend({method:o.literal("resources/subscribe"),params:R.extend({uri:o.string()})}),Gt=v.extend({method:o.literal("resources/unsubscribe"),params:R.extend({uri:o.string()})}),Kt=E.extend({method:o.literal("notifications/resources/updated"),params:M.extend({uri:o.string()})}),Xt=o.object({name:o.string(),description:o.optional(o.string()),required:o.optional(o.boolean())}).passthrough(),Yt=o.object({name:o.string(),description:o.optional(o.string()),arguments:o.optional(o.array(Xt))}).passthrough(),B=z.extend({method:o.literal("prompts/list")}),Wt=F.extend({prompts:o.array(Yt)}),G=v.extend({method:o.literal("prompts/get"),params:R.extend({name:o.string(),arguments:o.optional(o.record(o.string()))})}),K=o.object({type:o.literal("text"),text:o.string()}).passthrough(),X=o.object({type:o.literal("image"),data:o.string().base64(),mimeType:o.string()}).passthrough(),Y=o.object({type:o.literal("audio"),data:o.string().base64(),mimeType:o.string()}).passthrough(),Je=o.object({type:o.literal("resource"),resource:o.union([Ve,Ue])}).passthrough(),Qt=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,Y,Je])}).passthrough(),er=P.extend({description:o.optional(o.string()),messages:o.array(Qt)}),tr=E.extend({method:o.literal("notifications/prompts/list_changed")}),rr=o.object({name:o.string(),description:o.optional(o.string()),inputSchema:o.object({type:o.literal("object"),properties:o.optional(o.object({}).passthrough())}).passthrough()}).passthrough(),W=z.extend({method:o.literal("tools/list")}),nr=F.extend({tools:o.array(rr)}),Be=P.extend({content:o.array(o.union([K,X,Y,Je])),isError:o.boolean().default(!1).optional()}),Dr=Be.or(P.extend({toolResult:o.unknown()})),Q=v.extend({method:o.literal("tools/call"),params:R.extend({name:o.string(),arguments:o.optional(o.record(o.unknown()))})}),or=E.extend({method:o.literal("notifications/tools/list_changed")}),Ge=o.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),sr=v.extend({method:o.literal("logging/setLevel"),params:R.extend({level:Ge})}),ar=E.extend({method:o.literal("notifications/message"),params:M.extend({level:Ge,logger:o.optional(o.string()),data:o.unknown()})}),ir=o.object({name:o.string().optional()}).passthrough(),cr=o.object({hints:o.optional(o.array(ir)),costPriority:o.optional(o.number().min(0).max(1)),speedPriority:o.optional(o.number().min(0).max(1)),intelligencePriority:o.optional(o.number().min(0).max(1))}).passthrough(),lr=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,Y])}).passthrough(),pr=v.extend({method:o.literal("sampling/createMessage"),params:R.extend({messages:o.array(lr),systemPrompt:o.optional(o.string()),includeContext:o.optional(o.enum(["none","thisServer","allServers"])),temperature:o.optional(o.number()),maxTokens:o.number().int(),stopSequences:o.optional(o.array(o.string())),metadata:o.optional(o.object({}).passthrough()),modelPreferences:o.optional(cr)})}),_e=P.extend({model:o.string(),stopReason:o.optional(o.enum(["endTurn","stopSequence","maxTokens"]).or(o.string())),role:o.enum(["user","assistant"]),content:o.discriminatedUnion("type",[K,X,Y])}),ur=o.object({type:o.literal("ref/resource"),uri:o.string()}).passthrough(),mr=o.object({type:o.literal("ref/prompt"),name:o.string()}).passthrough(),ee=v.extend({method:o.literal("completion/complete"),params:R.extend({ref:o.union([mr,ur]),argument:o.object({name:o.string(),value:o.string()}).passthrough()})}),dr=P.extend({completion:o.object({values:o.array(o.string()).max(100),total:o.optional(o.number().int()),hasMore:o.optional(o.boolean())}).passthrough()}),hr=o.object({uri:o.string().startsWith("file://"),name:o.optional(o.string())}).passthrough(),fr=v.extend({method:o.literal("roots/list")}),xe=P.extend({roots:o.array(hr)}),gr=E.extend({method:o.literal("notifications/roots/list_changed")}),$r=o.union([H,be,ee,sr,G,B,V,U,J,Bt,Gt,Q,W]),qr=o.union([q,Z,ye,gr]),Hr=o.union([$,_e,xe]),Zr=o.union([H,pr,fr]),zr=o.union([q,Z,ar,Kt,Jt,or,tr]),Fr=o.union([$,qt,dr,er,Wt,Ft,Vt,Ut,Be,nr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var br=6e4,te=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.setNotificationHandler(q,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler(H,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new y(b.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{ge(t)||He(t)?this._onresponse(t):Oe(t)?this._onrequest(t,r):De(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new y(b.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:b.MethodNotFound,message:"Method not found"}}).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,g,k)=>this.request(f,g,{...k,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(f=>{var g;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var g,k;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:b.InternalError,message:(k=f.message)!==null&&k!==void 0?k:"Internal error"}})}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),ge(e))r(e);else{let s=new y(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var f,g,k,de,he;if(!this._transport){l(new Error("Not connected"));return}((f=this._options)===null||f===void 0?void 0:f.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(g=r?.signal)===null||g===void 0||g.throwIfAborted();let C=this._requestMessageId++,Ee={...e,jsonrpc:"2.0",id:C};r?.onprogress&&(this._progressHandlers.set(C,r.onprogress),Ee.params={...e.params,_meta:{progressToken:C}});let ke=S=>{var A;this._responseHandlers.delete(C),this._progressHandlers.delete(C),this._cleanupTimeout(C),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:C,reason:String(S)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(S)};this._responseHandlers.set(C,S=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(S instanceof Error)return l(S);try{let I=t.parse(S.result);i(I)}catch(I){l(I)}}}),(k=r?.signal)===null||k===void 0||k.addEventListener("abort",()=>{var S;ke((S=r?.signal)===null||S===void 0?void 0:S.reason)});let Ae=(de=r?.timeout)!==null&&de!==void 0?de:br,Lt=()=>ke(new y(b.RequestTimeout,"Request timed out",{timeout:Ae}));this._setupTimeout(C,Ae,r?.maxTotalTimeout,Lt,(he=r?.resetTimeoutOnProgress)!==null&&he!==void 0?he:!1),this._transport.send(Ee,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(S=>{this._cleanupTimeout(C),l(S)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}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,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ke(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(be,s=>this._oninitialize(s)),this.setNotificationHandler(ye,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ke(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:je.includes(t)?t:fe,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"},$)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},_e,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},xe,t)}async sendLoggingMessage(e){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 Ye=Symbol("Let zodToJsonSchema decide on which parser to use");var Xe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},We=n=>typeof n=="string"?{...Xe,name:n}:{...Xe,...n};var Qe=n=>{let e=We(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function ve(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function h(n,e,t,r,s){n[e]=t,ve(n,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function et(){return{}}import{ZodFirstPartyTypeKind as yr}from"zod";function tt(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==yr.ZodAny&&(t.items=m(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&h(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&h(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(h(t,"minItems",n.exactLength.value,n.exactLength.message,e),h(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function rt(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}function nt(){return{type:"boolean"}}function ne(n,e){return m(n.type._def,e)}var ot=(n,e)=>m(n.innerType._def,e);function Se(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>Se(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return _r(n,e)}}var _r=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":h(t,"minimum",r.value,r.message,e);break;case"max":h(t,"maximum",r.value,r.message,e);break}return t};function st(n,e){return{...m(n.innerType._def,e),default:n.defaultValue()}}function at(n,e){return e.effectStrategy==="input"?m(n.schema._def,e):{}}function it(n){return{type:"string",enum:Array.from(n.values)}}var xr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function ct(n,e){let t=[m(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(xr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function lt(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}import{ZodFirstPartyTypeKind as N}from"zod";var Re,T={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Re===void 0&&(Re=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Re),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":w(t,"email",r.message,e);break;case"format:idn-email":w(t,"idn-email",r.message,e);break;case"pattern:zod":_(t,T.email,r.message,e);break}break;case"url":w(t,"uri",r.message,e);break;case"uuid":w(t,"uuid",r.message,e);break;case"regex":_(t,r.regex,r.message,e);break;case"cuid":_(t,T.cuid,r.message,e);break;case"cuid2":_(t,T.cuid2,r.message,e);break;case"startsWith":_(t,RegExp(`^${Pe(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Pe(r.value,e)}$`),r.message,e);break;case"datetime":w(t,"date-time",r.message,e);break;case"date":w(t,"date",r.message,e);break;case"time":w(t,"time",r.message,e);break;case"duration":w(t,"duration",r.message,e);break;case"length":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{_(t,RegExp(Pe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&w(t,"ipv4",r.message,e),r.version!=="v4"&&w(t,"ipv6",r.message,e);break}case"base64url":_(t,T.base64url,r.message,e);break;case"jwt":_(t,T.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&_(t,T.ipv4Cidr,r.message,e),r.version!=="v4"&&_(t,T.ipv6Cidr,r.message,e);break}case"emoji":_(t,T.emoji(),r.message,e);break;case"ulid":{_(t,T.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{w(t,"binary",r.message,e);break}case"contentEncoding:base64":{h(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{_(t,T.base64,r.message,e);break}}break}case"nanoid":_(t,T.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Pe(n,e){return e.patternStrategy==="escape"?Sr(n):n}var vr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sr(n){let e="";for(let t=0;t<n.length;t++)vr.has(n[t])||(e+="\\"),e+=n[t];return e}function w(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):h(n,"format",e,t,r)}function _(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:pt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):h(n,"pattern",pt(e,r),t,r)}function pt(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
3
3
  ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
4
4
  ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
5
5
  `:`[${r[l]}\r
6
- ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}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`),n.source}return s}function se(n,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"&&n.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===M.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===M.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===M.ZodBranded&&n.keyType._def.type._def.typeName===M.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function lt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=m(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function pt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ut(){return{not:{}}}function mt(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ht(n,e){if(e.target==="openApi3")return dt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in O&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=O[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return dt(n,e)}var dt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function ft(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:O[n.innerType._def.typeName],nullable:!0}:{type:[O[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function gt(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",_e(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as xr}from"zod";function bt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let f=Rr(l);f&&t&&(l instanceof xr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),f=!1);let g=m(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});g!==void 0&&(r.properties[i]=g,f||s.push(i))}s.length&&(r.required=s);let a=Sr(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Sr(n,e){if(n.catchall._def.typeName!=="ZodNever")return m(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Rr(n){try{return n.isOptional()}catch{return!0}}var yt=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(n.innerType._def,e);let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var _t=(n,e)=>{if(e.pipeStrategy==="input")return m(n.in._def,e);if(e.pipeStrategy==="output")return m(n.out._def,e);let t=m(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function vt(n,e){return m(n.type._def,e)}function xt(n,e){let r={type:"array",uniqueItems:!0,items:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&h(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&h(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function St(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Rt(){return{not:{}}}function Pt(){return{}}var Tt=(n,e)=>m(n.innerType._def,e);var wt=(n,e,t)=>{switch(e){case d.ZodString:return oe(n,t);case d.ZodNumber:return gt(n,t);case d.ZodObject:return bt(n,t);case d.ZodBigInt:return et(n,t);case d.ZodBoolean:return tt();case d.ZodDate:return ve(n,t);case d.ZodUndefined:return Rt();case d.ZodNull:return mt(t);case d.ZodArray:return Qe(n,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return ht(n,t);case d.ZodIntersection:return at(n,t);case d.ZodTuple:return St(n,t);case d.ZodRecord:return se(n,t);case d.ZodLiteral:return it(n,t);case d.ZodEnum:return st(n);case d.ZodNativeEnum:return pt(n);case d.ZodNullable:return ft(n,t);case d.ZodOptional:return yt(n,t);case d.ZodMap:return lt(n,t);case d.ZodSet:return xt(n,t);case d.ZodLazy:return()=>n.getter()._def;case d.ZodPromise:return vt(n,t);case d.ZodNaN:case d.ZodNever:return ut();case d.ZodEffects:return ot(n,t);case d.ZodAny:return Ye();case d.ZodUnknown:return Pt();case d.ZodDefault:return nt(n,t);case d.ZodBranded:return ne(n,t);case d.ZodReadonly:return Tt(n,t);case d.ZodCatch:return rt(n,t);case d.ZodPipeline:return _t(n,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==Ke)return i}if(r&&!t){let i=Pr(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=wt(n,n.typeName,e),a=typeof c=="function"?m(c(),e):c;if(a&&wr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Pr=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Tr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Tr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},wr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Re=(n,e)=>{let t=We(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[f,g])=>({...l,[f]:m(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=m(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};import{z as ae}from"zod";import{ZodType as Cr}from"zod";var Pe;(function(n){n.Completable="McpCompletable"})(Pe||(Pe={}));var j=class extends Cr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Pe.Completable,complete:e.complete,...kr(e)});function kr(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,f;let{message:g}=n;return a.code==="invalid_enum_value"?{message:g??i.defaultError}:typeof i.data>"u"?{message:(l=g??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(f=g??t)!==null&&f!==void 0?f:i.defaultError}},description:s}}var ce=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Re(t.inputSchema,{strictUnions:!0}):Er}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(b.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(b.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new y(b.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ie;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ie;let a=await s._def.complete(e.params.argument.value);return Ct(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ie;throw new y(b.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ie;let c=await s(e.params.argument.value);return Ct(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new y(b.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ar(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(b.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=ae.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=ae.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Er={type:"object"};function Ar(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Ct(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ie={completion:{values:[],hasMore:!1}};import Et from"node:process";var le=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
7
- `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),jr(t)}clear(){this._buffer=void 0}};function jr(n){return He.parse(JSON.parse(n))}function kt(n){return JSON.stringify(n)+`
8
- `}var pe=class{constructor(e=Et.stdin,t=Et.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new le,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=kt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};import{z as jt}from"zod";var Te=process.env.personalToken||""||"";function At(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var It=new ce({name:"F2C MCP",version:"0.0.1"});E("notification",{message:"MCP server instance created"});It.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:jt.string().default(Te).describe("Your Figma personal access token"),figmaUrl:jt.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{E("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=At(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return E("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Nt(){E("notification",{message:"Starting Figma-to-HTML service"});let n=new pe;E("notification",{message:"Transport layer initialized"}),await It.connect(n),E("notification",{message:"MCP server connected to stdio"})}Nt().catch(n=>{E("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
6
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}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`),n.source}return s}function se(n,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"&&n.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===N.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===N.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===N.ZodBranded&&n.keyType._def.type._def.typeName===N.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function ut(n,e){if(e.mapStrategy==="record")return se(n,e);let t=m(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function mt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function dt(){return{not:{}}}function ht(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gt(n,e){if(e.target==="openApi3")return ft(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in O&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=O[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return ft(n,e)}var ft=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function bt(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:O[n.innerType._def.typeName],nullable:!0}:{type:[O[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function yt(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",ve(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as Rr}from"zod";function _t(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let f=Tr(l);f&&t&&(l instanceof Rr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),f=!1);let g=m(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});g!==void 0&&(r.properties[i]=g,f||s.push(i))}s.length&&(r.required=s);let a=Pr(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Pr(n,e){if(n.catchall._def.typeName!=="ZodNever")return m(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Tr(n){try{return n.isOptional()}catch{return!0}}var xt=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(n.innerType._def,e);let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var vt=(n,e)=>{if(e.pipeStrategy==="input")return m(n.in._def,e);if(e.pipeStrategy==="output")return m(n.out._def,e);let t=m(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function St(n,e){return m(n.type._def,e)}function Rt(n,e){let r={type:"array",uniqueItems:!0,items:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&h(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&h(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function Pt(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Tt(){return{not:{}}}function wt(){return{}}var Ct=(n,e)=>m(n.innerType._def,e);var Et=(n,e,t)=>{switch(e){case d.ZodString:return oe(n,t);case d.ZodNumber:return yt(n,t);case d.ZodObject:return _t(n,t);case d.ZodBigInt:return rt(n,t);case d.ZodBoolean:return nt();case d.ZodDate:return Se(n,t);case d.ZodUndefined:return Tt();case d.ZodNull:return ht(t);case d.ZodArray:return tt(n,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return gt(n,t);case d.ZodIntersection:return ct(n,t);case d.ZodTuple:return Pt(n,t);case d.ZodRecord:return se(n,t);case d.ZodLiteral:return lt(n,t);case d.ZodEnum:return it(n);case d.ZodNativeEnum:return mt(n);case d.ZodNullable:return bt(n,t);case d.ZodOptional:return xt(n,t);case d.ZodMap:return ut(n,t);case d.ZodSet:return Rt(n,t);case d.ZodLazy:return()=>n.getter()._def;case d.ZodPromise:return St(n,t);case d.ZodNaN:case d.ZodNever:return dt();case d.ZodEffects:return at(n,t);case d.ZodAny:return et();case d.ZodUnknown:return wt();case d.ZodDefault:return st(n,t);case d.ZodBranded:return ne(n,t);case d.ZodReadonly:return Ct(n,t);case d.ZodCatch:return ot(n,t);case d.ZodPipeline:return vt(n,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==Ye)return i}if(r&&!t){let i=wr(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=Et(n,n.typeName,e),a=typeof c=="function"?m(c(),e):c;if(a&&Er(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var wr=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Cr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Cr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Er=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Te=(n,e)=>{let t=Qe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[f,g])=>({...l,[f]:m(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=m(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};import{z as ae}from"zod";import{ZodType as kr}from"zod";var we;(function(n){n.Completable="McpCompletable"})(we||(we={}));var j=class extends kr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:we.Completable,complete:e.complete,...Ar(e)});function Ar(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,f;let{message:g}=n;return a.code==="invalid_enum_value"?{message:g??i.defaultError}:typeof i.data>"u"?{message:(l=g??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(f=g??t)!==null&&f!==void 0?f:i.defaultError}},description:s}}var ce=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(W,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Te(t.inputSchema,{strictUnions:!0}):jr}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(b.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(b.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new y(b.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ie;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ie;let a=await s._def.complete(e.params.argument.value);return kt(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ie;throw new y(b.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ie;let c=await s(e.params.argument.value);return kt(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(V,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(U,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new y(b.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ir(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(b.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=ae.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=ae.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var jr={type:"object"};function Ir(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function kt(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ie={completion:{values:[],hasMore:!1}};import jt from"node:process";var le=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
7
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Mr(t)}clear(){this._buffer=void 0}};function Mr(n){return Ze.parse(JSON.parse(n))}function At(n){return JSON.stringify(n)+`
8
+ `}var pe=class{constructor(e=jt.stdin,t=jt.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new le,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=At(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};import{z as ue}from"zod";var Ce=process.env.personalToken||""||"";function It(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}function Mt(n){return n?n.length>214?{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u8D85\u8FC7214\u4E2A\u5B57\u7B26"}:/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(n)?n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico"?{isValid:!1,message:"\u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\u4F5C\u4E3A\u9879\u76EE\u540D"}:{isValid:!0}:{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001-\u3001.\u3001~\uFF0C\u5982\u679C\u4F7F\u7528 scope \u5219\u9700\u8981\u4EE5 @ \u5F00\u5934"}:{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"}}var me=new ce({name:"F2C MCP",version:"0.0.1"});x("notification",{message:"MCP server instance created"});me.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:ue.string().default(Ce).describe("Your Figma personal access token"),figmaUrl:ue.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Ce,figmaUrl:e})=>{x("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=It(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return x("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});me.tool("\u521B\u5EFA\u6216\u65B0\u589EAstro\u7EC4\u4EF6","\u521B\u5EFA\u6216\u65B0\u589EAstro\u7EC4\u4EF6\u901A\u8FC7\u7EC4\u4EF6\u540D\u5B57",{componentName:ue.string().regex(/^[A-Z][a-zA-Z0-9_]*$/,{message:"\u7EC4\u4EF6\u540D\u79F0\u5FC5\u987B\u4EE5\u5927\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u4E14\u53EA\u80FD\u5305\u542B\u82F1\u6587\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF"}).describe("\u7EC4\u4EF6\u7684\u540D\u5B57")},async({componentName:n})=>{x("notification",{message:"Creating Astro component",params:{componentName:n}});try{if(!n.match(/^[A-Z][a-zA-Z0-9_]*$/))throw new Error("\u7EC4\u4EF6\u540D\u79F0\u5FC5\u987B\u4EE5\u5927\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u4E14\u53EA\u80FD\u5305\u542B\u82F1\u6587\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF");try{return Nt(`npx --registry=https://npm-registry.yy.com @astro/create-astro new component ${n}`,{stdio:"pipe"}),{content:[{type:"text",text:`\u6210\u529F\u521B\u5EFA Astro \u7EC4\u4EF6: ${n} --registry=https://npm-registry.yy.com`}]}}catch(e){throw new Error(`\u521B\u5EFA\u7EC4\u4EF6\u5931\u8D25: ${e.message}
9
+ \u8BF7\u786E\u4FDD\u60A8\u5728YY\u5185\u7F51\u73AF\u5883\u4E0B\u6267\u884C\u6B64\u64CD\u4F5C`)}}catch(e){return x("error",{message:`Error: ${e.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${e.message}`}]}}});me.tool("\u521B\u5EFAAstro\u9879\u76EE","\u901A\u8FC7\u9879\u76EE\u540D\u79F0\u521B\u5EFA\u65B0\u7684Astro\u9879\u76EE",{projectName:ue.string().describe("\u9879\u76EE\u7684\u540D\u79F0")},async({projectName:n})=>{x("notification",{message:"Creating Astro project",params:{projectName:n}});try{let e=Mt(n);if(!e.isValid)throw new Error(e.message);try{return Nt(`npx --registry=https://npm-registry.yy.com @astro/create-astro new project --name ${n}`,{stdio:"pipe"}),{content:[{type:"text",text:`\u6210\u529F\u521B\u5EFA Astro \u9879\u76EE: ${n}`}]}}catch(t){throw new Error(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t.message}
10
+ \u8BF7\u786E\u4FDD\u60A8\u5728YY\u5185\u7F51\u73AF\u5883\u4E0B\u6267\u884C\u6B64\u64CD\u4F5C`)}}catch(e){return x("error",{message:`Error: ${e.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${e.message}`}]}}});async function Ot(){x("notification",{message:"Starting Figma-to-HTML service"});let n=new pe;x("notification",{message:"Transport layer initialized"}),await me.connect(n),x("notification",{message:"MCP server connected to stdio"})}Ot().catch(n=>{x("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
- "use strict";var qt=Object.create;var Ae=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty;var Ft=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $t(e))!zt.call(n,s)&&s!==t&&Ae(n,s,{get:()=>e[s],enumerable:!(r=Ht(e,s))||r.enumerable});return n};var Ut=(n,e,t)=>(t=n!=null?qt(Zt(n)):{},Ft(e||!n||!n.__esModule?Ae(t,"default",{value:n,enumerable:!0}):t,n));function k(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}var o=require("zod"),me="2024-11-05",je=[me,"2024-10-07"],L="2.0",Ie=o.z.union([o.z.string(),o.z.number().int()]),Ne=o.z.string(),x=o.z.object({_meta:o.z.optional(o.z.object({progressToken:o.z.optional(Ie)}).passthrough())}).passthrough(),_=o.z.object({method:o.z.string(),params:o.z.optional(x)}),N=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),w=o.z.object({method:o.z.string(),params:o.z.optional(N)}),S=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),D=o.z.union([o.z.string(),o.z.number().int()]),Me=o.z.object({jsonrpc:o.z.literal(L),id:D}).merge(_).strict(),Oe=n=>Me.safeParse(n).success,Le=o.z.object({jsonrpc:o.z.literal(L)}).merge(w).strict(),De=n=>Le.safeParse(n).success,qe=o.z.object({jsonrpc:o.z.literal(L),id:D,result:S}).strict(),de=n=>qe.safeParse(n).success,g;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(g||(g={}));var He=o.z.object({jsonrpc:o.z.literal(L),id:D,error:o.z.object({code:o.z.number().int(),message:o.z.string(),data:o.z.optional(o.z.unknown())})}).strict(),$e=n=>He.safeParse(n).success,Ze=o.z.union([Me,Le,qe,He]),q=S.strict(),H=w.extend({method:o.z.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.z.string().optional()})}),ze=o.z.object({name:o.z.string(),version:o.z.string()}).passthrough(),Vt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),sampling:o.z.optional(o.z.object({}).passthrough()),roots:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),he=_.extend({method:o.z.literal("initialize"),params:x.extend({protocolVersion:o.z.string(),capabilities:Vt,clientInfo:ze})});var Jt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),logging:o.z.optional(o.z.object({}).passthrough()),completions:o.z.optional(o.z.object({}).passthrough()),prompts:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough()),resources:o.z.optional(o.z.object({subscribe:o.z.optional(o.z.boolean()),listChanged:o.z.optional(o.z.boolean())}).passthrough()),tools:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),Bt=S.extend({protocolVersion:o.z.string(),capabilities:Jt,serverInfo:ze,instructions:o.z.optional(o.z.string())}),fe=w.extend({method:o.z.literal("notifications/initialized")});var $=_.extend({method:o.z.literal("ping")}),Gt=o.z.object({progress:o.z.number(),total:o.z.optional(o.z.number())}).passthrough(),Z=w.extend({method:o.z.literal("notifications/progress"),params:N.merge(Gt).extend({progressToken:Ie})}),z=_.extend({params:x.extend({cursor:o.z.optional(Ne)}).optional()}),F=S.extend({nextCursor:o.z.optional(Ne)}),Fe=o.z.object({uri:o.z.string(),mimeType:o.z.optional(o.z.string())}).passthrough(),Ue=Fe.extend({text:o.z.string()}),Ve=Fe.extend({blob:o.z.string().base64()}),Kt=o.z.object({uri:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),Xt=o.z.object({uriTemplate:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),U=z.extend({method:o.z.literal("resources/list")}),Wt=F.extend({resources:o.z.array(Kt)}),V=z.extend({method:o.z.literal("resources/templates/list")}),Yt=F.extend({resourceTemplates:o.z.array(Xt)}),J=_.extend({method:o.z.literal("resources/read"),params:x.extend({uri:o.z.string()})}),Qt=S.extend({contents:o.z.array(o.z.union([Ue,Ve]))}),er=w.extend({method:o.z.literal("notifications/resources/list_changed")}),tr=_.extend({method:o.z.literal("resources/subscribe"),params:x.extend({uri:o.z.string()})}),rr=_.extend({method:o.z.literal("resources/unsubscribe"),params:x.extend({uri:o.z.string()})}),nr=w.extend({method:o.z.literal("notifications/resources/updated"),params:N.extend({uri:o.z.string()})}),or=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),required:o.z.optional(o.z.boolean())}).passthrough(),sr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),arguments:o.z.optional(o.z.array(or))}).passthrough(),B=z.extend({method:o.z.literal("prompts/list")}),ar=F.extend({prompts:o.z.array(sr)}),G=_.extend({method:o.z.literal("prompts/get"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.string()))})}),K=o.z.object({type:o.z.literal("text"),text:o.z.string()}).passthrough(),X=o.z.object({type:o.z.literal("image"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),W=o.z.object({type:o.z.literal("audio"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),Je=o.z.object({type:o.z.literal("resource"),resource:o.z.union([Ue,Ve])}).passthrough(),ir=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W,Je])}).passthrough(),cr=S.extend({description:o.z.optional(o.z.string()),messages:o.z.array(ir)}),lr=w.extend({method:o.z.literal("notifications/prompts/list_changed")}),pr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),inputSchema:o.z.object({type:o.z.literal("object"),properties:o.z.optional(o.z.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.z.literal("tools/list")}),ur=F.extend({tools:o.z.array(pr)}),Be=S.extend({content:o.z.array(o.z.union([K,X,W,Je])),isError:o.z.boolean().default(!1).optional()}),zr=Be.or(S.extend({toolResult:o.z.unknown()})),Q=_.extend({method:o.z.literal("tools/call"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.unknown()))})}),mr=w.extend({method:o.z.literal("notifications/tools/list_changed")}),Ge=o.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=_.extend({method:o.z.literal("logging/setLevel"),params:x.extend({level:Ge})}),hr=w.extend({method:o.z.literal("notifications/message"),params:N.extend({level:Ge,logger:o.z.optional(o.z.string()),data:o.z.unknown()})}),fr=o.z.object({name:o.z.string().optional()}).passthrough(),gr=o.z.object({hints:o.z.optional(o.z.array(fr)),costPriority:o.z.optional(o.z.number().min(0).max(1)),speedPriority:o.z.optional(o.z.number().min(0).max(1)),intelligencePriority:o.z.optional(o.z.number().min(0).max(1))}).passthrough(),br=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W])}).passthrough(),yr=_.extend({method:o.z.literal("sampling/createMessage"),params:x.extend({messages:o.z.array(br),systemPrompt:o.z.optional(o.z.string()),includeContext:o.z.optional(o.z.enum(["none","thisServer","allServers"])),temperature:o.z.optional(o.z.number()),maxTokens:o.z.number().int(),stopSequences:o.z.optional(o.z.array(o.z.string())),metadata:o.z.optional(o.z.object({}).passthrough()),modelPreferences:o.z.optional(gr)})}),ge=S.extend({model:o.z.string(),stopReason:o.z.optional(o.z.enum(["endTurn","stopSequence","maxTokens"]).or(o.z.string())),role:o.z.enum(["user","assistant"]),content:o.z.discriminatedUnion("type",[K,X,W])}),_r=o.z.object({type:o.z.literal("ref/resource"),uri:o.z.string()}).passthrough(),vr=o.z.object({type:o.z.literal("ref/prompt"),name:o.z.string()}).passthrough(),ee=_.extend({method:o.z.literal("completion/complete"),params:x.extend({ref:o.z.union([vr,_r]),argument:o.z.object({name:o.z.string(),value:o.z.string()}).passthrough()})}),xr=S.extend({completion:o.z.object({values:o.z.array(o.z.string()).max(100),total:o.z.optional(o.z.number().int()),hasMore:o.z.optional(o.z.boolean())}).passthrough()}),Sr=o.z.object({uri:o.z.string().startsWith("file://"),name:o.z.optional(o.z.string())}).passthrough(),Rr=_.extend({method:o.z.literal("roots/list")}),be=S.extend({roots:o.z.array(Sr)}),Pr=w.extend({method:o.z.literal("notifications/roots/list_changed")}),Fr=o.z.union([$,he,ee,dr,G,B,U,V,J,tr,rr,Q,Y]),Ur=o.z.union([H,Z,fe,Pr]),Vr=o.z.union([q,ge,be]),Jr=o.z.union([$,yr,Rr]),Br=o.z.union([H,Z,hr,nr,er,mr,lr]),Gr=o.z.union([q,Bt,xr,cr,ar,Wt,Yt,Qt,Be,ur]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Tr=6e4,te=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.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new b(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{de(t)||$e(t)?this._onresponse(t):Oe(t)?this._onrequest(t,r):De(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new b(g.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:g.MethodNotFound,message:"Method not found"}}).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,f,C)=>this.request(h,f,{...C,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(h=>{var f;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var f,C;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(C=h.message)!==null&&C!==void 0?C:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),de(e))r(e);else{let s=new b(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var h,f,C,pe,ue;if(!this._transport){l(new Error("Not connected"));return}((h=this._options)===null||h===void 0?void 0:h.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let T=this._requestMessageId++,Ce={...e,jsonrpc:"2.0",id:T};r?.onprogress&&(this._progressHandlers.set(T,r.onprogress),Ce.params={...e.params,_meta:{progressToken:T}});let ke=v=>{var E;this._responseHandlers.delete(T),this._progressHandlers.delete(T),this._cleanupTimeout(T),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:T,reason:String(v)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(v)};this._responseHandlers.set(T,v=>{var E;if(!(!((E=r?.signal)===null||E===void 0)&&E.aborted)){if(v instanceof Error)return l(v);try{let I=t.parse(v.result);i(I)}catch(I){l(I)}}}),(C=r?.signal)===null||C===void 0||C.addEventListener("abort",()=>{var v;ke((v=r?.signal)===null||v===void 0?void 0:v.reason)});let Ee=(pe=r?.timeout)!==null&&pe!==void 0?pe:Tr,Dt=()=>ke(new b(g.RequestTimeout,"Request timed out",{timeout:Ee}));this._setupTimeout(T,Ee,r?.maxTotalTimeout,Dt,(ue=r?.resetTimeoutOnProgress)!==null&&ue!==void 0?ue:!1),this._transport.send(Ce,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(T),l(v)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}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,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ke(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(he,s=>this._oninitialize(s)),this.setNotificationHandler(fe,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ke(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:je.includes(t)?t:me,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"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},ge,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},be,t)}async sendLoggingMessage(e){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 We=Symbol("Let zodToJsonSchema decide on which parser to use");var Xe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Ye=n=>typeof n=="string"?{...Xe,name:n}:{...Xe,...n};var Qe=n=>{let e=Ye(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function ye(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function d(n,e,t,r,s){n[e]=t,ye(n,e,r,s)}var m=require("zod");function et(){return{}}var tt=require("zod");function rt(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==tt.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&d(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&d(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(d(t,"minItems",n.exactLength.value,n.exactLength.message,e),d(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function nt(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}function ot(){return{type:"boolean"}}function ne(n,e){return u(n.type._def,e)}var st=(n,e)=>u(n.innerType._def,e);function _e(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>_e(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return wr(n,e)}}var wr=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":d(t,"minimum",r.value,r.message,e);break;case"max":d(t,"maximum",r.value,r.message,e);break}return t};function at(n,e){return{...u(n.innerType._def,e),default:n.defaultValue()}}function it(n,e){return e.effectStrategy==="input"?u(n.schema._def,e):{}}function ct(n){return{type:"string",enum:Array.from(n.values)}}var Cr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function lt(n,e){let t=[u(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(Cr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function pt(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}var A=require("zod");var ve,R={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ve===void 0&&(ve=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ve),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":P(t,"email",r.message,e);break;case"format:idn-email":P(t,"idn-email",r.message,e);break;case"pattern:zod":y(t,R.email,r.message,e);break}break;case"url":P(t,"uri",r.message,e);break;case"uuid":P(t,"uuid",r.message,e);break;case"regex":y(t,r.regex,r.message,e);break;case"cuid":y(t,R.cuid,r.message,e);break;case"cuid2":y(t,R.cuid2,r.message,e);break;case"startsWith":y(t,RegExp(`^${xe(r.value,e)}`),r.message,e);break;case"endsWith":y(t,RegExp(`${xe(r.value,e)}$`),r.message,e);break;case"datetime":P(t,"date-time",r.message,e);break;case"date":P(t,"date",r.message,e);break;case"time":P(t,"time",r.message,e);break;case"duration":P(t,"duration",r.message,e);break;case"length":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{y(t,RegExp(xe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&P(t,"ipv4",r.message,e),r.version!=="v4"&&P(t,"ipv6",r.message,e);break}case"base64url":y(t,R.base64url,r.message,e);break;case"jwt":y(t,R.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&y(t,R.ipv4Cidr,r.message,e),r.version!=="v4"&&y(t,R.ipv6Cidr,r.message,e);break}case"emoji":y(t,R.emoji(),r.message,e);break;case"ulid":{y(t,R.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{P(t,"binary",r.message,e);break}case"contentEncoding:base64":{d(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{y(t,R.base64,r.message,e);break}}break}case"nanoid":y(t,R.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function xe(n,e){return e.patternStrategy==="escape"?Er(n):n}var kr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Er(n){let e="";for(let t=0;t<n.length;t++)kr.has(n[t])||(e+="\\"),e+=n[t];return e}function P(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(n,"format",e,t,r)}function y(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ut(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(n,"pattern",ut(e,r),t,r)}function ut(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
1
+ "use strict";var Ht=Object.create;var Ie=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var Ut=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zt(e))!Vt.call(n,s)&&s!==t&&Ie(n,s,{get:()=>e[s],enumerable:!(r=Zt(e,s))||r.enumerable});return n};var Jt=(n,e,t)=>(t=n!=null?Ht(Ft(n)):{},Ut(e||!n||!n.__esModule?Ie(t,"default",{value:n,enumerable:!0}):t,n));function _(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}var Ee=require("child_process");var o=require("zod"),he="2024-11-05",Me=[he,"2024-10-07"],D="2.0",Ne=o.z.union([o.z.string(),o.z.number().int()]),Oe=o.z.string(),S=o.z.object({_meta:o.z.optional(o.z.object({progressToken:o.z.optional(Ne)}).passthrough())}).passthrough(),x=o.z.object({method:o.z.string(),params:o.z.optional(S)}),M=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),C=o.z.object({method:o.z.string(),params:o.z.optional(M)}),R=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),$=o.z.union([o.z.string(),o.z.number().int()]),Le=o.z.object({jsonrpc:o.z.literal(D),id:$}).merge(x).strict(),De=n=>Le.safeParse(n).success,$e=o.z.object({jsonrpc:o.z.literal(D)}).merge(C).strict(),qe=n=>$e.safeParse(n).success,He=o.z.object({jsonrpc:o.z.literal(D),id:$,result:R}).strict(),fe=n=>He.safeParse(n).success,g;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(g||(g={}));var Ze=o.z.object({jsonrpc:o.z.literal(D),id:$,error:o.z.object({code:o.z.number().int(),message:o.z.string(),data:o.z.optional(o.z.unknown())})}).strict(),ze=n=>Ze.safeParse(n).success,Fe=o.z.union([Le,$e,He,Ze]),q=R.strict(),H=C.extend({method:o.z.literal("notifications/cancelled"),params:M.extend({requestId:$,reason:o.z.string().optional()})}),Ve=o.z.object({name:o.z.string(),version:o.z.string()}).passthrough(),Bt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),sampling:o.z.optional(o.z.object({}).passthrough()),roots:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),ge=x.extend({method:o.z.literal("initialize"),params:S.extend({protocolVersion:o.z.string(),capabilities:Bt,clientInfo:Ve})});var Gt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),logging:o.z.optional(o.z.object({}).passthrough()),completions:o.z.optional(o.z.object({}).passthrough()),prompts:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough()),resources:o.z.optional(o.z.object({subscribe:o.z.optional(o.z.boolean()),listChanged:o.z.optional(o.z.boolean())}).passthrough()),tools:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),Kt=R.extend({protocolVersion:o.z.string(),capabilities:Gt,serverInfo:Ve,instructions:o.z.optional(o.z.string())}),be=C.extend({method:o.z.literal("notifications/initialized")});var Z=x.extend({method:o.z.literal("ping")}),Xt=o.z.object({progress:o.z.number(),total:o.z.optional(o.z.number())}).passthrough(),z=C.extend({method:o.z.literal("notifications/progress"),params:M.merge(Xt).extend({progressToken:Ne})}),F=x.extend({params:S.extend({cursor:o.z.optional(Oe)}).optional()}),V=R.extend({nextCursor:o.z.optional(Oe)}),Ue=o.z.object({uri:o.z.string(),mimeType:o.z.optional(o.z.string())}).passthrough(),Je=Ue.extend({text:o.z.string()}),Be=Ue.extend({blob:o.z.string().base64()}),Yt=o.z.object({uri:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),Wt=o.z.object({uriTemplate:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),U=F.extend({method:o.z.literal("resources/list")}),Qt=V.extend({resources:o.z.array(Yt)}),J=F.extend({method:o.z.literal("resources/templates/list")}),er=V.extend({resourceTemplates:o.z.array(Wt)}),B=x.extend({method:o.z.literal("resources/read"),params:S.extend({uri:o.z.string()})}),tr=R.extend({contents:o.z.array(o.z.union([Je,Be]))}),rr=C.extend({method:o.z.literal("notifications/resources/list_changed")}),nr=x.extend({method:o.z.literal("resources/subscribe"),params:S.extend({uri:o.z.string()})}),or=x.extend({method:o.z.literal("resources/unsubscribe"),params:S.extend({uri:o.z.string()})}),sr=C.extend({method:o.z.literal("notifications/resources/updated"),params:M.extend({uri:o.z.string()})}),ar=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),required:o.z.optional(o.z.boolean())}).passthrough(),ir=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),arguments:o.z.optional(o.z.array(ar))}).passthrough(),G=F.extend({method:o.z.literal("prompts/list")}),cr=V.extend({prompts:o.z.array(ir)}),K=x.extend({method:o.z.literal("prompts/get"),params:S.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.string()))})}),X=o.z.object({type:o.z.literal("text"),text:o.z.string()}).passthrough(),Y=o.z.object({type:o.z.literal("image"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),W=o.z.object({type:o.z.literal("audio"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),Ge=o.z.object({type:o.z.literal("resource"),resource:o.z.union([Je,Be])}).passthrough(),lr=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([X,Y,W,Ge])}).passthrough(),pr=R.extend({description:o.z.optional(o.z.string()),messages:o.z.array(lr)}),ur=C.extend({method:o.z.literal("notifications/prompts/list_changed")}),mr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),inputSchema:o.z.object({type:o.z.literal("object"),properties:o.z.optional(o.z.object({}).passthrough())}).passthrough()}).passthrough(),Q=F.extend({method:o.z.literal("tools/list")}),dr=V.extend({tools:o.z.array(mr)}),Ke=R.extend({content:o.z.array(o.z.union([X,Y,W,Ge])),isError:o.z.boolean().default(!1).optional()}),Vr=Ke.or(R.extend({toolResult:o.z.unknown()})),ee=x.extend({method:o.z.literal("tools/call"),params:S.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.unknown()))})}),hr=C.extend({method:o.z.literal("notifications/tools/list_changed")}),Xe=o.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),fr=x.extend({method:o.z.literal("logging/setLevel"),params:S.extend({level:Xe})}),gr=C.extend({method:o.z.literal("notifications/message"),params:M.extend({level:Xe,logger:o.z.optional(o.z.string()),data:o.z.unknown()})}),br=o.z.object({name:o.z.string().optional()}).passthrough(),yr=o.z.object({hints:o.z.optional(o.z.array(br)),costPriority:o.z.optional(o.z.number().min(0).max(1)),speedPriority:o.z.optional(o.z.number().min(0).max(1)),intelligencePriority:o.z.optional(o.z.number().min(0).max(1))}).passthrough(),_r=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([X,Y,W])}).passthrough(),xr=x.extend({method:o.z.literal("sampling/createMessage"),params:S.extend({messages:o.z.array(_r),systemPrompt:o.z.optional(o.z.string()),includeContext:o.z.optional(o.z.enum(["none","thisServer","allServers"])),temperature:o.z.optional(o.z.number()),maxTokens:o.z.number().int(),stopSequences:o.z.optional(o.z.array(o.z.string())),metadata:o.z.optional(o.z.object({}).passthrough()),modelPreferences:o.z.optional(yr)})}),ye=R.extend({model:o.z.string(),stopReason:o.z.optional(o.z.enum(["endTurn","stopSequence","maxTokens"]).or(o.z.string())),role:o.z.enum(["user","assistant"]),content:o.z.discriminatedUnion("type",[X,Y,W])}),vr=o.z.object({type:o.z.literal("ref/resource"),uri:o.z.string()}).passthrough(),Sr=o.z.object({type:o.z.literal("ref/prompt"),name:o.z.string()}).passthrough(),te=x.extend({method:o.z.literal("completion/complete"),params:S.extend({ref:o.z.union([Sr,vr]),argument:o.z.object({name:o.z.string(),value:o.z.string()}).passthrough()})}),Rr=R.extend({completion:o.z.object({values:o.z.array(o.z.string()).max(100),total:o.z.optional(o.z.number().int()),hasMore:o.z.optional(o.z.boolean())}).passthrough()}),Pr=o.z.object({uri:o.z.string().startsWith("file://"),name:o.z.optional(o.z.string())}).passthrough(),Tr=x.extend({method:o.z.literal("roots/list")}),_e=R.extend({roots:o.z.array(Pr)}),wr=C.extend({method:o.z.literal("notifications/roots/list_changed")}),Ur=o.z.union([Z,ge,te,fr,K,G,U,J,B,nr,or,ee,Q]),Jr=o.z.union([H,z,be,wr]),Br=o.z.union([q,ye,_e]),Gr=o.z.union([Z,xr,Tr]),Kr=o.z.union([H,z,gr,sr,rr,hr,ur]),Xr=o.z.union([q,Kt,Rr,pr,cr,Qt,er,tr,Ke,dr]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Cr=6e4,re=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.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(z,t=>{this._onprogress(t)}),this.setRequestHandler(Z,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new b(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{fe(t)||ze(t)?this._onresponse(t):De(t)?this._onrequest(t,r):qe(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new b(g.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:g.MethodNotFound,message:"Method not found"}}).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,f,E)=>this.request(h,f,{...E,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(h=>{var f;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var f,E;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(E=h.message)!==null&&E!==void 0?E:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),fe(e))r(e);else{let s=new b(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var h,f,E,me,de;if(!this._transport){l(new Error("Not connected"));return}((h=this._options)===null||h===void 0?void 0:h.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let w=this._requestMessageId++,ke={...e,jsonrpc:"2.0",id:w};r?.onprogress&&(this._progressHandlers.set(w,r.onprogress),ke.params={...e.params,_meta:{progressToken:w}});let Ae=v=>{var k;this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),(k=this._transport)===null||k===void 0||k.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(v)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(v)};this._responseHandlers.set(w,v=>{var k;if(!(!((k=r?.signal)===null||k===void 0)&&k.aborted)){if(v instanceof Error)return l(v);try{let I=t.parse(v.result);i(I)}catch(I){l(I)}}}),(E=r?.signal)===null||E===void 0||E.addEventListener("abort",()=>{var v;Ae((v=r?.signal)===null||v===void 0?void 0:v.reason)});let je=(me=r?.timeout)!==null&&me!==void 0?me:Cr,qt=()=>Ae(new b(g.RequestTimeout,"Request timed out",{timeout:je}));this._setupTimeout(w,je,r?.maxTotalTimeout,qt,(de=r?.resetTimeoutOnProgress)!==null&&de!==void 0?de:!1),this._transport.send(ke,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(w),l(v)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}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,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ye(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var ne=class extends re{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(ge,s=>this._oninitialize(s)),this.setNotificationHandler(be,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ye(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Me.includes(t)?t:he,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"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},ye,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},_e,t)}async sendLoggingMessage(e){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 Qe=Symbol("Let zodToJsonSchema decide on which parser to use");var We={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},et=n=>typeof n=="string"?{...We,name:n}:{...We,...n};var tt=n=>{let e=et(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function xe(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function d(n,e,t,r,s){n[e]=t,xe(n,e,r,s)}var m=require("zod");function rt(){return{}}var nt=require("zod");function ot(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==nt.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&d(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&d(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(d(t,"minItems",n.exactLength.value,n.exactLength.message,e),d(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function st(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}function at(){return{type:"boolean"}}function oe(n,e){return u(n.type._def,e)}var it=(n,e)=>u(n.innerType._def,e);function ve(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>ve(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Er(n,e)}}var Er=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":d(t,"minimum",r.value,r.message,e);break;case"max":d(t,"maximum",r.value,r.message,e);break}return t};function ct(n,e){return{...u(n.innerType._def,e),default:n.defaultValue()}}function lt(n,e){return e.effectStrategy==="input"?u(n.schema._def,e):{}}function pt(n){return{type:"string",enum:Array.from(n.values)}}var kr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function ut(n,e){let t=[u(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(kr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function mt(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}var A=require("zod");var Se,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Se===void 0&&(Se=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Se),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function se(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":T(t,"email",r.message,e);break;case"format:idn-email":T(t,"idn-email",r.message,e);break;case"pattern:zod":y(t,P.email,r.message,e);break}break;case"url":T(t,"uri",r.message,e);break;case"uuid":T(t,"uuid",r.message,e);break;case"regex":y(t,r.regex,r.message,e);break;case"cuid":y(t,P.cuid,r.message,e);break;case"cuid2":y(t,P.cuid2,r.message,e);break;case"startsWith":y(t,RegExp(`^${Re(r.value,e)}`),r.message,e);break;case"endsWith":y(t,RegExp(`${Re(r.value,e)}$`),r.message,e);break;case"datetime":T(t,"date-time",r.message,e);break;case"date":T(t,"date",r.message,e);break;case"time":T(t,"time",r.message,e);break;case"duration":T(t,"duration",r.message,e);break;case"length":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{y(t,RegExp(Re(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&T(t,"ipv4",r.message,e),r.version!=="v4"&&T(t,"ipv6",r.message,e);break}case"base64url":y(t,P.base64url,r.message,e);break;case"jwt":y(t,P.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&y(t,P.ipv4Cidr,r.message,e),r.version!=="v4"&&y(t,P.ipv6Cidr,r.message,e);break}case"emoji":y(t,P.emoji(),r.message,e);break;case"ulid":{y(t,P.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{T(t,"binary",r.message,e);break}case"contentEncoding:base64":{d(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{y(t,P.base64,r.message,e);break}}break}case"nanoid":y(t,P.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Re(n,e){return e.patternStrategy==="escape"?jr(n):n}var Ar=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function jr(n){let e="";for(let t=0;t<n.length;t++)Ar.has(n[t])||(e+="\\"),e+=n[t];return e}function T(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(n,"format",e,t,r)}function y(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:dt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(n,"pattern",dt(e,r),t,r)}function dt(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
2
2
  ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
3
3
  ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
4
4
  `:`[${r[l]}\r
5
- ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}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`),n.source}return s}function se(n,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"&&n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodBranded&&n.keyType._def.type._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function mt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=u(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function dt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ht(){return{not:{}}}function ft(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var M={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bt(n,e){if(e.target==="openApi3")return gt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in M&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=M[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return gt(n,e)}var gt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>u(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function yt(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:M[n.innerType._def.typeName],nullable:!0}:{type:[M[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function _t(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",ye(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}var vt=require("zod");function xt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let h=jr(l);h&&t&&(l instanceof vt.ZodOptional&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),h=!1);let f=u(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,h||s.push(i))}s.length&&(r.required=s);let a=Ar(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Ar(n,e){if(n.catchall._def.typeName!=="ZodNever")return u(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function jr(n){try{return n.isOptional()}catch{return!0}}var St=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(n.innerType._def,e);let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Rt=(n,e)=>{if(e.pipeStrategy==="input")return u(n.in._def,e);if(e.pipeStrategy==="output")return u(n.out._def,e);let t=u(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Pt(n,e){return u(n.type._def,e)}function Tt(n,e){let r={type:"array",uniqueItems:!0,items:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&d(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&d(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function wt(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Ct(){return{not:{}}}function kt(){return{}}var Et=(n,e)=>u(n.innerType._def,e);var At=(n,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return oe(n,t);case m.ZodFirstPartyTypeKind.ZodNumber:return _t(n,t);case m.ZodFirstPartyTypeKind.ZodObject:return xt(n,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return nt(n,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return ot();case m.ZodFirstPartyTypeKind.ZodDate:return _e(n,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return Ct();case m.ZodFirstPartyTypeKind.ZodNull:return ft(t);case m.ZodFirstPartyTypeKind.ZodArray:return rt(n,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return bt(n,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return lt(n,t);case m.ZodFirstPartyTypeKind.ZodTuple:return wt(n,t);case m.ZodFirstPartyTypeKind.ZodRecord:return se(n,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return pt(n,t);case m.ZodFirstPartyTypeKind.ZodEnum:return ct(n);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return dt(n);case m.ZodFirstPartyTypeKind.ZodNullable:return yt(n,t);case m.ZodFirstPartyTypeKind.ZodOptional:return St(n,t);case m.ZodFirstPartyTypeKind.ZodMap:return mt(n,t);case m.ZodFirstPartyTypeKind.ZodSet:return Tt(n,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>n.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return Pt(n,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return ht();case m.ZodFirstPartyTypeKind.ZodEffects:return it(n,t);case m.ZodFirstPartyTypeKind.ZodAny:return et();case m.ZodFirstPartyTypeKind.ZodUnknown:return kt();case m.ZodFirstPartyTypeKind.ZodDefault:return at(n,t);case m.ZodFirstPartyTypeKind.ZodBranded:return ne(n,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return Et(n,t);case m.ZodFirstPartyTypeKind.ZodCatch:return st(n,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Rt(n,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==We)return i}if(r&&!t){let i=Ir(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=At(n,n.typeName,e),a=typeof c=="function"?u(c(),e):c;if(a&&Mr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Ir=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Nr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Nr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Mr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Se=(n,e)=>{let t=Qe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[h,f])=>({...l,[h]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=u(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var O=require("zod");var jt=require("zod"),Re;(function(n){n.Completable="McpCompletable"})(Re||(Re={}));var j=class extends jt.ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Re.Completable,complete:e.complete,...Or(e)});function Or(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,h;let{message:f}=n;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(l=f??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(h=f??t)!==null&&h!==void 0?h:i.defaultError}},description:s}}var ie=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Se(t.inputSchema,{strictUnions:!0}):Lr}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new b(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new b(g.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new b(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ae;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ae;let a=await s._def.complete(e.params.argument.value);return It(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ae;throw new b(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ae;let c=await s(e.params.argument.value);return It(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new b(g.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Dr(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new b(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=O.z.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=O.z.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Lr={type:"object"};function Dr(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function It(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ae={completion:{values:[],hasMore:!1}};var Pe=Ut(require("process"),1);var ce=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
6
- `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),qr(t)}clear(){this._buffer=void 0}};function qr(n){return Ze.parse(JSON.parse(n))}function Nt(n){return JSON.stringify(n)+`
7
- `}var le=class{constructor(e=Pe.default.stdin,t=Pe.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ce,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=Nt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};var we=require("zod");var Te=process.env.personalToken||""||"";function Mt(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var Ot=new ie({name:"F2C MCP",version:"0.0.1"});k("notification",{message:"MCP server instance created"});Ot.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:we.z.string().default(Te).describe("Your Figma personal access token"),figmaUrl:we.z.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{k("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=Mt(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return k("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Lt(){k("notification",{message:"Starting Figma-to-HTML service"});let n=new le;k("notification",{message:"Transport layer initialized"}),await Ot.connect(n),k("notification",{message:"MCP server connected to stdio"})}Lt().catch(n=>{k("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
5
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}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`),n.source}return s}function ae(n,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"&&n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=se(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodBranded&&n.keyType._def.type._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function ht(n,e){if(e.mapStrategy==="record")return ae(n,e);let t=u(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function ft(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function gt(){return{not:{}}}function bt(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var N={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _t(n,e){if(e.target==="openApi3")return yt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in N&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=N[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return yt(n,e)}var yt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>u(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function xt(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:N[n.innerType._def.typeName],nullable:!0}:{type:[N[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function vt(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",xe(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}var St=require("zod");function Rt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let h=Mr(l);h&&t&&(l instanceof St.ZodOptional&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),h=!1);let f=u(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,h||s.push(i))}s.length&&(r.required=s);let a=Ir(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Ir(n,e){if(n.catchall._def.typeName!=="ZodNever")return u(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mr(n){try{return n.isOptional()}catch{return!0}}var Pt=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(n.innerType._def,e);let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Tt=(n,e)=>{if(e.pipeStrategy==="input")return u(n.in._def,e);if(e.pipeStrategy==="output")return u(n.out._def,e);let t=u(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function wt(n,e){return u(n.type._def,e)}function Ct(n,e){let r={type:"array",uniqueItems:!0,items:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&d(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&d(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function Et(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function kt(){return{not:{}}}function At(){return{}}var jt=(n,e)=>u(n.innerType._def,e);var It=(n,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return se(n,t);case m.ZodFirstPartyTypeKind.ZodNumber:return vt(n,t);case m.ZodFirstPartyTypeKind.ZodObject:return Rt(n,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return st(n,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return at();case m.ZodFirstPartyTypeKind.ZodDate:return ve(n,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return kt();case m.ZodFirstPartyTypeKind.ZodNull:return bt(t);case m.ZodFirstPartyTypeKind.ZodArray:return ot(n,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return _t(n,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return ut(n,t);case m.ZodFirstPartyTypeKind.ZodTuple:return Et(n,t);case m.ZodFirstPartyTypeKind.ZodRecord:return ae(n,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return mt(n,t);case m.ZodFirstPartyTypeKind.ZodEnum:return pt(n);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return ft(n);case m.ZodFirstPartyTypeKind.ZodNullable:return xt(n,t);case m.ZodFirstPartyTypeKind.ZodOptional:return Pt(n,t);case m.ZodFirstPartyTypeKind.ZodMap:return ht(n,t);case m.ZodFirstPartyTypeKind.ZodSet:return Ct(n,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>n.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return wt(n,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return gt();case m.ZodFirstPartyTypeKind.ZodEffects:return lt(n,t);case m.ZodFirstPartyTypeKind.ZodAny:return rt();case m.ZodFirstPartyTypeKind.ZodUnknown:return At();case m.ZodFirstPartyTypeKind.ZodDefault:return ct(n,t);case m.ZodFirstPartyTypeKind.ZodBranded:return oe(n,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return jt(n,t);case m.ZodFirstPartyTypeKind.ZodCatch:return it(n,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Tt(n,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==Qe)return i}if(r&&!t){let i=Nr(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=It(n,n.typeName,e),a=typeof c=="function"?u(c(),e):c;if(a&&Lr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Nr=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Or(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Or=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Lr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Pe=(n,e)=>{let t=tt(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[h,f])=>({...l,[h]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=u(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var O=require("zod");var Mt=require("zod"),Te;(function(n){n.Completable="McpCompletable"})(Te||(Te={}));var j=class extends Mt.ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Te.Completable,complete:e.complete,...Dr(e)});function Dr(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,h;let{message:f}=n;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(l=f??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(h=f??t)!==null&&h!==void 0?h:i.defaultError}},description:s}}var ce=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ne(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Q,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Pe(t.inputSchema,{strictUnions:!0}):$r}))})),this.server.setRequestHandler(ee,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new b(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.setRequestHandler(te,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new b(g.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new b(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ie;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ie;let a=await s._def.complete(e.params.argument.value);return Nt(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ie;throw new b(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ie;let c=await s(e.params.argument.value);return Nt(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(J,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(B,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new b(g.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(G,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?qr(t.argsSchema):void 0}))})),this.server.setRequestHandler(K,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new b(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=O.z.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=O.z.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var $r={type:"object"};function qr(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Nt(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ie={completion:{values:[],hasMore:!1}};var we=Jt(require("process"),1);var le=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
6
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Hr(t)}clear(){this._buffer=void 0}};function Hr(n){return Fe.parse(JSON.parse(n))}function Ot(n){return JSON.stringify(n)+`
7
+ `}var pe=class{constructor(e=we.default.stdin,t=we.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new le,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=Ot(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};var L=require("zod");var Ce=process.env.personalToken||""||"";function Lt(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}function Dt(n){return n?n.length>214?{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u8D85\u8FC7214\u4E2A\u5B57\u7B26"}:/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(n)?n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico"?{isValid:!1,message:"\u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\u4F5C\u4E3A\u9879\u76EE\u540D"}:{isValid:!0}:{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001-\u3001.\u3001~\uFF0C\u5982\u679C\u4F7F\u7528 scope \u5219\u9700\u8981\u4EE5 @ \u5F00\u5934"}:{isValid:!1,message:"\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"}}var ue=new ce({name:"F2C MCP",version:"0.0.1"});_("notification",{message:"MCP server instance created"});ue.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:L.z.string().default(Ce).describe("Your Figma personal access token"),figmaUrl:L.z.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Ce,figmaUrl:e})=>{_("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=Lt(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return _("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});ue.tool("\u521B\u5EFA\u6216\u65B0\u589EAstro\u7EC4\u4EF6","\u521B\u5EFA\u6216\u65B0\u589EAstro\u7EC4\u4EF6\u901A\u8FC7\u7EC4\u4EF6\u540D\u5B57",{componentName:L.z.string().regex(/^[A-Z][a-zA-Z0-9_]*$/,{message:"\u7EC4\u4EF6\u540D\u79F0\u5FC5\u987B\u4EE5\u5927\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u4E14\u53EA\u80FD\u5305\u542B\u82F1\u6587\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF"}).describe("\u7EC4\u4EF6\u7684\u540D\u5B57")},async({componentName:n})=>{_("notification",{message:"Creating Astro component",params:{componentName:n}});try{if(!n.match(/^[A-Z][a-zA-Z0-9_]*$/))throw new Error("\u7EC4\u4EF6\u540D\u79F0\u5FC5\u987B\u4EE5\u5927\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u4E14\u53EA\u80FD\u5305\u542B\u82F1\u6587\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF");try{return(0,Ee.execSync)(`npx --registry=https://npm-registry.yy.com @astro/create-astro new component ${n}`,{stdio:"pipe"}),{content:[{type:"text",text:`\u6210\u529F\u521B\u5EFA Astro \u7EC4\u4EF6: ${n} --registry=https://npm-registry.yy.com`}]}}catch(e){throw new Error(`\u521B\u5EFA\u7EC4\u4EF6\u5931\u8D25: ${e.message}
8
+ \u8BF7\u786E\u4FDD\u60A8\u5728YY\u5185\u7F51\u73AF\u5883\u4E0B\u6267\u884C\u6B64\u64CD\u4F5C`)}}catch(e){return _("error",{message:`Error: ${e.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${e.message}`}]}}});ue.tool("\u521B\u5EFAAstro\u9879\u76EE","\u901A\u8FC7\u9879\u76EE\u540D\u79F0\u521B\u5EFA\u65B0\u7684Astro\u9879\u76EE",{projectName:L.z.string().describe("\u9879\u76EE\u7684\u540D\u79F0")},async({projectName:n})=>{_("notification",{message:"Creating Astro project",params:{projectName:n}});try{let e=Dt(n);if(!e.isValid)throw new Error(e.message);try{return(0,Ee.execSync)(`npx --registry=https://npm-registry.yy.com @astro/create-astro new project --name ${n}`,{stdio:"pipe"}),{content:[{type:"text",text:`\u6210\u529F\u521B\u5EFA Astro \u9879\u76EE: ${n}`}]}}catch(t){throw new Error(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t.message}
9
+ \u8BF7\u786E\u4FDD\u60A8\u5728YY\u5185\u7F51\u73AF\u5883\u4E0B\u6267\u884C\u6B64\u64CD\u4F5C`)}}catch(e){return _("error",{message:`Error: ${e.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${e.message}`}]}}});async function $t(){_("notification",{message:"Starting Figma-to-HTML service"});let n=new pe;_("notification",{message:"Transport layer initialized"}),await ue.connect(n),_("notification",{message:"MCP server connected to stdio"})}$t().catch(n=>{_("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});