@f2c/mcp 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/cli.mjs +2 -2
- package/dist/stdio.js +2 -2
- package/dist/stdio.mjs +2 -2
- package/dist/streamableHttp.js +3 -3
- package/dist/streamableHttp.mjs +3 -3
- package/package.json +1 -1
package/dist/cli.js
CHANGED
@@ -1,8 +1,8 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
"use strict";var Ft=Object.create;var Ae=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var Jt=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ut(e))!Gt.call(o,s)&&s!==t&&Ae(o,s,{get:()=>e[s],enumerable:!(r=zt(e,s))||r.enumerable});return o};var Bt=(o,e,t)=>(t=o!=null?Ft(Vt(o)):{},Jt(e||!o||!o.__esModule?Ae(t,"default",{value:o,enumerable:!0}):t,o));function Ne(o,e){let t={jsonrpc:"2.0",...o==="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 n=require("zod"),fe="2025-03-26",Ie=[fe,"2024-11-05","2024-10-07"],$="2.0",Oe=n.z.union([n.z.string(),n.z.number().int()]),Me=n.z.string(),Kt=n.z.object({progressToken:n.z.optional(Oe)}).passthrough(),R=n.z.object({_meta:n.z.optional(Kt)}).passthrough(),v=n.z.object({method:n.z.string(),params:n.z.optional(R)}),L=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),k=n.z.object({method:n.z.string(),params:n.z.optional(L)}),P=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),q=n.z.union([n.z.string(),n.z.number().int()]),Le=n.z.object({jsonrpc:n.z.literal($),id:q}).merge(v).strict(),De=o=>Le.safeParse(o).success,He=n.z.object({jsonrpc:n.z.literal($)}).merge(k).strict(),$e=o=>He.safeParse(o).success,qe=n.z.object({jsonrpc:n.z.literal($),id:q,result:P}).strict(),he=o=>qe.safeParse(o).success,g;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(g||(g={}));var Ze=n.z.object({jsonrpc:n.z.literal($),id:q,error:n.z.object({code:n.z.number().int(),message:n.z.string(),data:n.z.optional(n.z.unknown())})}).strict(),Fe=o=>Ze.safeParse(o).success,ze=n.z.union([Le,He,qe,Ze]),Z=P.strict(),F=k.extend({method:n.z.literal("notifications/cancelled"),params:L.extend({requestId:q,reason:n.z.string().optional()})}),Ue=n.z.object({name:n.z.string(),version:n.z.string()}).passthrough(),Xt=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),sampling:n.z.optional(n.z.object({}).passthrough()),roots:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),ge=v.extend({method:n.z.literal("initialize"),params:R.extend({protocolVersion:n.z.string(),capabilities:Xt,clientInfo:Ue})});var Wt=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),logging:n.z.optional(n.z.object({}).passthrough()),completions:n.z.optional(n.z.object({}).passthrough()),prompts:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough()),resources:n.z.optional(n.z.object({subscribe:n.z.optional(n.z.boolean()),listChanged:n.z.optional(n.z.boolean())}).passthrough()),tools:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),Yt=P.extend({protocolVersion:n.z.string(),capabilities:Wt,serverInfo:Ue,instructions:n.z.optional(n.z.string())}),be=k.extend({method:n.z.literal("notifications/initialized")});var z=v.extend({method:n.z.literal("ping")}),Qt=n.z.object({progress:n.z.number(),total:n.z.optional(n.z.number())}).passthrough(),U=k.extend({method:n.z.literal("notifications/progress"),params:L.merge(Qt).extend({progressToken:Oe})}),V=v.extend({params:R.extend({cursor:n.z.optional(Me)}).optional()}),G=P.extend({nextCursor:n.z.optional(Me)}),Ve=n.z.object({uri:n.z.string(),mimeType:n.z.optional(n.z.string())}).passthrough(),Ge=Ve.extend({text:n.z.string()}),Je=Ve.extend({blob:n.z.string().base64()}),er=n.z.object({uri:n.z.string(),name:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string())}).passthrough(),tr=n.z.object({uriTemplate:n.z.string(),name:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string())}).passthrough(),J=V.extend({method:n.z.literal("resources/list")}),rr=G.extend({resources:n.z.array(er)}),B=V.extend({method:n.z.literal("resources/templates/list")}),or=G.extend({resourceTemplates:n.z.array(tr)}),K=v.extend({method:n.z.literal("resources/read"),params:R.extend({uri:n.z.string()})}),nr=P.extend({contents:n.z.array(n.z.union([Ge,Je]))}),sr=k.extend({method:n.z.literal("notifications/resources/list_changed")}),ar=v.extend({method:n.z.literal("resources/subscribe"),params:R.extend({uri:n.z.string()})}),ir=v.extend({method:n.z.literal("resources/unsubscribe"),params:R.extend({uri:n.z.string()})}),lr=k.extend({method:n.z.literal("notifications/resources/updated"),params:L.extend({uri:n.z.string()})}),cr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),required:n.z.optional(n.z.boolean())}).passthrough(),pr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),arguments:n.z.optional(n.z.array(cr))}).passthrough(),X=V.extend({method:n.z.literal("prompts/list")}),ur=G.extend({prompts:n.z.array(pr)}),W=v.extend({method:n.z.literal("prompts/get"),params:R.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.string()))})}),Y=n.z.object({type:n.z.literal("text"),text:n.z.string()}).passthrough(),Q=n.z.object({type:n.z.literal("image"),data:n.z.string().base64(),mimeType:n.z.string()}).passthrough(),ee=n.z.object({type:n.z.literal("audio"),data:n.z.string().base64(),mimeType:n.z.string()}).passthrough(),Be=n.z.object({type:n.z.literal("resource"),resource:n.z.union([Ge,Je])}).passthrough(),mr=n.z.object({role:n.z.enum(["user","assistant"]),content:n.z.union([Y,Q,ee,Be])}).passthrough(),dr=P.extend({description:n.z.optional(n.z.string()),messages:n.z.array(mr)}),fr=k.extend({method:n.z.literal("notifications/prompts/list_changed")}),hr=n.z.object({title:n.z.optional(n.z.string()),readOnlyHint:n.z.optional(n.z.boolean()),destructiveHint:n.z.optional(n.z.boolean()),idempotentHint:n.z.optional(n.z.boolean()),openWorldHint:n.z.optional(n.z.boolean())}).passthrough(),gr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),inputSchema:n.z.object({type:n.z.literal("object"),properties:n.z.optional(n.z.object({}).passthrough())}).passthrough(),annotations:n.z.optional(hr)}).passthrough(),te=V.extend({method:n.z.literal("tools/list")}),br=G.extend({tools:n.z.array(gr)}),Ke=P.extend({content:n.z.array(n.z.union([Y,Q,ee,Be])),isError:n.z.boolean().default(!1).optional()}),Kr=Ke.or(P.extend({toolResult:n.z.unknown()})),re=v.extend({method:n.z.literal("tools/call"),params:R.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.unknown()))})}),yr=k.extend({method:n.z.literal("notifications/tools/list_changed")}),Xe=n.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),_r=v.extend({method:n.z.literal("logging/setLevel"),params:R.extend({level:Xe})}),xr=k.extend({method:n.z.literal("notifications/message"),params:L.extend({level:Xe,logger:n.z.optional(n.z.string()),data:n.z.unknown()})}),vr=n.z.object({name:n.z.string().optional()}).passthrough(),Sr=n.z.object({hints:n.z.optional(n.z.array(vr)),costPriority:n.z.optional(n.z.number().min(0).max(1)),speedPriority:n.z.optional(n.z.number().min(0).max(1)),intelligencePriority:n.z.optional(n.z.number().min(0).max(1))}).passthrough(),Rr=n.z.object({role:n.z.enum(["user","assistant"]),content:n.z.union([Y,Q,ee])}).passthrough(),Pr=v.extend({method:n.z.literal("sampling/createMessage"),params:R.extend({messages:n.z.array(Rr),systemPrompt:n.z.optional(n.z.string()),includeContext:n.z.optional(n.z.enum(["none","thisServer","allServers"])),temperature:n.z.optional(n.z.number()),maxTokens:n.z.number().int(),stopSequences:n.z.optional(n.z.array(n.z.string())),metadata:n.z.optional(n.z.object({}).passthrough()),modelPreferences:n.z.optional(Sr)})}),ye=P.extend({model:n.z.string(),stopReason:n.z.optional(n.z.enum(["endTurn","stopSequence","maxTokens"]).or(n.z.string())),role:n.z.enum(["user","assistant"]),content:n.z.discriminatedUnion("type",[Y,Q,ee])}),Tr=n.z.object({type:n.z.literal("ref/resource"),uri:n.z.string()}).passthrough(),wr=n.z.object({type:n.z.literal("ref/prompt"),name:n.z.string()}).passthrough(),oe=v.extend({method:n.z.literal("completion/complete"),params:R.extend({ref:n.z.union([wr,Tr]),argument:n.z.object({name:n.z.string(),value:n.z.string()}).passthrough()})}),Cr=P.extend({completion:n.z.object({values:n.z.array(n.z.string()).max(100),total:n.z.optional(n.z.number().int()),hasMore:n.z.optional(n.z.boolean())}).passthrough()}),kr=n.z.object({uri:n.z.string().startsWith("file://"),name:n.z.optional(n.z.string())}).passthrough(),Er=v.extend({method:n.z.literal("roots/list")}),_e=P.extend({roots:n.z.array(kr)}),jr=k.extend({method:n.z.literal("notifications/roots/list_changed")}),Xr=n.z.union([z,ge,oe,_r,W,X,J,B,K,ar,ir,re,te]),Wr=n.z.union([F,U,be,jr]),Yr=n.z.union([Z,ye,_e]),Qr=n.z.union([z,Pr,Er]),eo=n.z.union([F,U,xr,lr,sr,yr,fr]),to=n.z.union([Z,Yt,Cr,dr,ur,rr,or,nr,Ke,br]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Ar=6e4,ne=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(F,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,s,l=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:l,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)=>{he(t)||Fe(t)?this._onresponse(t):De(t)?this._onrequest(t,r):$e(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,l,a;let i=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(i===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(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let y={signal:c.signal,sessionId:(l=this._transport)===null||l===void 0?void 0:l.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,x,E)=>this.request(f,x,{...E,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>i(e,y)).then(f=>{var x;if(!c.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var x,E;if(!c.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:g.InternalError,message:(E=f.message)!==null&&E!==void 0?E:"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),l=this._progressHandlers.get(s);if(!l){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(c){a(c);return}l(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 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:l,onresumptiontoken:a}=r??{};return new Promise((i,c)=>{var y,f,x,E,de;if(!this._transport){c(new Error("Not connected"));return}((y=this._options)===null||y===void 0?void 0:y.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let C=this._requestMessageId++,ke={...e,jsonrpc:"2.0",id:C};r?.onprogress&&(this._progressHandlers.set(C,r.onprogress),ke.params={...e.params,_meta:{progressToken:C}});let Ee=S=>{var j;this._responseHandlers.delete(C),this._progressHandlers.delete(C),this._cleanupTimeout(C),(j=this._transport)===null||j===void 0||j.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:C,reason:String(S)}},{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`))),c(S)};this._responseHandlers.set(C,S=>{var j;if(!(!((j=r?.signal)===null||j===void 0)&&j.aborted)){if(S instanceof Error)return c(S);try{let M=t.parse(S.result);i(M)}catch(M){c(M)}}}),(x=r?.signal)===null||x===void 0||x.addEventListener("abort",()=>{var S;Ee((S=r?.signal)===null||S===void 0?void 0:S.reason)});let je=(E=r?.timeout)!==null&&E!==void 0?E:Ar,Zt=()=>Ee(new b(g.RequestTimeout,"Request timed out",{timeout:je}));this._setupTimeout(C,je,r?.maxTotalTimeout,Zt,(de=r?.resetTimeoutOnProgress)!==null&&de!==void 0?de:!1),this._transport.send(ke,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(S=>{this._cleanupTimeout(C),c(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,l)=>Promise.resolve(t(e.parse(s),l)))}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 We(o,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),{...o})}var se=class extends ne{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=We(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:Ie.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"},Z)}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 Ye={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=o=>typeof o=="string"?{...Ye,name:o}:{...Ye,...o};var tt=o=>{let e=et(o),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(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function d(o,e,t,r,s){o[e]=t,xe(o,e,r,s)}var m=require("zod");function rt(){return{}}var ot=require("zod");function nt(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==ot.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&d(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&d(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(d(t,"minItems",o.exactLength.value,o.exactLength.message,e),d(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function st(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.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 ae(o,e){return u(o.type._def,e)}var it=(o,e)=>u(o.innerType._def,e);function ve(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,l)=>ve(o,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 Nr(o,e)}}var Nr=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.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 lt(o,e){return{...u(o.innerType._def,e),default:o.defaultValue()}}function ct(o,e){return e.effectStrategy==="input"?u(o.schema._def,e):{}}function pt(o){return{type:"string",enum:Array.from(o.values)}}var Ir=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ut(o,e){let t=[u(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(l=>!!l),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(l=>{if(Ir(l))s.push(...l.allOf),l.unevaluatedProperties===void 0&&(r=void 0);else{let a=l;if("additionalProperties"in l&&l.additionalProperties===!1){let{additionalProperties:i,...c}=l;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function mt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}var N=require("zod");var Se,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:()=>(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 ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.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":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(`^${Re(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Re(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":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":{_(t,RegExp(Re(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":{d(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 Re(o,e){return e.patternStrategy==="escape"?Mr(o):o}var Or=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mr(o){let e="";for(let t=0;t<o.length;t++)Or.has(o[t])||(e+="\\"),e+=o[t];return e}function w(o,e,t,r){o.format||o.anyOf?.some(s=>s.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(o,"format",e,t,r)}function _(o,e,t,r){o.pattern||o.allOf?.some(s=>s.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:dt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(o,"pattern",dt(e,r),t,r)}function dt(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,s="",l=!1,a=!1,i=!1;for(let c=0;c<r.length;c++){if(l){s+=r[c],l=!1;continue}if(t.i){if(a){if(r[c].match(/[a-z]/)){i?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),i=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],i=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(t.m){if(r[c]==="^"){s+=`(^|(?<=[\r
|
2
|
+
"use strict";var Ft=Object.create;var Ae=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Gt=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ut(e))!Jt.call(o,s)&&s!==t&&Ae(o,s,{get:()=>e[s],enumerable:!(r=zt(e,s))||r.enumerable});return o};var Bt=(o,e,t)=>(t=o!=null?Ft(Vt(o)):{},Gt(e||!o||!o.__esModule?Ae(t,"default",{value:o,enumerable:!0}):t,o));function Ne(o,e){let t={jsonrpc:"2.0",...o==="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 n=require("zod"),fe="2025-03-26",Oe=[fe,"2024-11-05","2024-10-07"],$="2.0",Ie=n.z.union([n.z.string(),n.z.number().int()]),Me=n.z.string(),Kt=n.z.object({progressToken:n.z.optional(Ie)}).passthrough(),R=n.z.object({_meta:n.z.optional(Kt)}).passthrough(),v=n.z.object({method:n.z.string(),params:n.z.optional(R)}),L=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),k=n.z.object({method:n.z.string(),params:n.z.optional(L)}),P=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),q=n.z.union([n.z.string(),n.z.number().int()]),Le=n.z.object({jsonrpc:n.z.literal($),id:q}).merge(v).strict(),De=o=>Le.safeParse(o).success,He=n.z.object({jsonrpc:n.z.literal($)}).merge(k).strict(),$e=o=>He.safeParse(o).success,qe=n.z.object({jsonrpc:n.z.literal($),id:q,result:P}).strict(),he=o=>qe.safeParse(o).success,g;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(g||(g={}));var Ze=n.z.object({jsonrpc:n.z.literal($),id:q,error:n.z.object({code:n.z.number().int(),message:n.z.string(),data:n.z.optional(n.z.unknown())})}).strict(),Fe=o=>Ze.safeParse(o).success,ze=n.z.union([Le,He,qe,Ze]),Z=P.strict(),F=k.extend({method:n.z.literal("notifications/cancelled"),params:L.extend({requestId:q,reason:n.z.string().optional()})}),Ue=n.z.object({name:n.z.string(),version:n.z.string()}).passthrough(),Xt=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),sampling:n.z.optional(n.z.object({}).passthrough()),roots:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),ge=v.extend({method:n.z.literal("initialize"),params:R.extend({protocolVersion:n.z.string(),capabilities:Xt,clientInfo:Ue})});var Wt=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),logging:n.z.optional(n.z.object({}).passthrough()),completions:n.z.optional(n.z.object({}).passthrough()),prompts:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough()),resources:n.z.optional(n.z.object({subscribe:n.z.optional(n.z.boolean()),listChanged:n.z.optional(n.z.boolean())}).passthrough()),tools:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),Yt=P.extend({protocolVersion:n.z.string(),capabilities:Wt,serverInfo:Ue,instructions:n.z.optional(n.z.string())}),be=k.extend({method:n.z.literal("notifications/initialized")});var z=v.extend({method:n.z.literal("ping")}),Qt=n.z.object({progress:n.z.number(),total:n.z.optional(n.z.number())}).passthrough(),U=k.extend({method:n.z.literal("notifications/progress"),params:L.merge(Qt).extend({progressToken:Ie})}),V=v.extend({params:R.extend({cursor:n.z.optional(Me)}).optional()}),J=P.extend({nextCursor:n.z.optional(Me)}),Ve=n.z.object({uri:n.z.string(),mimeType:n.z.optional(n.z.string())}).passthrough(),Je=Ve.extend({text:n.z.string()}),Ge=Ve.extend({blob:n.z.string().base64()}),er=n.z.object({uri:n.z.string(),name:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string())}).passthrough(),tr=n.z.object({uriTemplate:n.z.string(),name:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string())}).passthrough(),G=V.extend({method:n.z.literal("resources/list")}),rr=J.extend({resources:n.z.array(er)}),B=V.extend({method:n.z.literal("resources/templates/list")}),or=J.extend({resourceTemplates:n.z.array(tr)}),K=v.extend({method:n.z.literal("resources/read"),params:R.extend({uri:n.z.string()})}),nr=P.extend({contents:n.z.array(n.z.union([Je,Ge]))}),sr=k.extend({method:n.z.literal("notifications/resources/list_changed")}),ar=v.extend({method:n.z.literal("resources/subscribe"),params:R.extend({uri:n.z.string()})}),ir=v.extend({method:n.z.literal("resources/unsubscribe"),params:R.extend({uri:n.z.string()})}),lr=k.extend({method:n.z.literal("notifications/resources/updated"),params:L.extend({uri:n.z.string()})}),cr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),required:n.z.optional(n.z.boolean())}).passthrough(),pr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),arguments:n.z.optional(n.z.array(cr))}).passthrough(),X=V.extend({method:n.z.literal("prompts/list")}),ur=J.extend({prompts:n.z.array(pr)}),W=v.extend({method:n.z.literal("prompts/get"),params:R.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.string()))})}),Y=n.z.object({type:n.z.literal("text"),text:n.z.string()}).passthrough(),Q=n.z.object({type:n.z.literal("image"),data:n.z.string().base64(),mimeType:n.z.string()}).passthrough(),ee=n.z.object({type:n.z.literal("audio"),data:n.z.string().base64(),mimeType:n.z.string()}).passthrough(),Be=n.z.object({type:n.z.literal("resource"),resource:n.z.union([Je,Ge])}).passthrough(),mr=n.z.object({role:n.z.enum(["user","assistant"]),content:n.z.union([Y,Q,ee,Be])}).passthrough(),dr=P.extend({description:n.z.optional(n.z.string()),messages:n.z.array(mr)}),fr=k.extend({method:n.z.literal("notifications/prompts/list_changed")}),hr=n.z.object({title:n.z.optional(n.z.string()),readOnlyHint:n.z.optional(n.z.boolean()),destructiveHint:n.z.optional(n.z.boolean()),idempotentHint:n.z.optional(n.z.boolean()),openWorldHint:n.z.optional(n.z.boolean())}).passthrough(),gr=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),inputSchema:n.z.object({type:n.z.literal("object"),properties:n.z.optional(n.z.object({}).passthrough())}).passthrough(),annotations:n.z.optional(hr)}).passthrough(),te=V.extend({method:n.z.literal("tools/list")}),br=J.extend({tools:n.z.array(gr)}),Ke=P.extend({content:n.z.array(n.z.union([Y,Q,ee,Be])),isError:n.z.boolean().default(!1).optional()}),Kr=Ke.or(P.extend({toolResult:n.z.unknown()})),re=v.extend({method:n.z.literal("tools/call"),params:R.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.unknown()))})}),yr=k.extend({method:n.z.literal("notifications/tools/list_changed")}),Xe=n.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),_r=v.extend({method:n.z.literal("logging/setLevel"),params:R.extend({level:Xe})}),xr=k.extend({method:n.z.literal("notifications/message"),params:L.extend({level:Xe,logger:n.z.optional(n.z.string()),data:n.z.unknown()})}),vr=n.z.object({name:n.z.string().optional()}).passthrough(),Sr=n.z.object({hints:n.z.optional(n.z.array(vr)),costPriority:n.z.optional(n.z.number().min(0).max(1)),speedPriority:n.z.optional(n.z.number().min(0).max(1)),intelligencePriority:n.z.optional(n.z.number().min(0).max(1))}).passthrough(),Rr=n.z.object({role:n.z.enum(["user","assistant"]),content:n.z.union([Y,Q,ee])}).passthrough(),Pr=v.extend({method:n.z.literal("sampling/createMessage"),params:R.extend({messages:n.z.array(Rr),systemPrompt:n.z.optional(n.z.string()),includeContext:n.z.optional(n.z.enum(["none","thisServer","allServers"])),temperature:n.z.optional(n.z.number()),maxTokens:n.z.number().int(),stopSequences:n.z.optional(n.z.array(n.z.string())),metadata:n.z.optional(n.z.object({}).passthrough()),modelPreferences:n.z.optional(Sr)})}),ye=P.extend({model:n.z.string(),stopReason:n.z.optional(n.z.enum(["endTurn","stopSequence","maxTokens"]).or(n.z.string())),role:n.z.enum(["user","assistant"]),content:n.z.discriminatedUnion("type",[Y,Q,ee])}),Tr=n.z.object({type:n.z.literal("ref/resource"),uri:n.z.string()}).passthrough(),wr=n.z.object({type:n.z.literal("ref/prompt"),name:n.z.string()}).passthrough(),oe=v.extend({method:n.z.literal("completion/complete"),params:R.extend({ref:n.z.union([wr,Tr]),argument:n.z.object({name:n.z.string(),value:n.z.string()}).passthrough()})}),Cr=P.extend({completion:n.z.object({values:n.z.array(n.z.string()).max(100),total:n.z.optional(n.z.number().int()),hasMore:n.z.optional(n.z.boolean())}).passthrough()}),kr=n.z.object({uri:n.z.string().startsWith("file://"),name:n.z.optional(n.z.string())}).passthrough(),Er=v.extend({method:n.z.literal("roots/list")}),_e=P.extend({roots:n.z.array(kr)}),jr=k.extend({method:n.z.literal("notifications/roots/list_changed")}),Xr=n.z.union([z,ge,oe,_r,W,X,G,B,K,ar,ir,re,te]),Wr=n.z.union([F,U,be,jr]),Yr=n.z.union([Z,ye,_e]),Qr=n.z.union([z,Pr,Er]),eo=n.z.union([F,U,xr,lr,sr,yr,fr]),to=n.z.union([Z,Yt,Cr,dr,ur,rr,or,nr,Ke,br]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Ar=6e4,ne=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(F,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,s,l=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:l,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)=>{he(t)||Fe(t)?this._onresponse(t):De(t)?this._onrequest(t,r):$e(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,l,a;let i=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(i===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(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let y={signal:c.signal,sessionId:(l=this._transport)===null||l===void 0?void 0:l.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,x,E)=>this.request(f,x,{...E,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>i(e,y)).then(f=>{var x;if(!c.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var x,E;if(!c.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:g.InternalError,message:(E=f.message)!==null&&E!==void 0?E:"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),l=this._progressHandlers.get(s);if(!l){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(c){a(c);return}l(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 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:l,onresumptiontoken:a}=r??{};return new Promise((i,c)=>{var y,f,x,E,de;if(!this._transport){c(new Error("Not connected"));return}((y=this._options)===null||y===void 0?void 0:y.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let C=this._requestMessageId++,ke={...e,jsonrpc:"2.0",id:C};r?.onprogress&&(this._progressHandlers.set(C,r.onprogress),ke.params={...e.params,_meta:{progressToken:C}});let Ee=S=>{var j;this._responseHandlers.delete(C),this._progressHandlers.delete(C),this._cleanupTimeout(C),(j=this._transport)===null||j===void 0||j.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:C,reason:String(S)}},{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`))),c(S)};this._responseHandlers.set(C,S=>{var j;if(!(!((j=r?.signal)===null||j===void 0)&&j.aborted)){if(S instanceof Error)return c(S);try{let M=t.parse(S.result);i(M)}catch(M){c(M)}}}),(x=r?.signal)===null||x===void 0||x.addEventListener("abort",()=>{var S;Ee((S=r?.signal)===null||S===void 0?void 0:S.reason)});let je=(E=r?.timeout)!==null&&E!==void 0?E:Ar,Zt=()=>Ee(new b(g.RequestTimeout,"Request timed out",{timeout:je}));this._setupTimeout(C,je,r?.maxTotalTimeout,Zt,(de=r?.resetTimeoutOnProgress)!==null&&de!==void 0?de:!1),this._transport.send(ke,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(S=>{this._cleanupTimeout(C),c(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,l)=>Promise.resolve(t(e.parse(s),l)))}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 We(o,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),{...o})}var se=class extends ne{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=We(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:Oe.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"},Z)}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 Ye={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=o=>typeof o=="string"?{...Ye,name:o}:{...Ye,...o};var tt=o=>{let e=et(o),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(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function d(o,e,t,r,s){o[e]=t,xe(o,e,r,s)}var m=require("zod");function rt(){return{}}var ot=require("zod");function nt(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==ot.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&d(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&d(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(d(t,"minItems",o.exactLength.value,o.exactLength.message,e),d(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function st(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.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 ae(o,e){return u(o.type._def,e)}var it=(o,e)=>u(o.innerType._def,e);function ve(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,l)=>ve(o,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 Nr(o,e)}}var Nr=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.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 lt(o,e){return{...u(o.innerType._def,e),default:o.defaultValue()}}function ct(o,e){return e.effectStrategy==="input"?u(o.schema._def,e):{}}function pt(o){return{type:"string",enum:Array.from(o.values)}}var Or=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ut(o,e){let t=[u(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(l=>!!l),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(l=>{if(Or(l))s.push(...l.allOf),l.unevaluatedProperties===void 0&&(r=void 0);else{let a=l;if("additionalProperties"in l&&l.additionalProperties===!1){let{additionalProperties:i,...c}=l;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function mt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}var N=require("zod");var Se,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:()=>(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 ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.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":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(`^${Re(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Re(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":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":{_(t,RegExp(Re(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":{d(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 Re(o,e){return e.patternStrategy==="escape"?Mr(o):o}var Ir=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mr(o){let e="";for(let t=0;t<o.length;t++)Ir.has(o[t])||(e+="\\"),e+=o[t];return e}function w(o,e,t,r){o.format||o.anyOf?.some(s=>s.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(o,"format",e,t,r)}function _(o,e,t,r){o.pattern||o.allOf?.some(s=>s.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:dt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(o,"pattern",dt(e,r),t,r)}function dt(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,s="",l=!1,a=!1,i=!1;for(let c=0;c<r.length;c++){if(l){s+=r[c],l=!1;continue}if(t.i){if(a){if(r[c].match(/[a-z]/)){i?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),i=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],i=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(t.m){if(r[c]==="^"){s+=`(^|(?<=[\r
|
3
3
|
]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
|
4
4
|
]))`;continue}}if(t.s&&r[c]==="."){s+=a?`${r[c]}\r
|
5
5
|
`:`[${r[c]}\r
|
6
|
-
]`;continue}s+=r[c],r[c]==="\\"?l=!0:a&&r[c]==="]"?a=!1:!a&&r[c]==="["&&(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`),o.source}return s}function le(o,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"&&o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,s)=>({...r,[s]:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodString&&o.keyType._def.checks?.length){let{type:r,...s}=ie(o.keyType._def,e);return{...t,propertyNames:s}}else{if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodBranded&&o.keyType._def.type._def.typeName===N.ZodFirstPartyTypeKind.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...s}=ae(o.keyType._def,e);return{...t,propertyNames:s}}}return t}function ft(o,e){if(e.mapStrategy==="record")return le(o,e);let t=u(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(o.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 ht(o){let e=o.values,r=Object.keys(o.values).filter(l=>typeof e[e[l]]!="number").map(l=>e[l]),s=Array.from(new Set(r.map(l=>typeof l)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function gt(){return{not:{}}}function bt(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _t(o,e){if(e.target==="openApi3")return yt(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in D&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,l)=>{let a=D[l._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,l)=>{let a=typeof l._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(l._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((l,a,i)=>i.indexOf(l)===a);return{type:s.length>1?s:s[0],enum:t.reduce((l,a)=>l.includes(a._def.value)?l:[...l,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(l=>!r.includes(l))],[])};return yt(o,e)}var yt=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.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(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:D[o.innerType._def.typeName],nullable:!0}:{type:[D[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function vt(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.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(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],l=o.shape();for(let i in l){let c=l[i];if(c===void 0||c._def===void 0)continue;let y=Dr(c);y&&t&&(c instanceof St.ZodOptional&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),y=!1);let f=u(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,y||s.push(i))}s.length&&(r.required=s);let a=Lr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function Lr(o,e){if(o.catchall._def.typeName!=="ZodNever")return u(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dr(o){try{return o.isOptional()}catch{return!0}}var Pt=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(o.innerType._def,e);let t=u(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Tt=(o,e)=>{if(e.pipeStrategy==="input")return u(o.in._def,e);if(e.pipeStrategy==="output")return u(o.out._def,e);let t=u(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function wt(o,e){return u(o.type._def,e)}function Ct(o,e){let r={type:"array",uniqueItems:!0,items:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&d(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&d(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function kt(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Et(){return{not:{}}}function jt(){return{}}var At=(o,e)=>u(o.innerType._def,e);var Nt=(o,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return ie(o,t);case m.ZodFirstPartyTypeKind.ZodNumber:return vt(o,t);case m.ZodFirstPartyTypeKind.ZodObject:return Rt(o,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return st(o,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return at();case m.ZodFirstPartyTypeKind.ZodDate:return ve(o,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return Et();case m.ZodFirstPartyTypeKind.ZodNull:return bt(t);case m.ZodFirstPartyTypeKind.ZodArray:return nt(o,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return _t(o,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return ut(o,t);case m.ZodFirstPartyTypeKind.ZodTuple:return kt(o,t);case m.ZodFirstPartyTypeKind.ZodRecord:return le(o,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return mt(o,t);case m.ZodFirstPartyTypeKind.ZodEnum:return pt(o);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return ht(o);case m.ZodFirstPartyTypeKind.ZodNullable:return xt(o,t);case m.ZodFirstPartyTypeKind.ZodOptional:return Pt(o,t);case m.ZodFirstPartyTypeKind.ZodMap:return ft(o,t);case m.ZodFirstPartyTypeKind.ZodSet:return Ct(o,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>o.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return wt(o,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return gt();case m.ZodFirstPartyTypeKind.ZodEffects:return ct(o,t);case m.ZodFirstPartyTypeKind.ZodAny:return rt();case m.ZodFirstPartyTypeKind.ZodUnknown:return jt();case m.ZodFirstPartyTypeKind.ZodDefault:return lt(o,t);case m.ZodFirstPartyTypeKind.ZodBranded:return ae(o,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return At(o,t);case m.ZodFirstPartyTypeKind.ZodCatch:return it(o,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Tt(o,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(o,e,t=!1){let r=e.seen.get(o);if(e.override){let i=e.override?.(o,e,r,t);if(i!==Qe)return i}if(r&&!t){let i=Hr(r,e);if(i!==void 0)return i}let s={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,s);let l=Nt(o,o.typeName,e),a=typeof l=="function"?u(l(),e):l;if(a&&qr(o,e,a),e.postProcess){let i=e.postProcess(a,o,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Hr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:$r(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.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}},$r=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},qr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Pe=(o,e)=>{let t=tt(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[y,f])=>({...c,[y]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,y]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,l=u(o._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&&(l.title=a);let i=s===void 0?r?{...l,[t.definitionPath]:r}:l:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:l}};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 H=require("zod");var It=require("zod"),Te;(function(o){o.Completable="McpCompletable"})(Te||(Te={}));var I=class extends It.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}};I.create=(o,e)=>new I({type:o,typeName:Te.Completable,complete:e.complete,...Zr(e)});function Zr(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=o;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 c,y;let{message:f}=o;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(c=f??r)!==null&&c!==void 0?c:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(y=f??t)!==null&&y!==void 0?y:i.defaultError}},description:s}}var pe=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 se(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({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}):Fr,annotations:t.annotations}))})),this.server.setRequestHandler(re,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 l=s.data,a=r.callback;try{return await Promise.resolve(a(l,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(l){return{content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,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 ce;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof I))return ce;let a=await s._def.complete(e.params.argument.value);return Mt(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 ce;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 ce;let l=await s(e.params.argument.value);return Mt(l)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(J,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([l,a])=>a.enabled).map(([l,a])=>({uri:l,name:a.name,...a.metadata})),s=[];for(let l of Object.values(this._registeredResourceTemplates)){if(!l.resourceTemplate.listCallback)continue;let a=await l.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...l.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(B,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(K,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 l of Object.values(this._registeredResourceTemplates)){let a=l.resourceTemplate.uriTemplate.match(r.toString());if(a)return l.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(X.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(X,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ur(t.argsSchema):void 0}))})),this.server.setRequestHandler(W,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 l=s.data,a=r.callback;return await Promise.resolve(a(l,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 l=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:l,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:l,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,l;if(t.length>1){let c=t[0];Ot(c)?(s=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!Ot(t[0])&&(l=t.shift())):typeof c=="object"&&c!==null&&(l=t.shift())}let a=t[0],i={description:r,inputSchema:s===void 0?void 0:H.z.object(s),annotations:l,callback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredTools[e],c.name&&(this._registeredTools[c.name]=i)),typeof c.description<"u"&&(i.description=c.description),typeof c.paramsSchema<"u"&&(i.inputSchema=H.z.object(c.paramsSchema)),typeof c.callback<"u"&&(i.callback=c.callback),typeof c.annotations<"u"&&(i.annotations=c.annotations),typeof c.enabled<"u"&&(i.enabled=c.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=i,this.setToolRequestHandlers(),this.sendToolListChanged(),i}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 l=t[0],a={description:r,argsSchema:s===void 0?void 0:H.z.object(s),callback:l,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=H.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 Fr={type:"object"};function Ot(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(zr)}function zr(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Ur(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Mt(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var ce={completion:{values:[],hasMore:!1}};var Lt=process.env.personalToken||""||"",Dt="F2C MCP",Ht="0.0.1";var h=require("zod");var we=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=Lt}async f2cNodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,format:e.format},r=this.opToUrl(`${this.f2cHost}/nodes`,t,[]);return this.fetch(r,"text")}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},s=await fetch(e,r);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return t==="text"?await s.text():await s.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let s=new URL(e);for(let[l,a]of Object.entries(t))r.includes(l)||s.searchParams.append(l,a);return s.toString()}},O=new we;var A=new pe({name:Dt,version:Ht},{capabilities:{logging:{}}});A.tool("figma_to_html","Convert Figma design to HTML code with node",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("List of node IDs to retrieve, comma separated"),format:h.z.string().default("html").describe("Format of the returned code"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.f2cNodeToCode(o)}]}}catch(e){return console.error("Tool execution error:",e),{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("List of node IDs to retrieve, comma separated"),personalToken:h.z.string().optional().describe("Your Figma personal access token"),version:h.z.string().optional().describe("Specify the version to return"),depth:h.z.number().optional().describe("Specify the depth of nodes to return"),geometry:h.z.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:h.z.string().optional().describe("Specify plugin data to return"),branch_data:h.z.boolean().optional().describe("Specify whether to return branch data")},async o=>{try{return{content:[{type:"text",text:await O.files(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_images","Get images of Figma nodes",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("Node IDs to get images for, comma separated"),format:h.z.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:h.z.number().optional().describe("Image scale factor"),svg_include_id:h.z.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:h.z.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:h.z.boolean().optional().describe("Whether to use absolute bounds"),version:h.z.string().optional().describe("Specify the version to return"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.images(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_image_fills","Get all image resources in the specified Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.imageFills(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_file_meta","Get metadata information for a Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.meta(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});var Ce=Bt(require("process"),1);var ue=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
|
+
]`;continue}s+=r[c],r[c]==="\\"?l=!0:a&&r[c]==="]"?a=!1:!a&&r[c]==="["&&(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`),o.source}return s}function le(o,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"&&o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,s)=>({...r,[s]:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodString&&o.keyType._def.checks?.length){let{type:r,...s}=ie(o.keyType._def,e);return{...t,propertyNames:s}}else{if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===N.ZodFirstPartyTypeKind.ZodBranded&&o.keyType._def.type._def.typeName===N.ZodFirstPartyTypeKind.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...s}=ae(o.keyType._def,e);return{...t,propertyNames:s}}}return t}function ft(o,e){if(e.mapStrategy==="record")return le(o,e);let t=u(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(o.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 ht(o){let e=o.values,r=Object.keys(o.values).filter(l=>typeof e[e[l]]!="number").map(l=>e[l]),s=Array.from(new Set(r.map(l=>typeof l)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function gt(){return{not:{}}}function bt(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _t(o,e){if(e.target==="openApi3")return yt(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in D&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,l)=>{let a=D[l._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,l)=>{let a=typeof l._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(l._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((l,a,i)=>i.indexOf(l)===a);return{type:s.length>1?s:s[0],enum:t.reduce((l,a)=>l.includes(a._def.value)?l:[...l,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(l=>!r.includes(l))],[])};return yt(o,e)}var yt=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.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(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:D[o.innerType._def.typeName],nullable:!0}:{type:[D[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function vt(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.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(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],l=o.shape();for(let i in l){let c=l[i];if(c===void 0||c._def===void 0)continue;let y=Dr(c);y&&t&&(c instanceof St.ZodOptional&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),y=!1);let f=u(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,y||s.push(i))}s.length&&(r.required=s);let a=Lr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function Lr(o,e){if(o.catchall._def.typeName!=="ZodNever")return u(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dr(o){try{return o.isOptional()}catch{return!0}}var Pt=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(o.innerType._def,e);let t=u(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Tt=(o,e)=>{if(e.pipeStrategy==="input")return u(o.in._def,e);if(e.pipeStrategy==="output")return u(o.out._def,e);let t=u(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function wt(o,e){return u(o.type._def,e)}function Ct(o,e){let r={type:"array",uniqueItems:!0,items:u(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&d(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&d(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function kt(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Et(){return{not:{}}}function jt(){return{}}var At=(o,e)=>u(o.innerType._def,e);var Nt=(o,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return ie(o,t);case m.ZodFirstPartyTypeKind.ZodNumber:return vt(o,t);case m.ZodFirstPartyTypeKind.ZodObject:return Rt(o,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return st(o,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return at();case m.ZodFirstPartyTypeKind.ZodDate:return ve(o,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return Et();case m.ZodFirstPartyTypeKind.ZodNull:return bt(t);case m.ZodFirstPartyTypeKind.ZodArray:return nt(o,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return _t(o,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return ut(o,t);case m.ZodFirstPartyTypeKind.ZodTuple:return kt(o,t);case m.ZodFirstPartyTypeKind.ZodRecord:return le(o,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return mt(o,t);case m.ZodFirstPartyTypeKind.ZodEnum:return pt(o);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return ht(o);case m.ZodFirstPartyTypeKind.ZodNullable:return xt(o,t);case m.ZodFirstPartyTypeKind.ZodOptional:return Pt(o,t);case m.ZodFirstPartyTypeKind.ZodMap:return ft(o,t);case m.ZodFirstPartyTypeKind.ZodSet:return Ct(o,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>o.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return wt(o,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return gt();case m.ZodFirstPartyTypeKind.ZodEffects:return ct(o,t);case m.ZodFirstPartyTypeKind.ZodAny:return rt();case m.ZodFirstPartyTypeKind.ZodUnknown:return jt();case m.ZodFirstPartyTypeKind.ZodDefault:return lt(o,t);case m.ZodFirstPartyTypeKind.ZodBranded:return ae(o,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return At(o,t);case m.ZodFirstPartyTypeKind.ZodCatch:return it(o,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Tt(o,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(o,e,t=!1){let r=e.seen.get(o);if(e.override){let i=e.override?.(o,e,r,t);if(i!==Qe)return i}if(r&&!t){let i=Hr(r,e);if(i!==void 0)return i}let s={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,s);let l=Nt(o,o.typeName,e),a=typeof l=="function"?u(l(),e):l;if(a&&qr(o,e,a),e.postProcess){let i=e.postProcess(a,o,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Hr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:$r(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.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}},$r=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},qr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Pe=(o,e)=>{let t=tt(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[y,f])=>({...c,[y]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,y]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,l=u(o._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&&(l.title=a);let i=s===void 0?r?{...l,[t.definitionPath]:r}:l:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:l}};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 H=require("zod");var Ot=require("zod"),Te;(function(o){o.Completable="McpCompletable"})(Te||(Te={}));var O=class extends Ot.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}};O.create=(o,e)=>new O({type:o,typeName:Te.Completable,complete:e.complete,...Zr(e)});function Zr(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=o;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 c,y;let{message:f}=o;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(c=f??r)!==null&&c!==void 0?c:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(y=f??t)!==null&&y!==void 0?y:i.defaultError}},description:s}}var pe=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 se(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({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}):Fr,annotations:t.annotations}))})),this.server.setRequestHandler(re,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 l=s.data,a=r.callback;try{return await Promise.resolve(a(l,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(l){return{content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,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 ce;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof O))return ce;let a=await s._def.complete(e.params.argument.value);return Mt(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 ce;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 ce;let l=await s(e.params.argument.value);return Mt(l)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(G,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([l,a])=>a.enabled).map(([l,a])=>({uri:l,name:a.name,...a.metadata})),s=[];for(let l of Object.values(this._registeredResourceTemplates)){if(!l.resourceTemplate.listCallback)continue;let a=await l.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...l.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(B,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(K,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 l of Object.values(this._registeredResourceTemplates)){let a=l.resourceTemplate.uriTemplate.match(r.toString());if(a)return l.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(X.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(X,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ur(t.argsSchema):void 0}))})),this.server.setRequestHandler(W,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 l=s.data,a=r.callback;return await Promise.resolve(a(l,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 l=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:l,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:l,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,l;if(t.length>1){let c=t[0];It(c)?(s=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!It(t[0])&&(l=t.shift())):typeof c=="object"&&c!==null&&(l=t.shift())}let a=t[0],i={description:r,inputSchema:s===void 0?void 0:H.z.object(s),annotations:l,callback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredTools[e],c.name&&(this._registeredTools[c.name]=i)),typeof c.description<"u"&&(i.description=c.description),typeof c.paramsSchema<"u"&&(i.inputSchema=H.z.object(c.paramsSchema)),typeof c.callback<"u"&&(i.callback=c.callback),typeof c.annotations<"u"&&(i.annotations=c.annotations),typeof c.enabled<"u"&&(i.enabled=c.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=i,this.setToolRequestHandlers(),this.sendToolListChanged(),i}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 l=t[0],a={description:r,argsSchema:s===void 0?void 0:H.z.object(s),callback:l,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=H.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 Fr={type:"object"};function It(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(zr)}function zr(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Ur(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Mt(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var ce={completion:{values:[],hasMore:!1}};var Lt=process.env.personalToken||""||"",Dt="F2C MCP",Ht="0.0.1";var h=require("zod");var we=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=Lt}async f2cNodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,format:e.format},r=this.opToUrl(`${this.f2cHost}/nodes`,t,[]);return this.fetch(r,"text")}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},s=await fetch(e,r);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return t==="text"?await s.text():await s.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let s=new URL(e);for(let[l,a]of Object.entries(t))r.includes(l)||s.searchParams.append(l,a);return s.toString()}},I=new we;var A=new pe({name:Dt,version:Ht},{capabilities:{logging:{}}});A.tool("figma_to_html","Convert Figma design to HTML code with node",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("List of node IDs to retrieve, comma separated"),format:h.z.string().default("html").describe("Format of the returned code"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await I.f2cNodeToCode(o)}]}}catch(e){return console.error("Tool execution error:",e),{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("List of node IDs to retrieve, comma separated"),personalToken:h.z.string().optional().describe("Your Figma personal access token"),version:h.z.string().optional().describe("Specify the version to return"),depth:h.z.number().optional().describe("Specify the depth of nodes to return"),geometry:h.z.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:h.z.string().optional().describe("Specify plugin data to return"),branch_data:h.z.boolean().optional().describe("Specify whether to return branch data")},async o=>{try{let e=await I.files(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_images","Get images of Figma nodes",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),ids:h.z.string().describe("Node IDs to get images for, comma separated"),format:h.z.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:h.z.number().optional().describe("Image scale factor"),svg_include_id:h.z.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:h.z.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:h.z.boolean().optional().describe("Whether to use absolute bounds"),version:h.z.string().optional().describe("Specify the version to return"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.images(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_image_fills","Get all image resources in the specified Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.imageFills(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});A.tool("figma_get_file_meta","Get metadata information for a Figma file",{fileKey:h.z.string().describe("Unique identifier of the Figma file"),personalToken:h.z.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.meta(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});var Ce=Bt(require("process"),1);var ue=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
7
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Vr(t)}clear(){this._buffer=void 0}};function Vr(o){return ze.parse(JSON.parse(o))}function $t(o){return JSON.stringify(o)+`
|
8
8
|
`}var me=class{constructor(e=Ce.default.stdin,t=Ce.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ue,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=$t(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};async function qt(o){let e=new me;await o.connect(e)}qt(A).catch(o=>{Ne("error",{message:`Server startup failed: ${o.message}`,code:-32e3}),process.exit(1)});
|
package/dist/cli.mjs
CHANGED
@@ -1,8 +1,8 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
function Ae(o,e){let t={jsonrpc:"2.0",...o==="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 n}from"zod";var he="2025-03-26",Ne=[he,"2024-11-05","2024-10-07"],$="2.0",Ie=n.union([n.string(),n.number().int()]),Oe=n.string(),$t=n.object({progressToken:n.optional(Ie)}).passthrough(),P=n.object({_meta:n.optional($t)}).passthrough(),S=n.object({method:n.string(),params:n.optional(P)}),L=n.object({_meta:n.optional(n.object({}).passthrough())}).passthrough(),E=n.object({method:n.string(),params:n.optional(L)}),T=n.object({_meta:n.optional(n.object({}).passthrough())}).passthrough(),q=n.union([n.string(),n.number().int()]),Me=n.object({jsonrpc:n.literal($),id:q}).merge(S).strict(),Le=o=>Me.safeParse(o).success,De=n.object({jsonrpc:n.literal($)}).merge(E).strict(),He=o=>De.safeParse(o).success,$e=n.object({jsonrpc:n.literal($),id:q,result:T}).strict(),ge=o=>$e.safeParse(o).success,b;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(b||(b={}));var qe=n.object({jsonrpc:n.literal($),id:q,error:n.object({code:n.number().int(),message:n.string(),data:n.optional(n.unknown())})}).strict(),Ze=o=>qe.safeParse(o).success,Fe=n.union([Me,De,$e,qe]),Z=T.strict(),F=E.extend({method:n.literal("notifications/cancelled"),params:L.extend({requestId:q,reason:n.string().optional()})}),ze=n.object({name:n.string(),version:n.string()}).passthrough(),qt=n.object({experimental:n.optional(n.object({}).passthrough()),sampling:n.optional(n.object({}).passthrough()),roots:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough())}).passthrough(),be=S.extend({method:n.literal("initialize"),params:P.extend({protocolVersion:n.string(),capabilities:qt,clientInfo:ze})});var Zt=n.object({experimental:n.optional(n.object({}).passthrough()),logging:n.optional(n.object({}).passthrough()),completions:n.optional(n.object({}).passthrough()),prompts:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough()),resources:n.optional(n.object({subscribe:n.optional(n.boolean()),listChanged:n.optional(n.boolean())}).passthrough()),tools:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough())}).passthrough(),Ft=T.extend({protocolVersion:n.string(),capabilities:Zt,serverInfo:ze,instructions:n.optional(n.string())}),ye=E.extend({method:n.literal("notifications/initialized")});var z=S.extend({method:n.literal("ping")}),zt=n.object({progress:n.number(),total:n.optional(n.number())}).passthrough(),U=E.extend({method:n.literal("notifications/progress"),params:L.merge(zt).extend({progressToken:Ie})}),V=S.extend({params:P.extend({cursor:n.optional(Oe)}).optional()}),G=T.extend({nextCursor:n.optional(Oe)}),Ue=n.object({uri:n.string(),mimeType:n.optional(n.string())}).passthrough(),Ve=Ue.extend({text:n.string()}),Ge=Ue.extend({blob:n.string().base64()}),Ut=n.object({uri:n.string(),name:n.string(),description:n.optional(n.string()),mimeType:n.optional(n.string())}).passthrough(),Vt=n.object({uriTemplate:n.string(),name:n.string(),description:n.optional(n.string()),mimeType:n.optional(n.string())}).passthrough(),J=V.extend({method:n.literal("resources/list")}),Gt=G.extend({resources:n.array(Ut)}),B=V.extend({method:n.literal("resources/templates/list")}),Jt=G.extend({resourceTemplates:n.array(Vt)}),K=S.extend({method:n.literal("resources/read"),params:P.extend({uri:n.string()})}),Bt=T.extend({contents:n.array(n.union([Ve,Ge]))}),Kt=E.extend({method:n.literal("notifications/resources/list_changed")}),Xt=S.extend({method:n.literal("resources/subscribe"),params:P.extend({uri:n.string()})}),Wt=S.extend({method:n.literal("resources/unsubscribe"),params:P.extend({uri:n.string()})}),Yt=E.extend({method:n.literal("notifications/resources/updated"),params:L.extend({uri:n.string()})}),Qt=n.object({name:n.string(),description:n.optional(n.string()),required:n.optional(n.boolean())}).passthrough(),er=n.object({name:n.string(),description:n.optional(n.string()),arguments:n.optional(n.array(Qt))}).passthrough(),X=V.extend({method:n.literal("prompts/list")}),tr=G.extend({prompts:n.array(er)}),W=S.extend({method:n.literal("prompts/get"),params:P.extend({name:n.string(),arguments:n.optional(n.record(n.string()))})}),Y=n.object({type:n.literal("text"),text:n.string()}).passthrough(),Q=n.object({type:n.literal("image"),data:n.string().base64(),mimeType:n.string()}).passthrough(),ee=n.object({type:n.literal("audio"),data:n.string().base64(),mimeType:n.string()}).passthrough(),Je=n.object({type:n.literal("resource"),resource:n.union([Ve,Ge])}).passthrough(),rr=n.object({role:n.enum(["user","assistant"]),content:n.union([Y,Q,ee,Je])}).passthrough(),or=T.extend({description:n.optional(n.string()),messages:n.array(rr)}),nr=E.extend({method:n.literal("notifications/prompts/list_changed")}),sr=n.object({title:n.optional(n.string()),readOnlyHint:n.optional(n.boolean()),destructiveHint:n.optional(n.boolean()),idempotentHint:n.optional(n.boolean()),openWorldHint:n.optional(n.boolean())}).passthrough(),ar=n.object({name:n.string(),description:n.optional(n.string()),inputSchema:n.object({type:n.literal("object"),properties:n.optional(n.object({}).passthrough())}).passthrough(),annotations:n.optional(sr)}).passthrough(),te=V.extend({method:n.literal("tools/list")}),ir=G.extend({tools:n.array(ar)}),Be=T.extend({content:n.array(n.union([Y,Q,ee,Je])),isError:n.boolean().default(!1).optional()}),Fr=Be.or(T.extend({toolResult:n.unknown()})),re=S.extend({method:n.literal("tools/call"),params:P.extend({name:n.string(),arguments:n.optional(n.record(n.unknown()))})}),lr=E.extend({method:n.literal("notifications/tools/list_changed")}),Ke=n.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),cr=S.extend({method:n.literal("logging/setLevel"),params:P.extend({level:Ke})}),pr=E.extend({method:n.literal("notifications/message"),params:L.extend({level:Ke,logger:n.optional(n.string()),data:n.unknown()})}),ur=n.object({name:n.string().optional()}).passthrough(),mr=n.object({hints:n.optional(n.array(ur)),costPriority:n.optional(n.number().min(0).max(1)),speedPriority:n.optional(n.number().min(0).max(1)),intelligencePriority:n.optional(n.number().min(0).max(1))}).passthrough(),dr=n.object({role:n.enum(["user","assistant"]),content:n.union([Y,Q,ee])}).passthrough(),fr=S.extend({method:n.literal("sampling/createMessage"),params:P.extend({messages:n.array(dr),systemPrompt:n.optional(n.string()),includeContext:n.optional(n.enum(["none","thisServer","allServers"])),temperature:n.optional(n.number()),maxTokens:n.number().int(),stopSequences:n.optional(n.array(n.string())),metadata:n.optional(n.object({}).passthrough()),modelPreferences:n.optional(mr)})}),_e=T.extend({model:n.string(),stopReason:n.optional(n.enum(["endTurn","stopSequence","maxTokens"]).or(n.string())),role:n.enum(["user","assistant"]),content:n.discriminatedUnion("type",[Y,Q,ee])}),hr=n.object({type:n.literal("ref/resource"),uri:n.string()}).passthrough(),gr=n.object({type:n.literal("ref/prompt"),name:n.string()}).passthrough(),oe=S.extend({method:n.literal("completion/complete"),params:P.extend({ref:n.union([gr,hr]),argument:n.object({name:n.string(),value:n.string()}).passthrough()})}),br=T.extend({completion:n.object({values:n.array(n.string()).max(100),total:n.optional(n.number().int()),hasMore:n.optional(n.boolean())}).passthrough()}),yr=n.object({uri:n.string().startsWith("file://"),name:n.optional(n.string())}).passthrough(),_r=S.extend({method:n.literal("roots/list")}),xe=T.extend({roots:n.array(yr)}),xr=E.extend({method:n.literal("notifications/roots/list_changed")}),zr=n.union([z,be,oe,cr,W,X,J,B,K,Xt,Wt,re,te]),Ur=n.union([F,U,ye,xr]),Vr=n.union([Z,_e,xe]),Gr=n.union([z,fr,_r]),Jr=n.union([F,U,pr,Yt,Kt,lr,nr]),Br=n.union([Z,Ft,br,or,tr,Gt,Jt,Bt,Be,ir]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var vr=6e4,ne=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(F,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,s,l=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:l,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)||Ze(t)?this._onresponse(t):Le(t)?this._onrequest(t,r):He(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,l,a;let i=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(i===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(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let _={signal:c.signal,sessionId:(l=this._transport)===null||l===void 0?void 0:l.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,v,j)=>this.request(h,v,{...j,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>i(e,_)).then(h=>{var v;if(!c.signal.aborted)return(v=this._transport)===null||v===void 0?void 0:v.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var v,j;if(!c.signal.aborted)return(v=this._transport)===null||v===void 0?void 0:v.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:b.InternalError,message:(j=h.message)!==null&&j!==void 0?j:"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),l=this._progressHandlers.get(s);if(!l){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(c){a(c);return}l(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:l,onresumptiontoken:a}=r??{};return new Promise((i,c)=>{var _,h,v,j,fe;if(!this._transport){c(new Error("Not connected"));return}((_=this._options)===null||_===void 0?void 0:_.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(h=r?.signal)===null||h===void 0||h.throwIfAborted();let k=this._requestMessageId++,ke={...e,jsonrpc:"2.0",id:k};r?.onprogress&&(this._progressHandlers.set(k,r.onprogress),ke.params={...e.params,_meta:{progressToken:k}});let Ee=R=>{var A;this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(R)}},{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`))),c(R)};this._responseHandlers.set(k,R=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(R instanceof Error)return c(R);try{let M=t.parse(R.result);i(M)}catch(M){c(M)}}}),(v=r?.signal)===null||v===void 0||v.addEventListener("abort",()=>{var R;Ee((R=r?.signal)===null||R===void 0?void 0:R.reason)});let je=(j=r?.timeout)!==null&&j!==void 0?j:vr,Ht=()=>Ee(new y(b.RequestTimeout,"Request timed out",{timeout:je}));this._setupTimeout(k,je,r?.maxTotalTimeout,Ht,(fe=r?.resetTimeoutOnProgress)!==null&&fe!==void 0?fe:!1),this._transport.send(ke,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(R=>{this._cleanupTimeout(k),c(R)})})}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,l)=>Promise.resolve(t(e.parse(s),l)))}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 Xe(o,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),{...o})}var se=class extends ne{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=Xe(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:Ne.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"},Z)}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 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"},Qe=o=>typeof o=="string"?{...We,name:o}:{...We,...o};var et=o=>{let e=Qe(o),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(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function f(o,e,t,r,s){o[e]=t,ve(o,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function tt(){return{}}import{ZodFirstPartyTypeKind as Sr}from"zod";function rt(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==Sr.ZodAny&&(t.items=m(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&f(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&f(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(f(t,"minItems",o.exactLength.value,o.exactLength.message,e),f(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function ot(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}function nt(){return{type:"boolean"}}function ae(o,e){return m(o.type._def,e)}var st=(o,e)=>m(o.innerType._def,e);function Se(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,l)=>Se(o,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 Rr(o,e)}}var Rr=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.checks)switch(r.kind){case"min":f(t,"minimum",r.value,r.message,e);break;case"max":f(t,"maximum",r.value,r.message,e);break}return t};function at(o,e){return{...m(o.innerType._def,e),default:o.defaultValue()}}function it(o,e){return e.effectStrategy==="input"?m(o.schema._def,e):{}}function lt(o){return{type:"string",enum:Array.from(o.values)}}var Pr=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ct(o,e){let t=[m(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(l=>!!l),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(l=>{if(Pr(l))s.push(...l.allOf),l.unevaluatedProperties===void 0&&(r=void 0);else{let a=l;if("additionalProperties"in l&&l.additionalProperties===!1){let{additionalProperties:i,...c}=l;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function pt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}import{ZodFirstPartyTypeKind as D}from"zod";var Re,w={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 ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.checks)switch(r.kind){case"min":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":f(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":C(t,"email",r.message,e);break;case"format:idn-email":C(t,"idn-email",r.message,e);break;case"pattern:zod":x(t,w.email,r.message,e);break}break;case"url":C(t,"uri",r.message,e);break;case"uuid":C(t,"uuid",r.message,e);break;case"regex":x(t,r.regex,r.message,e);break;case"cuid":x(t,w.cuid,r.message,e);break;case"cuid2":x(t,w.cuid2,r.message,e);break;case"startsWith":x(t,RegExp(`^${Pe(r.value,e)}`),r.message,e);break;case"endsWith":x(t,RegExp(`${Pe(r.value,e)}$`),r.message,e);break;case"datetime":C(t,"date-time",r.message,e);break;case"date":C(t,"date",r.message,e);break;case"time":C(t,"time",r.message,e);break;case"duration":C(t,"duration",r.message,e);break;case"length":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{x(t,RegExp(Pe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&C(t,"ipv4",r.message,e),r.version!=="v4"&&C(t,"ipv6",r.message,e);break}case"base64url":x(t,w.base64url,r.message,e);break;case"jwt":x(t,w.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&x(t,w.ipv4Cidr,r.message,e),r.version!=="v4"&&x(t,w.ipv6Cidr,r.message,e);break}case"emoji":x(t,w.emoji(),r.message,e);break;case"ulid":{x(t,w.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{C(t,"binary",r.message,e);break}case"contentEncoding:base64":{f(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{x(t,w.base64,r.message,e);break}}break}case"nanoid":x(t,w.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Pe(o,e){return e.patternStrategy==="escape"?wr(o):o}var Tr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wr(o){let e="";for(let t=0;t<o.length;t++)Tr.has(o[t])||(e+="\\"),e+=o[t];return e}function C(o,e,t,r){o.format||o.anyOf?.some(s=>s.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):f(o,"format",e,t,r)}function x(o,e,t,r){o.pattern||o.allOf?.some(s=>s.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:ut(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):f(o,"pattern",ut(e,r),t,r)}function ut(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,s="",l=!1,a=!1,i=!1;for(let c=0;c<r.length;c++){if(l){s+=r[c],l=!1;continue}if(t.i){if(a){if(r[c].match(/[a-z]/)){i?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),i=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],i=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(t.m){if(r[c]==="^"){s+=`(^|(?<=[\r
|
2
|
+
function Ae(o,e){let t={jsonrpc:"2.0",...o==="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 n}from"zod";var he="2025-03-26",Ne=[he,"2024-11-05","2024-10-07"],$="2.0",Oe=n.union([n.string(),n.number().int()]),Ie=n.string(),$t=n.object({progressToken:n.optional(Oe)}).passthrough(),P=n.object({_meta:n.optional($t)}).passthrough(),S=n.object({method:n.string(),params:n.optional(P)}),L=n.object({_meta:n.optional(n.object({}).passthrough())}).passthrough(),E=n.object({method:n.string(),params:n.optional(L)}),T=n.object({_meta:n.optional(n.object({}).passthrough())}).passthrough(),q=n.union([n.string(),n.number().int()]),Me=n.object({jsonrpc:n.literal($),id:q}).merge(S).strict(),Le=o=>Me.safeParse(o).success,De=n.object({jsonrpc:n.literal($)}).merge(E).strict(),He=o=>De.safeParse(o).success,$e=n.object({jsonrpc:n.literal($),id:q,result:T}).strict(),ge=o=>$e.safeParse(o).success,b;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(b||(b={}));var qe=n.object({jsonrpc:n.literal($),id:q,error:n.object({code:n.number().int(),message:n.string(),data:n.optional(n.unknown())})}).strict(),Ze=o=>qe.safeParse(o).success,Fe=n.union([Me,De,$e,qe]),Z=T.strict(),F=E.extend({method:n.literal("notifications/cancelled"),params:L.extend({requestId:q,reason:n.string().optional()})}),ze=n.object({name:n.string(),version:n.string()}).passthrough(),qt=n.object({experimental:n.optional(n.object({}).passthrough()),sampling:n.optional(n.object({}).passthrough()),roots:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough())}).passthrough(),be=S.extend({method:n.literal("initialize"),params:P.extend({protocolVersion:n.string(),capabilities:qt,clientInfo:ze})});var Zt=n.object({experimental:n.optional(n.object({}).passthrough()),logging:n.optional(n.object({}).passthrough()),completions:n.optional(n.object({}).passthrough()),prompts:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough()),resources:n.optional(n.object({subscribe:n.optional(n.boolean()),listChanged:n.optional(n.boolean())}).passthrough()),tools:n.optional(n.object({listChanged:n.optional(n.boolean())}).passthrough())}).passthrough(),Ft=T.extend({protocolVersion:n.string(),capabilities:Zt,serverInfo:ze,instructions:n.optional(n.string())}),ye=E.extend({method:n.literal("notifications/initialized")});var z=S.extend({method:n.literal("ping")}),zt=n.object({progress:n.number(),total:n.optional(n.number())}).passthrough(),U=E.extend({method:n.literal("notifications/progress"),params:L.merge(zt).extend({progressToken:Oe})}),V=S.extend({params:P.extend({cursor:n.optional(Ie)}).optional()}),J=T.extend({nextCursor:n.optional(Ie)}),Ue=n.object({uri:n.string(),mimeType:n.optional(n.string())}).passthrough(),Ve=Ue.extend({text:n.string()}),Je=Ue.extend({blob:n.string().base64()}),Ut=n.object({uri:n.string(),name:n.string(),description:n.optional(n.string()),mimeType:n.optional(n.string())}).passthrough(),Vt=n.object({uriTemplate:n.string(),name:n.string(),description:n.optional(n.string()),mimeType:n.optional(n.string())}).passthrough(),G=V.extend({method:n.literal("resources/list")}),Jt=J.extend({resources:n.array(Ut)}),B=V.extend({method:n.literal("resources/templates/list")}),Gt=J.extend({resourceTemplates:n.array(Vt)}),K=S.extend({method:n.literal("resources/read"),params:P.extend({uri:n.string()})}),Bt=T.extend({contents:n.array(n.union([Ve,Je]))}),Kt=E.extend({method:n.literal("notifications/resources/list_changed")}),Xt=S.extend({method:n.literal("resources/subscribe"),params:P.extend({uri:n.string()})}),Wt=S.extend({method:n.literal("resources/unsubscribe"),params:P.extend({uri:n.string()})}),Yt=E.extend({method:n.literal("notifications/resources/updated"),params:L.extend({uri:n.string()})}),Qt=n.object({name:n.string(),description:n.optional(n.string()),required:n.optional(n.boolean())}).passthrough(),er=n.object({name:n.string(),description:n.optional(n.string()),arguments:n.optional(n.array(Qt))}).passthrough(),X=V.extend({method:n.literal("prompts/list")}),tr=J.extend({prompts:n.array(er)}),W=S.extend({method:n.literal("prompts/get"),params:P.extend({name:n.string(),arguments:n.optional(n.record(n.string()))})}),Y=n.object({type:n.literal("text"),text:n.string()}).passthrough(),Q=n.object({type:n.literal("image"),data:n.string().base64(),mimeType:n.string()}).passthrough(),ee=n.object({type:n.literal("audio"),data:n.string().base64(),mimeType:n.string()}).passthrough(),Ge=n.object({type:n.literal("resource"),resource:n.union([Ve,Je])}).passthrough(),rr=n.object({role:n.enum(["user","assistant"]),content:n.union([Y,Q,ee,Ge])}).passthrough(),or=T.extend({description:n.optional(n.string()),messages:n.array(rr)}),nr=E.extend({method:n.literal("notifications/prompts/list_changed")}),sr=n.object({title:n.optional(n.string()),readOnlyHint:n.optional(n.boolean()),destructiveHint:n.optional(n.boolean()),idempotentHint:n.optional(n.boolean()),openWorldHint:n.optional(n.boolean())}).passthrough(),ar=n.object({name:n.string(),description:n.optional(n.string()),inputSchema:n.object({type:n.literal("object"),properties:n.optional(n.object({}).passthrough())}).passthrough(),annotations:n.optional(sr)}).passthrough(),te=V.extend({method:n.literal("tools/list")}),ir=J.extend({tools:n.array(ar)}),Be=T.extend({content:n.array(n.union([Y,Q,ee,Ge])),isError:n.boolean().default(!1).optional()}),Fr=Be.or(T.extend({toolResult:n.unknown()})),re=S.extend({method:n.literal("tools/call"),params:P.extend({name:n.string(),arguments:n.optional(n.record(n.unknown()))})}),lr=E.extend({method:n.literal("notifications/tools/list_changed")}),Ke=n.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),cr=S.extend({method:n.literal("logging/setLevel"),params:P.extend({level:Ke})}),pr=E.extend({method:n.literal("notifications/message"),params:L.extend({level:Ke,logger:n.optional(n.string()),data:n.unknown()})}),ur=n.object({name:n.string().optional()}).passthrough(),mr=n.object({hints:n.optional(n.array(ur)),costPriority:n.optional(n.number().min(0).max(1)),speedPriority:n.optional(n.number().min(0).max(1)),intelligencePriority:n.optional(n.number().min(0).max(1))}).passthrough(),dr=n.object({role:n.enum(["user","assistant"]),content:n.union([Y,Q,ee])}).passthrough(),fr=S.extend({method:n.literal("sampling/createMessage"),params:P.extend({messages:n.array(dr),systemPrompt:n.optional(n.string()),includeContext:n.optional(n.enum(["none","thisServer","allServers"])),temperature:n.optional(n.number()),maxTokens:n.number().int(),stopSequences:n.optional(n.array(n.string())),metadata:n.optional(n.object({}).passthrough()),modelPreferences:n.optional(mr)})}),_e=T.extend({model:n.string(),stopReason:n.optional(n.enum(["endTurn","stopSequence","maxTokens"]).or(n.string())),role:n.enum(["user","assistant"]),content:n.discriminatedUnion("type",[Y,Q,ee])}),hr=n.object({type:n.literal("ref/resource"),uri:n.string()}).passthrough(),gr=n.object({type:n.literal("ref/prompt"),name:n.string()}).passthrough(),oe=S.extend({method:n.literal("completion/complete"),params:P.extend({ref:n.union([gr,hr]),argument:n.object({name:n.string(),value:n.string()}).passthrough()})}),br=T.extend({completion:n.object({values:n.array(n.string()).max(100),total:n.optional(n.number().int()),hasMore:n.optional(n.boolean())}).passthrough()}),yr=n.object({uri:n.string().startsWith("file://"),name:n.optional(n.string())}).passthrough(),_r=S.extend({method:n.literal("roots/list")}),xe=T.extend({roots:n.array(yr)}),xr=E.extend({method:n.literal("notifications/roots/list_changed")}),zr=n.union([z,be,oe,cr,W,X,G,B,K,Xt,Wt,re,te]),Ur=n.union([F,U,ye,xr]),Vr=n.union([Z,_e,xe]),Jr=n.union([z,fr,_r]),Gr=n.union([F,U,pr,Yt,Kt,lr,nr]),Br=n.union([Z,Ft,br,or,tr,Jt,Gt,Bt,Be,ir]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var vr=6e4,ne=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(F,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,s,l=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:l,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)||Ze(t)?this._onresponse(t):Le(t)?this._onrequest(t,r):He(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,l,a;let i=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(i===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(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let _={signal:c.signal,sessionId:(l=this._transport)===null||l===void 0?void 0:l.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,v,j)=>this.request(h,v,{...j,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>i(e,_)).then(h=>{var v;if(!c.signal.aborted)return(v=this._transport)===null||v===void 0?void 0:v.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var v,j;if(!c.signal.aborted)return(v=this._transport)===null||v===void 0?void 0:v.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:b.InternalError,message:(j=h.message)!==null&&j!==void 0?j:"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),l=this._progressHandlers.get(s);if(!l){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(c){a(c);return}l(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:l,onresumptiontoken:a}=r??{};return new Promise((i,c)=>{var _,h,v,j,fe;if(!this._transport){c(new Error("Not connected"));return}((_=this._options)===null||_===void 0?void 0:_.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(h=r?.signal)===null||h===void 0||h.throwIfAborted();let k=this._requestMessageId++,ke={...e,jsonrpc:"2.0",id:k};r?.onprogress&&(this._progressHandlers.set(k,r.onprogress),ke.params={...e.params,_meta:{progressToken:k}});let Ee=R=>{var A;this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(R)}},{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`))),c(R)};this._responseHandlers.set(k,R=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(R instanceof Error)return c(R);try{let M=t.parse(R.result);i(M)}catch(M){c(M)}}}),(v=r?.signal)===null||v===void 0||v.addEventListener("abort",()=>{var R;Ee((R=r?.signal)===null||R===void 0?void 0:R.reason)});let je=(j=r?.timeout)!==null&&j!==void 0?j:vr,Ht=()=>Ee(new y(b.RequestTimeout,"Request timed out",{timeout:je}));this._setupTimeout(k,je,r?.maxTotalTimeout,Ht,(fe=r?.resetTimeoutOnProgress)!==null&&fe!==void 0?fe:!1),this._transport.send(ke,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:a}).catch(R=>{this._cleanupTimeout(k),c(R)})})}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,l)=>Promise.resolve(t(e.parse(s),l)))}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 Xe(o,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),{...o})}var se=class extends ne{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=Xe(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:Ne.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"},Z)}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 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"},Qe=o=>typeof o=="string"?{...We,name:o}:{...We,...o};var et=o=>{let e=Qe(o),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(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function f(o,e,t,r,s){o[e]=t,ve(o,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function tt(){return{}}import{ZodFirstPartyTypeKind as Sr}from"zod";function rt(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==Sr.ZodAny&&(t.items=m(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&f(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&f(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(f(t,"minItems",o.exactLength.value,o.exactLength.message,e),f(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function ot(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}function nt(){return{type:"boolean"}}function ae(o,e){return m(o.type._def,e)}var st=(o,e)=>m(o.innerType._def,e);function Se(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,l)=>Se(o,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 Rr(o,e)}}var Rr=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.checks)switch(r.kind){case"min":f(t,"minimum",r.value,r.message,e);break;case"max":f(t,"maximum",r.value,r.message,e);break}return t};function at(o,e){return{...m(o.innerType._def,e),default:o.defaultValue()}}function it(o,e){return e.effectStrategy==="input"?m(o.schema._def,e):{}}function lt(o){return{type:"string",enum:Array.from(o.values)}}var Pr=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ct(o,e){let t=[m(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(l=>!!l),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(l=>{if(Pr(l))s.push(...l.allOf),l.unevaluatedProperties===void 0&&(r=void 0);else{let a=l;if("additionalProperties"in l&&l.additionalProperties===!1){let{additionalProperties:i,...c}=l;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function pt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}import{ZodFirstPartyTypeKind as D}from"zod";var Re,w={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 ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.checks)switch(r.kind){case"min":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":f(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":C(t,"email",r.message,e);break;case"format:idn-email":C(t,"idn-email",r.message,e);break;case"pattern:zod":x(t,w.email,r.message,e);break}break;case"url":C(t,"uri",r.message,e);break;case"uuid":C(t,"uuid",r.message,e);break;case"regex":x(t,r.regex,r.message,e);break;case"cuid":x(t,w.cuid,r.message,e);break;case"cuid2":x(t,w.cuid2,r.message,e);break;case"startsWith":x(t,RegExp(`^${Pe(r.value,e)}`),r.message,e);break;case"endsWith":x(t,RegExp(`${Pe(r.value,e)}$`),r.message,e);break;case"datetime":C(t,"date-time",r.message,e);break;case"date":C(t,"date",r.message,e);break;case"time":C(t,"time",r.message,e);break;case"duration":C(t,"duration",r.message,e);break;case"length":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{x(t,RegExp(Pe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&C(t,"ipv4",r.message,e),r.version!=="v4"&&C(t,"ipv6",r.message,e);break}case"base64url":x(t,w.base64url,r.message,e);break;case"jwt":x(t,w.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&x(t,w.ipv4Cidr,r.message,e),r.version!=="v4"&&x(t,w.ipv6Cidr,r.message,e);break}case"emoji":x(t,w.emoji(),r.message,e);break;case"ulid":{x(t,w.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{C(t,"binary",r.message,e);break}case"contentEncoding:base64":{f(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{x(t,w.base64,r.message,e);break}}break}case"nanoid":x(t,w.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Pe(o,e){return e.patternStrategy==="escape"?wr(o):o}var Tr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wr(o){let e="";for(let t=0;t<o.length;t++)Tr.has(o[t])||(e+="\\"),e+=o[t];return e}function C(o,e,t,r){o.format||o.anyOf?.some(s=>s.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):f(o,"format",e,t,r)}function x(o,e,t,r){o.pattern||o.allOf?.some(s=>s.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:ut(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):f(o,"pattern",ut(e,r),t,r)}function ut(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,s="",l=!1,a=!1,i=!1;for(let c=0;c<r.length;c++){if(l){s+=r[c],l=!1;continue}if(t.i){if(a){if(r[c].match(/[a-z]/)){i?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),i=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],i=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(t.m){if(r[c]==="^"){s+=`(^|(?<=[\r
|
3
3
|
]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
|
4
4
|
]))`;continue}}if(t.s&&r[c]==="."){s+=a?`${r[c]}\r
|
5
5
|
`:`[${r[c]}\r
|
6
|
-
]`;continue}s+=r[c],r[c]==="\\"?l=!0:a&&r[c]==="]"?a=!1:!a&&r[c]==="["&&(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`),o.source}return s}function le(o,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"&&o.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,s)=>({...r,[s]:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===D.ZodString&&o.keyType._def.checks?.length){let{type:r,...s}=ie(o.keyType._def,e);return{...t,propertyNames:s}}else{if(o.keyType?._def.typeName===D.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===D.ZodBranded&&o.keyType._def.type._def.typeName===D.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...s}=ae(o.keyType._def,e);return{...t,propertyNames:s}}}return t}function mt(o,e){if(e.mapStrategy==="record")return le(o,e);let t=m(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(o.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(o){let e=o.values,r=Object.keys(o.values).filter(l=>typeof e[e[l]]!="number").map(l=>e[l]),s=Array.from(new Set(r.map(l=>typeof l)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ft(){return{not:{}}}function ht(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var H={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bt(o,e){if(e.target==="openApi3")return gt(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in H&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,l)=>{let a=H[l._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,l)=>{let a=typeof l._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(l._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((l,a,i)=>i.indexOf(l)===a);return{type:s.length>1?s:s[0],enum:t.reduce((l,a)=>l.includes(a._def.value)?l:[...l,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(l=>!r.includes(l))],[])};return gt(o,e)}var gt=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.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 yt(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:H[o.innerType._def.typeName],nullable:!0}:{type:[H[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function _t(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"int":t.type="integer",ve(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as Cr}from"zod";function xt(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],l=o.shape();for(let i in l){let c=l[i];if(c===void 0||c._def===void 0)continue;let _=Er(c);_&&t&&(c instanceof Cr&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),_=!1);let h=m(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});h!==void 0&&(r.properties[i]=h,_||s.push(i))}s.length&&(r.required=s);let a=kr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function kr(o,e){if(o.catchall._def.typeName!=="ZodNever")return m(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Er(o){try{return o.isOptional()}catch{return!0}}var vt=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(o.innerType._def,e);let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var St=(o,e)=>{if(e.pipeStrategy==="input")return m(o.in._def,e);if(e.pipeStrategy==="output")return m(o.out._def,e);let t=m(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Rt(o,e){return m(o.type._def,e)}function Pt(o,e){let r={type:"array",uniqueItems:!0,items:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&f(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&f(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function Tt(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function wt(){return{not:{}}}function Ct(){return{}}var kt=(o,e)=>m(o.innerType._def,e);var Et=(o,e,t)=>{switch(e){case d.ZodString:return ie(o,t);case d.ZodNumber:return _t(o,t);case d.ZodObject:return xt(o,t);case d.ZodBigInt:return ot(o,t);case d.ZodBoolean:return nt();case d.ZodDate:return Se(o,t);case d.ZodUndefined:return wt();case d.ZodNull:return ht(t);case d.ZodArray:return rt(o,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return bt(o,t);case d.ZodIntersection:return ct(o,t);case d.ZodTuple:return Tt(o,t);case d.ZodRecord:return le(o,t);case d.ZodLiteral:return pt(o,t);case d.ZodEnum:return lt(o);case d.ZodNativeEnum:return dt(o);case d.ZodNullable:return yt(o,t);case d.ZodOptional:return vt(o,t);case d.ZodMap:return mt(o,t);case d.ZodSet:return Pt(o,t);case d.ZodLazy:return()=>o.getter()._def;case d.ZodPromise:return Rt(o,t);case d.ZodNaN:case d.ZodNever:return ft();case d.ZodEffects:return it(o,t);case d.ZodAny:return tt();case d.ZodUnknown:return Ct();case d.ZodDefault:return at(o,t);case d.ZodBranded:return ae(o,t);case d.ZodReadonly:return kt(o,t);case d.ZodCatch:return st(o,t);case d.ZodPipeline:return St(o,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(o,e,t=!1){let r=e.seen.get(o);if(e.override){let i=e.override?.(o,e,r,t);if(i!==Ye)return i}if(r&&!t){let i=jr(r,e);if(i!==void 0)return i}let s={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,s);let l=Et(o,o.typeName,e),a=typeof l=="function"?m(l(),e):l;if(a&&Nr(o,e,a),e.postProcess){let i=e.postProcess(a,o,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var jr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:Ar(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.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}},Ar=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},Nr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Te=(o,e)=>{let t=et(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[_,h])=>({...c,[_]:m(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,_]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,l=m(o._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&&(l.title=a);let i=s===void 0?r?{...l,[t.definitionPath]:r}:l:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:l}};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 ce}from"zod";import{ZodType as Ir}from"zod";var we;(function(o){o.Completable="McpCompletable"})(we||(we={}));var I=class extends Ir{_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}};I.create=(o,e)=>new I({type:o,typeName:we.Completable,complete:e.complete,...Or(e)});function Or(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=o;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 c,_;let{message:h}=o;return a.code==="invalid_enum_value"?{message:h??i.defaultError}:typeof i.data>"u"?{message:(c=h??r)!==null&&c!==void 0?c:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(_=h??t)!==null&&_!==void 0?_:i.defaultError}},description:s}}var ue=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 se(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({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}):Mr,annotations:t.annotations}))})),this.server.setRequestHandler(re,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 l=s.data,a=r.callback;try{return await Promise.resolve(a(l,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(l){return{content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,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 pe;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof I))return pe;let a=await s._def.complete(e.params.argument.value);return At(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 pe;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 pe;let l=await s(e.params.argument.value);return At(l)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(J,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([l,a])=>a.enabled).map(([l,a])=>({uri:l,name:a.name,...a.metadata})),s=[];for(let l of Object.values(this._registeredResourceTemplates)){if(!l.resourceTemplate.listCallback)continue;let a=await l.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...l.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(B,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(K,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 l of Object.values(this._registeredResourceTemplates)){let a=l.resourceTemplate.uriTemplate.match(r.toString());if(a)return l.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(X.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(X,()=>({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(W,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 l=s.data,a=r.callback;return await Promise.resolve(a(l,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 l=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:l,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:l,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,l;if(t.length>1){let c=t[0];jt(c)?(s=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!jt(t[0])&&(l=t.shift())):typeof c=="object"&&c!==null&&(l=t.shift())}let a=t[0],i={description:r,inputSchema:s===void 0?void 0:ce.object(s),annotations:l,callback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredTools[e],c.name&&(this._registeredTools[c.name]=i)),typeof c.description<"u"&&(i.description=c.description),typeof c.paramsSchema<"u"&&(i.inputSchema=ce.object(c.paramsSchema)),typeof c.callback<"u"&&(i.callback=c.callback),typeof c.annotations<"u"&&(i.annotations=c.annotations),typeof c.enabled<"u"&&(i.enabled=c.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=i,this.setToolRequestHandlers(),this.sendToolListChanged(),i}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 l=t[0],a={description:r,argsSchema:s===void 0?void 0:ce.object(s),callback:l,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=ce.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 Mr={type:"object"};function jt(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(Lr)}function Lr(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Dr(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function At(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var pe={completion:{values:[],hasMore:!1}};var Nt=process.env.personalToken||""||"",It="F2C MCP",Ot="0.0.1";import{z as g}from"zod";var Ce=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=Nt}async f2cNodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,format:e.format},r=this.opToUrl(`${this.f2cHost}/nodes`,t,[]);return this.fetch(r,"text")}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},s=await fetch(e,r);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return t==="text"?await s.text():await s.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let s=new URL(e);for(let[l,a]of Object.entries(t))r.includes(l)||s.searchParams.append(l,a);return s.toString()}},O=new Ce;var N=new ue({name:It,version:Ot},{capabilities:{logging:{}}});N.tool("figma_to_html","Convert Figma design to HTML code with node",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("List of node IDs to retrieve, comma separated"),format:g.string().default("html").describe("Format of the returned code"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.f2cNodeToCode(o)}]}}catch(e){return console.error("Tool execution error:",e),{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("List of node IDs to retrieve, comma separated"),personalToken:g.string().optional().describe("Your Figma personal access token"),version:g.string().optional().describe("Specify the version to return"),depth:g.number().optional().describe("Specify the depth of nodes to return"),geometry:g.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:g.string().optional().describe("Specify plugin data to return"),branch_data:g.boolean().optional().describe("Specify whether to return branch data")},async o=>{try{return{content:[{type:"text",text:await O.files(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_images","Get images of Figma nodes",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("Node IDs to get images for, comma separated"),format:g.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:g.number().optional().describe("Image scale factor"),svg_include_id:g.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:g.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:g.boolean().optional().describe("Whether to use absolute bounds"),version:g.string().optional().describe("Specify the version to return"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.images(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_image_fills","Get all image resources in the specified Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.imageFills(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_file_meta","Get metadata information for a Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await O.meta(o)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});import Lt from"node:process";var me=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
|
+
]`;continue}s+=r[c],r[c]==="\\"?l=!0:a&&r[c]==="]"?a=!1:!a&&r[c]==="["&&(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`),o.source}return s}function le(o,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"&&o.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,s)=>({...r,[s]:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===D.ZodString&&o.keyType._def.checks?.length){let{type:r,...s}=ie(o.keyType._def,e);return{...t,propertyNames:s}}else{if(o.keyType?._def.typeName===D.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===D.ZodBranded&&o.keyType._def.type._def.typeName===D.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...s}=ae(o.keyType._def,e);return{...t,propertyNames:s}}}return t}function mt(o,e){if(e.mapStrategy==="record")return le(o,e);let t=m(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(o.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(o){let e=o.values,r=Object.keys(o.values).filter(l=>typeof e[e[l]]!="number").map(l=>e[l]),s=Array.from(new Set(r.map(l=>typeof l)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ft(){return{not:{}}}function ht(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var H={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bt(o,e){if(e.target==="openApi3")return gt(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in H&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,l)=>{let a=H[l._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,l)=>{let a=typeof l._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(l._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((l,a,i)=>i.indexOf(l)===a);return{type:s.length>1?s:s[0],enum:t.reduce((l,a)=>l.includes(a._def.value)?l:[...l,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(l=>!r.includes(l))],[])};return gt(o,e)}var gt=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.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 yt(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:H[o.innerType._def.typeName],nullable:!0}:{type:[H[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function _t(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"int":t.type="integer",ve(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as Cr}from"zod";function xt(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],l=o.shape();for(let i in l){let c=l[i];if(c===void 0||c._def===void 0)continue;let _=Er(c);_&&t&&(c instanceof Cr&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),_=!1);let h=m(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});h!==void 0&&(r.properties[i]=h,_||s.push(i))}s.length&&(r.required=s);let a=kr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function kr(o,e){if(o.catchall._def.typeName!=="ZodNever")return m(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Er(o){try{return o.isOptional()}catch{return!0}}var vt=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(o.innerType._def,e);let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var St=(o,e)=>{if(e.pipeStrategy==="input")return m(o.in._def,e);if(e.pipeStrategy==="output")return m(o.out._def,e);let t=m(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Rt(o,e){return m(o.type._def,e)}function Pt(o,e){let r={type:"array",uniqueItems:!0,items:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&f(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&f(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function Tt(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function wt(){return{not:{}}}function Ct(){return{}}var kt=(o,e)=>m(o.innerType._def,e);var Et=(o,e,t)=>{switch(e){case d.ZodString:return ie(o,t);case d.ZodNumber:return _t(o,t);case d.ZodObject:return xt(o,t);case d.ZodBigInt:return ot(o,t);case d.ZodBoolean:return nt();case d.ZodDate:return Se(o,t);case d.ZodUndefined:return wt();case d.ZodNull:return ht(t);case d.ZodArray:return rt(o,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return bt(o,t);case d.ZodIntersection:return ct(o,t);case d.ZodTuple:return Tt(o,t);case d.ZodRecord:return le(o,t);case d.ZodLiteral:return pt(o,t);case d.ZodEnum:return lt(o);case d.ZodNativeEnum:return dt(o);case d.ZodNullable:return yt(o,t);case d.ZodOptional:return vt(o,t);case d.ZodMap:return mt(o,t);case d.ZodSet:return Pt(o,t);case d.ZodLazy:return()=>o.getter()._def;case d.ZodPromise:return Rt(o,t);case d.ZodNaN:case d.ZodNever:return ft();case d.ZodEffects:return it(o,t);case d.ZodAny:return tt();case d.ZodUnknown:return Ct();case d.ZodDefault:return at(o,t);case d.ZodBranded:return ae(o,t);case d.ZodReadonly:return kt(o,t);case d.ZodCatch:return st(o,t);case d.ZodPipeline:return St(o,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(o,e,t=!1){let r=e.seen.get(o);if(e.override){let i=e.override?.(o,e,r,t);if(i!==Ye)return i}if(r&&!t){let i=jr(r,e);if(i!==void 0)return i}let s={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,s);let l=Et(o,o.typeName,e),a=typeof l=="function"?m(l(),e):l;if(a&&Nr(o,e,a),e.postProcess){let i=e.postProcess(a,o,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var jr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:Ar(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.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}},Ar=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},Nr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Te=(o,e)=>{let t=et(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[_,h])=>({...c,[_]:m(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,_]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,l=m(o._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&&(l.title=a);let i=s===void 0?r?{...l,[t.definitionPath]:r}:l:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:l}};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 ce}from"zod";import{ZodType as Or}from"zod";var we;(function(o){o.Completable="McpCompletable"})(we||(we={}));var O=class extends Or{_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}};O.create=(o,e)=>new O({type:o,typeName:we.Completable,complete:e.complete,...Ir(e)});function Ir(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=o;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 c,_;let{message:h}=o;return a.code==="invalid_enum_value"?{message:h??i.defaultError}:typeof i.data>"u"?{message:(c=h??r)!==null&&c!==void 0?c:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(_=h??t)!==null&&_!==void 0?_:i.defaultError}},description:s}}var ue=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 se(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({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}):Mr,annotations:t.annotations}))})),this.server.setRequestHandler(re,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 l=s.data,a=r.callback;try{return await Promise.resolve(a(l,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(l){return{content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,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 pe;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof O))return pe;let a=await s._def.complete(e.params.argument.value);return At(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 pe;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 pe;let l=await s(e.params.argument.value);return At(l)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(G,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([l,a])=>a.enabled).map(([l,a])=>({uri:l,name:a.name,...a.metadata})),s=[];for(let l of Object.values(this._registeredResourceTemplates)){if(!l.resourceTemplate.listCallback)continue;let a=await l.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...l.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(B,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(K,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 l of Object.values(this._registeredResourceTemplates)){let a=l.resourceTemplate.uriTemplate.match(r.toString());if(a)return l.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(X.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(X,()=>({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(W,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 l=s.data,a=r.callback;return await Promise.resolve(a(l,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 l=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:l,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:l,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,l;if(t.length>1){let c=t[0];jt(c)?(s=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!jt(t[0])&&(l=t.shift())):typeof c=="object"&&c!==null&&(l=t.shift())}let a=t[0],i={description:r,inputSchema:s===void 0?void 0:ce.object(s),annotations:l,callback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredTools[e],c.name&&(this._registeredTools[c.name]=i)),typeof c.description<"u"&&(i.description=c.description),typeof c.paramsSchema<"u"&&(i.inputSchema=ce.object(c.paramsSchema)),typeof c.callback<"u"&&(i.callback=c.callback),typeof c.annotations<"u"&&(i.annotations=c.annotations),typeof c.enabled<"u"&&(i.enabled=c.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=i,this.setToolRequestHandlers(),this.sendToolListChanged(),i}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 l=t[0],a={description:r,argsSchema:s===void 0?void 0:ce.object(s),callback:l,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=ce.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 Mr={type:"object"};function jt(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(Lr)}function Lr(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Dr(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function At(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var pe={completion:{values:[],hasMore:!1}};var Nt=process.env.personalToken||""||"",Ot="F2C MCP",It="0.0.1";import{z as g}from"zod";var Ce=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=Nt}async f2cNodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,format:e.format},r=this.opToUrl(`${this.f2cHost}/nodes`,t,[]);return this.fetch(r,"text")}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},s=await fetch(e,r);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return t==="text"?await s.text():await s.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let s=new URL(e);for(let[l,a]of Object.entries(t))r.includes(l)||s.searchParams.append(l,a);return s.toString()}},I=new Ce;var N=new ue({name:Ot,version:It},{capabilities:{logging:{}}});N.tool("figma_to_html","Convert Figma design to HTML code with node",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("List of node IDs to retrieve, comma separated"),format:g.string().default("html").describe("Format of the returned code"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{return{content:[{type:"text",text:await I.f2cNodeToCode(o)}]}}catch(e){return console.error("Tool execution error:",e),{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("List of node IDs to retrieve, comma separated"),personalToken:g.string().optional().describe("Your Figma personal access token"),version:g.string().optional().describe("Specify the version to return"),depth:g.number().optional().describe("Specify the depth of nodes to return"),geometry:g.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:g.string().optional().describe("Specify plugin data to return"),branch_data:g.boolean().optional().describe("Specify whether to return branch data")},async o=>{try{let e=await I.files(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_images","Get images of Figma nodes",{fileKey:g.string().describe("Unique identifier of the Figma file"),ids:g.string().describe("Node IDs to get images for, comma separated"),format:g.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:g.number().optional().describe("Image scale factor"),svg_include_id:g.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:g.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:g.boolean().optional().describe("Whether to use absolute bounds"),version:g.string().optional().describe("Specify the version to return"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.images(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_image_fills","Get all image resources in the specified Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.imageFills(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});N.tool("figma_get_file_meta","Get metadata information for a Figma file",{fileKey:g.string().describe("Unique identifier of the Figma file"),personalToken:g.string().optional().describe("Your Figma personal access token")},async o=>{try{let e=await I.meta(o);return{content:[{type:"text",text:JSON.stringify(e)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}]}}});import Lt from"node:process";var me=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
7
|
`);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(o){return Fe.parse(JSON.parse(o))}function Mt(o){return JSON.stringify(o)+`
|
8
8
|
`}var de=class{constructor(e=Lt.stdin,t=Lt.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new me,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=Mt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};async function Dt(o){let e=new de;await o.connect(e)}Dt(N).catch(o=>{Ae("error",{message:`Server startup failed: ${o.message}`,code:-32e3}),process.exit(1)});
|