@f2c/mcp 0.0.4

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/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # F2C MCP Server
2
+
3
+ The F2C MCP Server is a Model Context Protocol server that enables AI coding assistants to access Figma design data and convert it to HTML/CSS code. Key features:
4
+
5
+ - Provides Figma design context to AI coding tools like Cursor
6
+ - Converts Figma nodes to HTML content with styling
7
+ - Supports Figma file URLs with fileKey and nodeId parameters
8
+ - Uses Figma API to fetch design metadata
9
+ - Implements JSON-RPC 2.0 protocol for communication
10
+
11
+ ## Getting Started
12
+
13
+ 1. Set up your Figma API key in `.env` file:
14
+ ```bash
15
+ FIGMA_API_KEY=your_api_key_here
16
+ ```
17
+
18
+ 2. Install dependencies:
19
+ ```bash
20
+ npm install
21
+ ```
22
+
23
+ 3. Start development server:
24
+ ```bash
25
+ npm run dev
26
+ ```
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var qt=Object.create;var Ae=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty;var Ft=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $t(e))!zt.call(n,s)&&s!==t&&Ae(n,s,{get:()=>e[s],enumerable:!(r=Ht(e,s))||r.enumerable});return n};var Ut=(n,e,t)=>(t=n!=null?qt(Zt(n)):{},Ft(e||!n||!n.__esModule?Ae(t,"default",{value:n,enumerable:!0}):t,n));function k(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}var o=require("zod"),me="2024-11-05",je=[me,"2024-10-07"],L="2.0",Ie=o.z.union([o.z.string(),o.z.number().int()]),Ne=o.z.string(),x=o.z.object({_meta:o.z.optional(o.z.object({progressToken:o.z.optional(Ie)}).passthrough())}).passthrough(),_=o.z.object({method:o.z.string(),params:o.z.optional(x)}),N=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),w=o.z.object({method:o.z.string(),params:o.z.optional(N)}),S=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),D=o.z.union([o.z.string(),o.z.number().int()]),Me=o.z.object({jsonrpc:o.z.literal(L),id:D}).merge(_).strict(),Oe=n=>Me.safeParse(n).success,Le=o.z.object({jsonrpc:o.z.literal(L)}).merge(w).strict(),De=n=>Le.safeParse(n).success,qe=o.z.object({jsonrpc:o.z.literal(L),id:D,result:S}).strict(),de=n=>qe.safeParse(n).success,g;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(g||(g={}));var He=o.z.object({jsonrpc:o.z.literal(L),id:D,error:o.z.object({code:o.z.number().int(),message:o.z.string(),data:o.z.optional(o.z.unknown())})}).strict(),$e=n=>He.safeParse(n).success,Ze=o.z.union([Me,Le,qe,He]),q=S.strict(),H=w.extend({method:o.z.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.z.string().optional()})}),ze=o.z.object({name:o.z.string(),version:o.z.string()}).passthrough(),Vt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),sampling:o.z.optional(o.z.object({}).passthrough()),roots:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),he=_.extend({method:o.z.literal("initialize"),params:x.extend({protocolVersion:o.z.string(),capabilities:Vt,clientInfo:ze})});var Jt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),logging:o.z.optional(o.z.object({}).passthrough()),completions:o.z.optional(o.z.object({}).passthrough()),prompts:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough()),resources:o.z.optional(o.z.object({subscribe:o.z.optional(o.z.boolean()),listChanged:o.z.optional(o.z.boolean())}).passthrough()),tools:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),Bt=S.extend({protocolVersion:o.z.string(),capabilities:Jt,serverInfo:ze,instructions:o.z.optional(o.z.string())}),fe=w.extend({method:o.z.literal("notifications/initialized")});var $=_.extend({method:o.z.literal("ping")}),Gt=o.z.object({progress:o.z.number(),total:o.z.optional(o.z.number())}).passthrough(),Z=w.extend({method:o.z.literal("notifications/progress"),params:N.merge(Gt).extend({progressToken:Ie})}),z=_.extend({params:x.extend({cursor:o.z.optional(Ne)}).optional()}),F=S.extend({nextCursor:o.z.optional(Ne)}),Fe=o.z.object({uri:o.z.string(),mimeType:o.z.optional(o.z.string())}).passthrough(),Ue=Fe.extend({text:o.z.string()}),Ve=Fe.extend({blob:o.z.string().base64()}),Kt=o.z.object({uri:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),Xt=o.z.object({uriTemplate:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),U=z.extend({method:o.z.literal("resources/list")}),Wt=F.extend({resources:o.z.array(Kt)}),V=z.extend({method:o.z.literal("resources/templates/list")}),Yt=F.extend({resourceTemplates:o.z.array(Xt)}),J=_.extend({method:o.z.literal("resources/read"),params:x.extend({uri:o.z.string()})}),Qt=S.extend({contents:o.z.array(o.z.union([Ue,Ve]))}),er=w.extend({method:o.z.literal("notifications/resources/list_changed")}),tr=_.extend({method:o.z.literal("resources/subscribe"),params:x.extend({uri:o.z.string()})}),rr=_.extend({method:o.z.literal("resources/unsubscribe"),params:x.extend({uri:o.z.string()})}),nr=w.extend({method:o.z.literal("notifications/resources/updated"),params:N.extend({uri:o.z.string()})}),or=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),required:o.z.optional(o.z.boolean())}).passthrough(),sr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),arguments:o.z.optional(o.z.array(or))}).passthrough(),B=z.extend({method:o.z.literal("prompts/list")}),ar=F.extend({prompts:o.z.array(sr)}),G=_.extend({method:o.z.literal("prompts/get"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.string()))})}),K=o.z.object({type:o.z.literal("text"),text:o.z.string()}).passthrough(),X=o.z.object({type:o.z.literal("image"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),W=o.z.object({type:o.z.literal("audio"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),Je=o.z.object({type:o.z.literal("resource"),resource:o.z.union([Ue,Ve])}).passthrough(),ir=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W,Je])}).passthrough(),cr=S.extend({description:o.z.optional(o.z.string()),messages:o.z.array(ir)}),lr=w.extend({method:o.z.literal("notifications/prompts/list_changed")}),pr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),inputSchema:o.z.object({type:o.z.literal("object"),properties:o.z.optional(o.z.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.z.literal("tools/list")}),ur=F.extend({tools:o.z.array(pr)}),Be=S.extend({content:o.z.array(o.z.union([K,X,W,Je])),isError:o.z.boolean().default(!1).optional()}),zr=Be.or(S.extend({toolResult:o.z.unknown()})),Q=_.extend({method:o.z.literal("tools/call"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.unknown()))})}),mr=w.extend({method:o.z.literal("notifications/tools/list_changed")}),Ge=o.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=_.extend({method:o.z.literal("logging/setLevel"),params:x.extend({level:Ge})}),hr=w.extend({method:o.z.literal("notifications/message"),params:N.extend({level:Ge,logger:o.z.optional(o.z.string()),data:o.z.unknown()})}),fr=o.z.object({name:o.z.string().optional()}).passthrough(),gr=o.z.object({hints:o.z.optional(o.z.array(fr)),costPriority:o.z.optional(o.z.number().min(0).max(1)),speedPriority:o.z.optional(o.z.number().min(0).max(1)),intelligencePriority:o.z.optional(o.z.number().min(0).max(1))}).passthrough(),br=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W])}).passthrough(),yr=_.extend({method:o.z.literal("sampling/createMessage"),params:x.extend({messages:o.z.array(br),systemPrompt:o.z.optional(o.z.string()),includeContext:o.z.optional(o.z.enum(["none","thisServer","allServers"])),temperature:o.z.optional(o.z.number()),maxTokens:o.z.number().int(),stopSequences:o.z.optional(o.z.array(o.z.string())),metadata:o.z.optional(o.z.object({}).passthrough()),modelPreferences:o.z.optional(gr)})}),ge=S.extend({model:o.z.string(),stopReason:o.z.optional(o.z.enum(["endTurn","stopSequence","maxTokens"]).or(o.z.string())),role:o.z.enum(["user","assistant"]),content:o.z.discriminatedUnion("type",[K,X,W])}),_r=o.z.object({type:o.z.literal("ref/resource"),uri:o.z.string()}).passthrough(),vr=o.z.object({type:o.z.literal("ref/prompt"),name:o.z.string()}).passthrough(),ee=_.extend({method:o.z.literal("completion/complete"),params:x.extend({ref:o.z.union([vr,_r]),argument:o.z.object({name:o.z.string(),value:o.z.string()}).passthrough()})}),xr=S.extend({completion:o.z.object({values:o.z.array(o.z.string()).max(100),total:o.z.optional(o.z.number().int()),hasMore:o.z.optional(o.z.boolean())}).passthrough()}),Sr=o.z.object({uri:o.z.string().startsWith("file://"),name:o.z.optional(o.z.string())}).passthrough(),Rr=_.extend({method:o.z.literal("roots/list")}),be=S.extend({roots:o.z.array(Sr)}),Pr=w.extend({method:o.z.literal("notifications/roots/list_changed")}),Fr=o.z.union([$,he,ee,dr,G,B,U,V,J,tr,rr,Q,Y]),Ur=o.z.union([H,Z,fe,Pr]),Vr=o.z.union([q,ge,be]),Jr=o.z.union([$,yr,Rr]),Br=o.z.union([H,Z,hr,nr,er,mr,lr]),Gr=o.z.union([q,Bt,xr,cr,ar,Wt,Yt,Qt,Be,ur]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Tr=6e4,te=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new b(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{de(t)||$e(t)?this._onresponse(t):Oe(t)?this._onrequest(t,r):De(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new b(g.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:g.MethodNotFound,message:"Method not found"}}).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,f,C)=>this.request(h,f,{...C,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(h=>{var f;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var f,C;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(C=h.message)!==null&&C!==void 0?C:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),de(e))r(e);else{let s=new b(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var h,f,C,pe,ue;if(!this._transport){l(new Error("Not connected"));return}((h=this._options)===null||h===void 0?void 0:h.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let T=this._requestMessageId++,Ce={...e,jsonrpc:"2.0",id:T};r?.onprogress&&(this._progressHandlers.set(T,r.onprogress),Ce.params={...e.params,_meta:{progressToken:T}});let ke=v=>{var E;this._responseHandlers.delete(T),this._progressHandlers.delete(T),this._cleanupTimeout(T),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:T,reason:String(v)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(v)};this._responseHandlers.set(T,v=>{var E;if(!(!((E=r?.signal)===null||E===void 0)&&E.aborted)){if(v instanceof Error)return l(v);try{let I=t.parse(v.result);i(I)}catch(I){l(I)}}}),(C=r?.signal)===null||C===void 0||C.addEventListener("abort",()=>{var v;ke((v=r?.signal)===null||v===void 0?void 0:v.reason)});let Ee=(pe=r?.timeout)!==null&&pe!==void 0?pe:Tr,Dt=()=>ke(new b(g.RequestTimeout,"Request timed out",{timeout:Ee}));this._setupTimeout(T,Ee,r?.maxTotalTimeout,Dt,(ue=r?.resetTimeoutOnProgress)!==null&&ue!==void 0?ue:!1),this._transport.send(Ce,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(T),l(v)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ke(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(he,s=>this._oninitialize(s)),this.setNotificationHandler(fe,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ke(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:je.includes(t)?t:me,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},ge,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},be,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var We=Symbol("Let zodToJsonSchema decide on which parser to use");var Xe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Ye=n=>typeof n=="string"?{...Xe,name:n}:{...Xe,...n};var Qe=n=>{let e=Ye(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function ye(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function d(n,e,t,r,s){n[e]=t,ye(n,e,r,s)}var m=require("zod");function et(){return{}}var tt=require("zod");function rt(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==tt.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&d(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&d(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(d(t,"minItems",n.exactLength.value,n.exactLength.message,e),d(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function nt(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}function ot(){return{type:"boolean"}}function ne(n,e){return u(n.type._def,e)}var st=(n,e)=>u(n.innerType._def,e);function _e(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>_e(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return wr(n,e)}}var wr=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":d(t,"minimum",r.value,r.message,e);break;case"max":d(t,"maximum",r.value,r.message,e);break}return t};function at(n,e){return{...u(n.innerType._def,e),default:n.defaultValue()}}function it(n,e){return e.effectStrategy==="input"?u(n.schema._def,e):{}}function ct(n){return{type:"string",enum:Array.from(n.values)}}var Cr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function lt(n,e){let t=[u(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(Cr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function pt(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}var A=require("zod");var ve,R={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ve===void 0&&(ve=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ve),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":P(t,"email",r.message,e);break;case"format:idn-email":P(t,"idn-email",r.message,e);break;case"pattern:zod":y(t,R.email,r.message,e);break}break;case"url":P(t,"uri",r.message,e);break;case"uuid":P(t,"uuid",r.message,e);break;case"regex":y(t,r.regex,r.message,e);break;case"cuid":y(t,R.cuid,r.message,e);break;case"cuid2":y(t,R.cuid2,r.message,e);break;case"startsWith":y(t,RegExp(`^${xe(r.value,e)}`),r.message,e);break;case"endsWith":y(t,RegExp(`${xe(r.value,e)}$`),r.message,e);break;case"datetime":P(t,"date-time",r.message,e);break;case"date":P(t,"date",r.message,e);break;case"time":P(t,"time",r.message,e);break;case"duration":P(t,"duration",r.message,e);break;case"length":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{y(t,RegExp(xe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&P(t,"ipv4",r.message,e),r.version!=="v4"&&P(t,"ipv6",r.message,e);break}case"base64url":y(t,R.base64url,r.message,e);break;case"jwt":y(t,R.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&y(t,R.ipv4Cidr,r.message,e),r.version!=="v4"&&y(t,R.ipv6Cidr,r.message,e);break}case"emoji":y(t,R.emoji(),r.message,e);break;case"ulid":{y(t,R.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{P(t,"binary",r.message,e);break}case"contentEncoding:base64":{d(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{y(t,R.base64,r.message,e);break}}break}case"nanoid":y(t,R.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function xe(n,e){return e.patternStrategy==="escape"?Er(n):n}var kr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Er(n){let e="";for(let t=0;t<n.length;t++)kr.has(n[t])||(e+="\\"),e+=n[t];return e}function P(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(n,"format",e,t,r)}function y(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ut(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(n,"pattern",ut(e,r),t,r)}function ut(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
3
+ ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
4
+ ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
5
+ `:`[${r[l]}\r
6
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return s}function se(n,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodBranded&&n.keyType._def.type._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function mt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=u(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function dt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ht(){return{not:{}}}function ft(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var M={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bt(n,e){if(e.target==="openApi3")return gt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in M&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=M[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return gt(n,e)}var gt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>u(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function yt(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:M[n.innerType._def.typeName],nullable:!0}:{type:[M[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function _t(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",ye(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}var vt=require("zod");function xt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let h=jr(l);h&&t&&(l instanceof vt.ZodOptional&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),h=!1);let f=u(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,h||s.push(i))}s.length&&(r.required=s);let a=Ar(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Ar(n,e){if(n.catchall._def.typeName!=="ZodNever")return u(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function jr(n){try{return n.isOptional()}catch{return!0}}var St=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(n.innerType._def,e);let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Rt=(n,e)=>{if(e.pipeStrategy==="input")return u(n.in._def,e);if(e.pipeStrategy==="output")return u(n.out._def,e);let t=u(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Pt(n,e){return u(n.type._def,e)}function Tt(n,e){let r={type:"array",uniqueItems:!0,items:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&d(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&d(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function wt(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Ct(){return{not:{}}}function kt(){return{}}var Et=(n,e)=>u(n.innerType._def,e);var At=(n,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return oe(n,t);case m.ZodFirstPartyTypeKind.ZodNumber:return _t(n,t);case m.ZodFirstPartyTypeKind.ZodObject:return xt(n,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return nt(n,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return ot();case m.ZodFirstPartyTypeKind.ZodDate:return _e(n,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return Ct();case m.ZodFirstPartyTypeKind.ZodNull:return ft(t);case m.ZodFirstPartyTypeKind.ZodArray:return rt(n,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return bt(n,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return lt(n,t);case m.ZodFirstPartyTypeKind.ZodTuple:return wt(n,t);case m.ZodFirstPartyTypeKind.ZodRecord:return se(n,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return pt(n,t);case m.ZodFirstPartyTypeKind.ZodEnum:return ct(n);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return dt(n);case m.ZodFirstPartyTypeKind.ZodNullable:return yt(n,t);case m.ZodFirstPartyTypeKind.ZodOptional:return St(n,t);case m.ZodFirstPartyTypeKind.ZodMap:return mt(n,t);case m.ZodFirstPartyTypeKind.ZodSet:return Tt(n,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>n.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return Pt(n,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return ht();case m.ZodFirstPartyTypeKind.ZodEffects:return it(n,t);case m.ZodFirstPartyTypeKind.ZodAny:return et();case m.ZodFirstPartyTypeKind.ZodUnknown:return kt();case m.ZodFirstPartyTypeKind.ZodDefault:return at(n,t);case m.ZodFirstPartyTypeKind.ZodBranded:return ne(n,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return Et(n,t);case m.ZodFirstPartyTypeKind.ZodCatch:return st(n,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Rt(n,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==We)return i}if(r&&!t){let i=Ir(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=At(n,n.typeName,e),a=typeof c=="function"?u(c(),e):c;if(a&&Mr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Ir=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Nr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Nr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Mr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Se=(n,e)=>{let t=Qe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[h,f])=>({...l,[h]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=u(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var O=require("zod");var jt=require("zod"),Re;(function(n){n.Completable="McpCompletable"})(Re||(Re={}));var j=class extends jt.ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Re.Completable,complete:e.complete,...Or(e)});function Or(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,h;let{message:f}=n;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(l=f??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(h=f??t)!==null&&h!==void 0?h:i.defaultError}},description:s}}var ie=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Se(t.inputSchema,{strictUnions:!0}):Lr}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new b(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new b(g.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new b(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ae;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ae;let a=await s._def.complete(e.params.argument.value);return It(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ae;throw new b(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ae;let c=await s(e.params.argument.value);return It(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new b(g.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Dr(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new b(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=O.z.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=O.z.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Lr={type:"object"};function Dr(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function It(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ae={completion:{values:[],hasMore:!1}};var Pe=Ut(require("process"),1);var ce=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
7
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),qr(t)}clear(){this._buffer=void 0}};function qr(n){return Ze.parse(JSON.parse(n))}function Nt(n){return JSON.stringify(n)+`
8
+ `}var le=class{constructor(e=Pe.default.stdin,t=Pe.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ce,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=Nt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};var we=require("zod");var Te=process.env.personalToken||""||"";function Mt(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var Ot=new ie({name:"F2C MCP",version:"0.0.1"});k("notification",{message:"MCP server instance created"});Ot.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:we.z.string().default(Te).describe("Your Figma personal access token"),figmaUrl:we.z.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{k("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=Mt(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return k("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Lt(){k("notification",{message:"Starting Figma-to-HTML service"});let n=new le;k("notification",{message:"Transport layer initialized"}),await Ot.connect(n),k("notification",{message:"MCP server connected to stdio"})}Lt().catch(n=>{k("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
package/dist/cli.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ function E(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}import{z as o}from"zod";var de="2024-11-05",Ee=[de,"2024-10-07"],L="2.0",Ae=o.union([o.string(),o.number().int()]),je=o.string(),S=o.object({_meta:o.optional(o.object({progressToken:o.optional(Ae)}).passthrough())}).passthrough(),v=o.object({method:o.string(),params:o.optional(S)}),N=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),C=o.object({method:o.string(),params:o.optional(N)}),R=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),D=o.union([o.string(),o.number().int()]),Ie=o.object({jsonrpc:o.literal(L),id:D}).merge(v).strict(),Ne=n=>Ie.safeParse(n).success,Me=o.object({jsonrpc:o.literal(L)}).merge(C).strict(),Oe=n=>Me.safeParse(n).success,Le=o.object({jsonrpc:o.literal(L),id:D,result:R}).strict(),he=n=>Le.safeParse(n).success,b;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(b||(b={}));var De=o.object({jsonrpc:o.literal(L),id:D,error:o.object({code:o.number().int(),message:o.string(),data:o.optional(o.unknown())})}).strict(),qe=n=>De.safeParse(n).success,He=o.union([Ie,Me,Le,De]),q=R.strict(),H=C.extend({method:o.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.string().optional()})}),$e=o.object({name:o.string(),version:o.string()}).passthrough(),Ot=o.object({experimental:o.optional(o.object({}).passthrough()),sampling:o.optional(o.object({}).passthrough()),roots:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),fe=v.extend({method:o.literal("initialize"),params:S.extend({protocolVersion:o.string(),capabilities:Ot,clientInfo:$e})});var Lt=o.object({experimental:o.optional(o.object({}).passthrough()),logging:o.optional(o.object({}).passthrough()),completions:o.optional(o.object({}).passthrough()),prompts:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough()),resources:o.optional(o.object({subscribe:o.optional(o.boolean()),listChanged:o.optional(o.boolean())}).passthrough()),tools:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),Dt=R.extend({protocolVersion:o.string(),capabilities:Lt,serverInfo:$e,instructions:o.optional(o.string())}),ge=C.extend({method:o.literal("notifications/initialized")});var $=v.extend({method:o.literal("ping")}),qt=o.object({progress:o.number(),total:o.optional(o.number())}).passthrough(),Z=C.extend({method:o.literal("notifications/progress"),params:N.merge(qt).extend({progressToken:Ae})}),z=v.extend({params:S.extend({cursor:o.optional(je)}).optional()}),F=R.extend({nextCursor:o.optional(je)}),Ze=o.object({uri:o.string(),mimeType:o.optional(o.string())}).passthrough(),ze=Ze.extend({text:o.string()}),Fe=Ze.extend({blob:o.string().base64()}),Ht=o.object({uri:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),$t=o.object({uriTemplate:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),U=z.extend({method:o.literal("resources/list")}),Zt=F.extend({resources:o.array(Ht)}),V=z.extend({method:o.literal("resources/templates/list")}),zt=F.extend({resourceTemplates:o.array($t)}),J=v.extend({method:o.literal("resources/read"),params:S.extend({uri:o.string()})}),Ft=R.extend({contents:o.array(o.union([ze,Fe]))}),Ut=C.extend({method:o.literal("notifications/resources/list_changed")}),Vt=v.extend({method:o.literal("resources/subscribe"),params:S.extend({uri:o.string()})}),Jt=v.extend({method:o.literal("resources/unsubscribe"),params:S.extend({uri:o.string()})}),Bt=C.extend({method:o.literal("notifications/resources/updated"),params:N.extend({uri:o.string()})}),Gt=o.object({name:o.string(),description:o.optional(o.string()),required:o.optional(o.boolean())}).passthrough(),Kt=o.object({name:o.string(),description:o.optional(o.string()),arguments:o.optional(o.array(Gt))}).passthrough(),B=z.extend({method:o.literal("prompts/list")}),Xt=F.extend({prompts:o.array(Kt)}),G=v.extend({method:o.literal("prompts/get"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.string()))})}),K=o.object({type:o.literal("text"),text:o.string()}).passthrough(),X=o.object({type:o.literal("image"),data:o.string().base64(),mimeType:o.string()}).passthrough(),W=o.object({type:o.literal("audio"),data:o.string().base64(),mimeType:o.string()}).passthrough(),Ue=o.object({type:o.literal("resource"),resource:o.union([ze,Fe])}).passthrough(),Wt=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W,Ue])}).passthrough(),Yt=R.extend({description:o.optional(o.string()),messages:o.array(Wt)}),Qt=C.extend({method:o.literal("notifications/prompts/list_changed")}),er=o.object({name:o.string(),description:o.optional(o.string()),inputSchema:o.object({type:o.literal("object"),properties:o.optional(o.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.literal("tools/list")}),tr=F.extend({tools:o.array(er)}),Ve=R.extend({content:o.array(o.union([K,X,W,Ue])),isError:o.boolean().default(!1).optional()}),Or=Ve.or(R.extend({toolResult:o.unknown()})),Q=v.extend({method:o.literal("tools/call"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.unknown()))})}),rr=C.extend({method:o.literal("notifications/tools/list_changed")}),Je=o.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),nr=v.extend({method:o.literal("logging/setLevel"),params:S.extend({level:Je})}),or=C.extend({method:o.literal("notifications/message"),params:N.extend({level:Je,logger:o.optional(o.string()),data:o.unknown()})}),sr=o.object({name:o.string().optional()}).passthrough(),ar=o.object({hints:o.optional(o.array(sr)),costPriority:o.optional(o.number().min(0).max(1)),speedPriority:o.optional(o.number().min(0).max(1)),intelligencePriority:o.optional(o.number().min(0).max(1))}).passthrough(),ir=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W])}).passthrough(),cr=v.extend({method:o.literal("sampling/createMessage"),params:S.extend({messages:o.array(ir),systemPrompt:o.optional(o.string()),includeContext:o.optional(o.enum(["none","thisServer","allServers"])),temperature:o.optional(o.number()),maxTokens:o.number().int(),stopSequences:o.optional(o.array(o.string())),metadata:o.optional(o.object({}).passthrough()),modelPreferences:o.optional(ar)})}),be=R.extend({model:o.string(),stopReason:o.optional(o.enum(["endTurn","stopSequence","maxTokens"]).or(o.string())),role:o.enum(["user","assistant"]),content:o.discriminatedUnion("type",[K,X,W])}),lr=o.object({type:o.literal("ref/resource"),uri:o.string()}).passthrough(),pr=o.object({type:o.literal("ref/prompt"),name:o.string()}).passthrough(),ee=v.extend({method:o.literal("completion/complete"),params:S.extend({ref:o.union([pr,lr]),argument:o.object({name:o.string(),value:o.string()}).passthrough()})}),ur=R.extend({completion:o.object({values:o.array(o.string()).max(100),total:o.optional(o.number().int()),hasMore:o.optional(o.boolean())}).passthrough()}),mr=o.object({uri:o.string().startsWith("file://"),name:o.optional(o.string())}).passthrough(),dr=v.extend({method:o.literal("roots/list")}),ye=R.extend({roots:o.array(mr)}),hr=C.extend({method:o.literal("notifications/roots/list_changed")}),Lr=o.union([$,fe,ee,nr,G,B,U,V,J,Vt,Jt,Q,Y]),Dr=o.union([H,Z,ge,hr]),qr=o.union([q,be,ye]),Hr=o.union([$,cr,dr]),$r=o.union([H,Z,or,Bt,Ut,rr,Qt]),Zr=o.union([q,Dt,ur,Yt,Xt,Zt,zt,Ft,Ve,tr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var fr=6e4,te=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new y(b.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{he(t)||qe(t)?this._onresponse(t):Ne(t)?this._onrequest(t,r):Oe(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new y(b.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:b.MethodNotFound,message:"Method not found"}}).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,g,k)=>this.request(f,g,{...k,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(f=>{var g;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var g,k;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:b.InternalError,message:(k=f.message)!==null&&k!==void 0?k:"Internal error"}})}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),he(e))r(e);else{let s=new y(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var f,g,k,ue,me;if(!this._transport){l(new Error("Not connected"));return}((f=this._options)===null||f===void 0?void 0:f.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(g=r?.signal)===null||g===void 0||g.throwIfAborted();let w=this._requestMessageId++,we={...e,jsonrpc:"2.0",id:w};r?.onprogress&&(this._progressHandlers.set(w,r.onprogress),we.params={...e.params,_meta:{progressToken:w}});let Ce=x=>{var A;this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(x)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(x)};this._responseHandlers.set(w,x=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(x instanceof Error)return l(x);try{let I=t.parse(x.result);i(I)}catch(I){l(I)}}}),(k=r?.signal)===null||k===void 0||k.addEventListener("abort",()=>{var x;Ce((x=r?.signal)===null||x===void 0?void 0:x.reason)});let ke=(ue=r?.timeout)!==null&&ue!==void 0?ue:fr,Mt=()=>Ce(new y(b.RequestTimeout,"Request timed out",{timeout:ke}));this._setupTimeout(w,ke,r?.maxTotalTimeout,Mt,(me=r?.resetTimeoutOnProgress)!==null&&me!==void 0?me:!1),this._transport.send(we,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(w),l(x)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Be(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(fe,s=>this._oninitialize(s)),this.setNotificationHandler(ge,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Be(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ee.includes(t)?t:de,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},be,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},ye,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ke=Symbol("Let zodToJsonSchema decide on which parser to use");var Ge={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Xe=n=>typeof n=="string"?{...Ge,name:n}:{...Ge,...n};var We=n=>{let e=Xe(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function _e(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function h(n,e,t,r,s){n[e]=t,_e(n,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function Ye(){return{}}import{ZodFirstPartyTypeKind as gr}from"zod";function Qe(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==gr.ZodAny&&(t.items=m(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&h(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&h(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(h(t,"minItems",n.exactLength.value,n.exactLength.message,e),h(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function et(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}function tt(){return{type:"boolean"}}function ne(n,e){return m(n.type._def,e)}var rt=(n,e)=>m(n.innerType._def,e);function ve(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>ve(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return br(n,e)}}var br=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":h(t,"minimum",r.value,r.message,e);break;case"max":h(t,"maximum",r.value,r.message,e);break}return t};function nt(n,e){return{...m(n.innerType._def,e),default:n.defaultValue()}}function ot(n,e){return e.effectStrategy==="input"?m(n.schema._def,e):{}}function st(n){return{type:"string",enum:Array.from(n.values)}}var yr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function at(n,e){let t=[m(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(yr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function it(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}import{ZodFirstPartyTypeKind as M}from"zod";var xe,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(xe===void 0&&(xe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xe),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":T(t,"email",r.message,e);break;case"format:idn-email":T(t,"idn-email",r.message,e);break;case"pattern:zod":_(t,P.email,r.message,e);break}break;case"url":T(t,"uri",r.message,e);break;case"uuid":T(t,"uuid",r.message,e);break;case"regex":_(t,r.regex,r.message,e);break;case"cuid":_(t,P.cuid,r.message,e);break;case"cuid2":_(t,P.cuid2,r.message,e);break;case"startsWith":_(t,RegExp(`^${Se(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Se(r.value,e)}$`),r.message,e);break;case"datetime":T(t,"date-time",r.message,e);break;case"date":T(t,"date",r.message,e);break;case"time":T(t,"time",r.message,e);break;case"duration":T(t,"duration",r.message,e);break;case"length":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{_(t,RegExp(Se(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&T(t,"ipv4",r.message,e),r.version!=="v4"&&T(t,"ipv6",r.message,e);break}case"base64url":_(t,P.base64url,r.message,e);break;case"jwt":_(t,P.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&_(t,P.ipv4Cidr,r.message,e),r.version!=="v4"&&_(t,P.ipv6Cidr,r.message,e);break}case"emoji":_(t,P.emoji(),r.message,e);break;case"ulid":{_(t,P.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{T(t,"binary",r.message,e);break}case"contentEncoding:base64":{h(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{_(t,P.base64,r.message,e);break}}break}case"nanoid":_(t,P.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Se(n,e){return e.patternStrategy==="escape"?vr(n):n}var _r=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vr(n){let e="";for(let t=0;t<n.length;t++)_r.has(n[t])||(e+="\\"),e+=n[t];return e}function T(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):h(n,"format",e,t,r)}function _(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ct(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):h(n,"pattern",ct(e,r),t,r)}function ct(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
3
+ ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
4
+ ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
5
+ `:`[${r[l]}\r
6
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return s}function se(n,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&n.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===M.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===M.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===M.ZodBranded&&n.keyType._def.type._def.typeName===M.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function lt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=m(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function pt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ut(){return{not:{}}}function mt(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ht(n,e){if(e.target==="openApi3")return dt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in O&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=O[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return dt(n,e)}var dt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function ft(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:O[n.innerType._def.typeName],nullable:!0}:{type:[O[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function gt(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",_e(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as xr}from"zod";function bt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let f=Rr(l);f&&t&&(l instanceof xr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),f=!1);let g=m(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});g!==void 0&&(r.properties[i]=g,f||s.push(i))}s.length&&(r.required=s);let a=Sr(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Sr(n,e){if(n.catchall._def.typeName!=="ZodNever")return m(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Rr(n){try{return n.isOptional()}catch{return!0}}var yt=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(n.innerType._def,e);let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var _t=(n,e)=>{if(e.pipeStrategy==="input")return m(n.in._def,e);if(e.pipeStrategy==="output")return m(n.out._def,e);let t=m(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function vt(n,e){return m(n.type._def,e)}function xt(n,e){let r={type:"array",uniqueItems:!0,items:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&h(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&h(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function St(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Rt(){return{not:{}}}function Pt(){return{}}var Tt=(n,e)=>m(n.innerType._def,e);var wt=(n,e,t)=>{switch(e){case d.ZodString:return oe(n,t);case d.ZodNumber:return gt(n,t);case d.ZodObject:return bt(n,t);case d.ZodBigInt:return et(n,t);case d.ZodBoolean:return tt();case d.ZodDate:return ve(n,t);case d.ZodUndefined:return Rt();case d.ZodNull:return mt(t);case d.ZodArray:return Qe(n,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return ht(n,t);case d.ZodIntersection:return at(n,t);case d.ZodTuple:return St(n,t);case d.ZodRecord:return se(n,t);case d.ZodLiteral:return it(n,t);case d.ZodEnum:return st(n);case d.ZodNativeEnum:return pt(n);case d.ZodNullable:return ft(n,t);case d.ZodOptional:return yt(n,t);case d.ZodMap:return lt(n,t);case d.ZodSet:return xt(n,t);case d.ZodLazy:return()=>n.getter()._def;case d.ZodPromise:return vt(n,t);case d.ZodNaN:case d.ZodNever:return ut();case d.ZodEffects:return ot(n,t);case d.ZodAny:return Ye();case d.ZodUnknown:return Pt();case d.ZodDefault:return nt(n,t);case d.ZodBranded:return ne(n,t);case d.ZodReadonly:return Tt(n,t);case d.ZodCatch:return rt(n,t);case d.ZodPipeline:return _t(n,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==Ke)return i}if(r&&!t){let i=Pr(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=wt(n,n.typeName,e),a=typeof c=="function"?m(c(),e):c;if(a&&wr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Pr=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Tr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Tr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},wr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Re=(n,e)=>{let t=We(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[f,g])=>({...l,[f]:m(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=m(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};import{z as ae}from"zod";import{ZodType as Cr}from"zod";var Pe;(function(n){n.Completable="McpCompletable"})(Pe||(Pe={}));var j=class extends Cr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Pe.Completable,complete:e.complete,...kr(e)});function kr(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,f;let{message:g}=n;return a.code==="invalid_enum_value"?{message:g??i.defaultError}:typeof i.data>"u"?{message:(l=g??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(f=g??t)!==null&&f!==void 0?f:i.defaultError}},description:s}}var ce=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Re(t.inputSchema,{strictUnions:!0}):Er}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(b.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(b.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new y(b.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ie;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ie;let a=await s._def.complete(e.params.argument.value);return Ct(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ie;throw new y(b.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ie;let c=await s(e.params.argument.value);return Ct(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new y(b.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ar(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(b.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=ae.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=ae.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Er={type:"object"};function Ar(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Ct(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ie={completion:{values:[],hasMore:!1}};import Et from"node:process";var le=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
7
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),jr(t)}clear(){this._buffer=void 0}};function jr(n){return He.parse(JSON.parse(n))}function kt(n){return JSON.stringify(n)+`
8
+ `}var pe=class{constructor(e=Et.stdin,t=Et.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new le,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=kt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};import{z as jt}from"zod";var Te=process.env.personalToken||""||"";function At(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var It=new ce({name:"F2C MCP",version:"0.0.1"});E("notification",{message:"MCP server instance created"});It.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:jt.string().default(Te).describe("Your Figma personal access token"),figmaUrl:jt.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{E("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=At(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return E("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Nt(){E("notification",{message:"Starting Figma-to-HTML service"});let n=new pe;E("notification",{message:"Transport layer initialized"}),await It.connect(n),E("notification",{message:"MCP server connected to stdio"})}Nt().catch(n=>{E("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";var qt=Object.create;var Ae=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty;var Ft=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $t(e))!zt.call(n,s)&&s!==t&&Ae(n,s,{get:()=>e[s],enumerable:!(r=Ht(e,s))||r.enumerable});return n};var Ut=(n,e,t)=>(t=n!=null?qt(Zt(n)):{},Ft(e||!n||!n.__esModule?Ae(t,"default",{value:n,enumerable:!0}):t,n));function k(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}var o=require("zod"),me="2024-11-05",je=[me,"2024-10-07"],L="2.0",Ie=o.z.union([o.z.string(),o.z.number().int()]),Ne=o.z.string(),x=o.z.object({_meta:o.z.optional(o.z.object({progressToken:o.z.optional(Ie)}).passthrough())}).passthrough(),_=o.z.object({method:o.z.string(),params:o.z.optional(x)}),N=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),w=o.z.object({method:o.z.string(),params:o.z.optional(N)}),S=o.z.object({_meta:o.z.optional(o.z.object({}).passthrough())}).passthrough(),D=o.z.union([o.z.string(),o.z.number().int()]),Me=o.z.object({jsonrpc:o.z.literal(L),id:D}).merge(_).strict(),Oe=n=>Me.safeParse(n).success,Le=o.z.object({jsonrpc:o.z.literal(L)}).merge(w).strict(),De=n=>Le.safeParse(n).success,qe=o.z.object({jsonrpc:o.z.literal(L),id:D,result:S}).strict(),de=n=>qe.safeParse(n).success,g;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(g||(g={}));var He=o.z.object({jsonrpc:o.z.literal(L),id:D,error:o.z.object({code:o.z.number().int(),message:o.z.string(),data:o.z.optional(o.z.unknown())})}).strict(),$e=n=>He.safeParse(n).success,Ze=o.z.union([Me,Le,qe,He]),q=S.strict(),H=w.extend({method:o.z.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.z.string().optional()})}),ze=o.z.object({name:o.z.string(),version:o.z.string()}).passthrough(),Vt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),sampling:o.z.optional(o.z.object({}).passthrough()),roots:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),he=_.extend({method:o.z.literal("initialize"),params:x.extend({protocolVersion:o.z.string(),capabilities:Vt,clientInfo:ze})});var Jt=o.z.object({experimental:o.z.optional(o.z.object({}).passthrough()),logging:o.z.optional(o.z.object({}).passthrough()),completions:o.z.optional(o.z.object({}).passthrough()),prompts:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough()),resources:o.z.optional(o.z.object({subscribe:o.z.optional(o.z.boolean()),listChanged:o.z.optional(o.z.boolean())}).passthrough()),tools:o.z.optional(o.z.object({listChanged:o.z.optional(o.z.boolean())}).passthrough())}).passthrough(),Bt=S.extend({protocolVersion:o.z.string(),capabilities:Jt,serverInfo:ze,instructions:o.z.optional(o.z.string())}),fe=w.extend({method:o.z.literal("notifications/initialized")});var $=_.extend({method:o.z.literal("ping")}),Gt=o.z.object({progress:o.z.number(),total:o.z.optional(o.z.number())}).passthrough(),Z=w.extend({method:o.z.literal("notifications/progress"),params:N.merge(Gt).extend({progressToken:Ie})}),z=_.extend({params:x.extend({cursor:o.z.optional(Ne)}).optional()}),F=S.extend({nextCursor:o.z.optional(Ne)}),Fe=o.z.object({uri:o.z.string(),mimeType:o.z.optional(o.z.string())}).passthrough(),Ue=Fe.extend({text:o.z.string()}),Ve=Fe.extend({blob:o.z.string().base64()}),Kt=o.z.object({uri:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),Xt=o.z.object({uriTemplate:o.z.string(),name:o.z.string(),description:o.z.optional(o.z.string()),mimeType:o.z.optional(o.z.string())}).passthrough(),U=z.extend({method:o.z.literal("resources/list")}),Wt=F.extend({resources:o.z.array(Kt)}),V=z.extend({method:o.z.literal("resources/templates/list")}),Yt=F.extend({resourceTemplates:o.z.array(Xt)}),J=_.extend({method:o.z.literal("resources/read"),params:x.extend({uri:o.z.string()})}),Qt=S.extend({contents:o.z.array(o.z.union([Ue,Ve]))}),er=w.extend({method:o.z.literal("notifications/resources/list_changed")}),tr=_.extend({method:o.z.literal("resources/subscribe"),params:x.extend({uri:o.z.string()})}),rr=_.extend({method:o.z.literal("resources/unsubscribe"),params:x.extend({uri:o.z.string()})}),nr=w.extend({method:o.z.literal("notifications/resources/updated"),params:N.extend({uri:o.z.string()})}),or=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),required:o.z.optional(o.z.boolean())}).passthrough(),sr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),arguments:o.z.optional(o.z.array(or))}).passthrough(),B=z.extend({method:o.z.literal("prompts/list")}),ar=F.extend({prompts:o.z.array(sr)}),G=_.extend({method:o.z.literal("prompts/get"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.string()))})}),K=o.z.object({type:o.z.literal("text"),text:o.z.string()}).passthrough(),X=o.z.object({type:o.z.literal("image"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),W=o.z.object({type:o.z.literal("audio"),data:o.z.string().base64(),mimeType:o.z.string()}).passthrough(),Je=o.z.object({type:o.z.literal("resource"),resource:o.z.union([Ue,Ve])}).passthrough(),ir=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W,Je])}).passthrough(),cr=S.extend({description:o.z.optional(o.z.string()),messages:o.z.array(ir)}),lr=w.extend({method:o.z.literal("notifications/prompts/list_changed")}),pr=o.z.object({name:o.z.string(),description:o.z.optional(o.z.string()),inputSchema:o.z.object({type:o.z.literal("object"),properties:o.z.optional(o.z.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.z.literal("tools/list")}),ur=F.extend({tools:o.z.array(pr)}),Be=S.extend({content:o.z.array(o.z.union([K,X,W,Je])),isError:o.z.boolean().default(!1).optional()}),zr=Be.or(S.extend({toolResult:o.z.unknown()})),Q=_.extend({method:o.z.literal("tools/call"),params:x.extend({name:o.z.string(),arguments:o.z.optional(o.z.record(o.z.unknown()))})}),mr=w.extend({method:o.z.literal("notifications/tools/list_changed")}),Ge=o.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=_.extend({method:o.z.literal("logging/setLevel"),params:x.extend({level:Ge})}),hr=w.extend({method:o.z.literal("notifications/message"),params:N.extend({level:Ge,logger:o.z.optional(o.z.string()),data:o.z.unknown()})}),fr=o.z.object({name:o.z.string().optional()}).passthrough(),gr=o.z.object({hints:o.z.optional(o.z.array(fr)),costPriority:o.z.optional(o.z.number().min(0).max(1)),speedPriority:o.z.optional(o.z.number().min(0).max(1)),intelligencePriority:o.z.optional(o.z.number().min(0).max(1))}).passthrough(),br=o.z.object({role:o.z.enum(["user","assistant"]),content:o.z.union([K,X,W])}).passthrough(),yr=_.extend({method:o.z.literal("sampling/createMessage"),params:x.extend({messages:o.z.array(br),systemPrompt:o.z.optional(o.z.string()),includeContext:o.z.optional(o.z.enum(["none","thisServer","allServers"])),temperature:o.z.optional(o.z.number()),maxTokens:o.z.number().int(),stopSequences:o.z.optional(o.z.array(o.z.string())),metadata:o.z.optional(o.z.object({}).passthrough()),modelPreferences:o.z.optional(gr)})}),ge=S.extend({model:o.z.string(),stopReason:o.z.optional(o.z.enum(["endTurn","stopSequence","maxTokens"]).or(o.z.string())),role:o.z.enum(["user","assistant"]),content:o.z.discriminatedUnion("type",[K,X,W])}),_r=o.z.object({type:o.z.literal("ref/resource"),uri:o.z.string()}).passthrough(),vr=o.z.object({type:o.z.literal("ref/prompt"),name:o.z.string()}).passthrough(),ee=_.extend({method:o.z.literal("completion/complete"),params:x.extend({ref:o.z.union([vr,_r]),argument:o.z.object({name:o.z.string(),value:o.z.string()}).passthrough()})}),xr=S.extend({completion:o.z.object({values:o.z.array(o.z.string()).max(100),total:o.z.optional(o.z.number().int()),hasMore:o.z.optional(o.z.boolean())}).passthrough()}),Sr=o.z.object({uri:o.z.string().startsWith("file://"),name:o.z.optional(o.z.string())}).passthrough(),Rr=_.extend({method:o.z.literal("roots/list")}),be=S.extend({roots:o.z.array(Sr)}),Pr=w.extend({method:o.z.literal("notifications/roots/list_changed")}),Fr=o.z.union([$,he,ee,dr,G,B,U,V,J,tr,rr,Q,Y]),Ur=o.z.union([H,Z,fe,Pr]),Vr=o.z.union([q,ge,be]),Jr=o.z.union([$,yr,Rr]),Br=o.z.union([H,Z,hr,nr,er,mr,lr]),Gr=o.z.union([q,Bt,xr,cr,ar,Wt,Yt,Qt,Be,ur]),b=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Tr=6e4,te=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new b(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{de(t)||$e(t)?this._onresponse(t):Oe(t)?this._onrequest(t,r):De(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new b(g.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:g.MethodNotFound,message:"Method not found"}}).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,f,C)=>this.request(h,f,{...C,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(h=>{var f;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var f,C;if(!i.signal.aborted)return(f=this._transport)===null||f===void 0?void 0:f.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(C=h.message)!==null&&C!==void 0?C:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),de(e))r(e);else{let s=new b(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var h,f,C,pe,ue;if(!this._transport){l(new Error("Not connected"));return}((h=this._options)===null||h===void 0?void 0:h.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=r?.signal)===null||f===void 0||f.throwIfAborted();let T=this._requestMessageId++,Ce={...e,jsonrpc:"2.0",id:T};r?.onprogress&&(this._progressHandlers.set(T,r.onprogress),Ce.params={...e.params,_meta:{progressToken:T}});let ke=v=>{var E;this._responseHandlers.delete(T),this._progressHandlers.delete(T),this._cleanupTimeout(T),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:T,reason:String(v)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(v)};this._responseHandlers.set(T,v=>{var E;if(!(!((E=r?.signal)===null||E===void 0)&&E.aborted)){if(v instanceof Error)return l(v);try{let I=t.parse(v.result);i(I)}catch(I){l(I)}}}),(C=r?.signal)===null||C===void 0||C.addEventListener("abort",()=>{var v;ke((v=r?.signal)===null||v===void 0?void 0:v.reason)});let Ee=(pe=r?.timeout)!==null&&pe!==void 0?pe:Tr,Dt=()=>ke(new b(g.RequestTimeout,"Request timed out",{timeout:Ee}));this._setupTimeout(T,Ee,r?.maxTotalTimeout,Dt,(ue=r?.resetTimeoutOnProgress)!==null&&ue!==void 0?ue:!1),this._transport.send(Ce,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(T),l(v)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ke(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(he,s=>this._oninitialize(s)),this.setNotificationHandler(fe,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ke(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:je.includes(t)?t:me,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},ge,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},be,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var We=Symbol("Let zodToJsonSchema decide on which parser to use");var Xe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Ye=n=>typeof n=="string"?{...Xe,name:n}:{...Xe,...n};var Qe=n=>{let e=Ye(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function ye(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function d(n,e,t,r,s){n[e]=t,ye(n,e,r,s)}var m=require("zod");function et(){return{}}var tt=require("zod");function rt(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==tt.ZodFirstPartyTypeKind.ZodAny&&(t.items=u(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&d(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&d(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(d(t,"minItems",n.exactLength.value,n.exactLength.message,e),d(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function nt(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}function ot(){return{type:"boolean"}}function ne(n,e){return u(n.type._def,e)}var st=(n,e)=>u(n.innerType._def,e);function _e(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>_e(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return wr(n,e)}}var wr=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":d(t,"minimum",r.value,r.message,e);break;case"max":d(t,"maximum",r.value,r.message,e);break}return t};function at(n,e){return{...u(n.innerType._def,e),default:n.defaultValue()}}function it(n,e){return e.effectStrategy==="input"?u(n.schema._def,e):{}}function ct(n){return{type:"string",enum:Array.from(n.values)}}var Cr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function lt(n,e){let t=[u(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),u(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(Cr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function pt(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}var A=require("zod");var ve,R={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ve===void 0&&(ve=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ve),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":P(t,"email",r.message,e);break;case"format:idn-email":P(t,"idn-email",r.message,e);break;case"pattern:zod":y(t,R.email,r.message,e);break}break;case"url":P(t,"uri",r.message,e);break;case"uuid":P(t,"uuid",r.message,e);break;case"regex":y(t,r.regex,r.message,e);break;case"cuid":y(t,R.cuid,r.message,e);break;case"cuid2":y(t,R.cuid2,r.message,e);break;case"startsWith":y(t,RegExp(`^${xe(r.value,e)}`),r.message,e);break;case"endsWith":y(t,RegExp(`${xe(r.value,e)}$`),r.message,e);break;case"datetime":P(t,"date-time",r.message,e);break;case"date":P(t,"date",r.message,e);break;case"time":P(t,"time",r.message,e);break;case"duration":P(t,"duration",r.message,e);break;case"length":d(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),d(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{y(t,RegExp(xe(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&P(t,"ipv4",r.message,e),r.version!=="v4"&&P(t,"ipv6",r.message,e);break}case"base64url":y(t,R.base64url,r.message,e);break;case"jwt":y(t,R.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&y(t,R.ipv4Cidr,r.message,e),r.version!=="v4"&&y(t,R.ipv6Cidr,r.message,e);break}case"emoji":y(t,R.emoji(),r.message,e);break;case"ulid":{y(t,R.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{P(t,"binary",r.message,e);break}case"contentEncoding:base64":{d(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{y(t,R.base64,r.message,e);break}}break}case"nanoid":y(t,R.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function xe(n,e){return e.patternStrategy==="escape"?Er(n):n}var kr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Er(n){let e="";for(let t=0;t<n.length;t++)kr.has(n[t])||(e+="\\"),e+=n[t];return e}function P(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):d(n,"format",e,t,r)}function y(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ut(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):d(n,"pattern",ut(e,r),t,r)}function ut(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
2
+ ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
3
+ ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
4
+ `:`[${r[l]}\r
5
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return s}function se(n,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===A.ZodFirstPartyTypeKind.ZodBranded&&n.keyType._def.type._def.typeName===A.ZodFirstPartyTypeKind.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function mt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=u(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function dt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ht(){return{not:{}}}function ft(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var M={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bt(n,e){if(e.target==="openApi3")return gt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in M&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=M[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return gt(n,e)}var gt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>u(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function yt(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:M[n.innerType._def.typeName],nullable:!0}:{type:[M[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=u(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function _t(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",ye(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?d(t,"minimum",r.value,r.message,e):d(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),d(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?d(t,"maximum",r.value,r.message,e):d(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),d(t,"maximum",r.value,r.message,e));break;case"multipleOf":d(t,"multipleOf",r.value,r.message,e);break}return t}var vt=require("zod");function xt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let h=jr(l);h&&t&&(l instanceof vt.ZodOptional&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),h=!1);let f=u(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(r.properties[i]=f,h||s.push(i))}s.length&&(r.required=s);let a=Ar(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Ar(n,e){if(n.catchall._def.typeName!=="ZodNever")return u(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function jr(n){try{return n.isOptional()}catch{return!0}}var St=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return u(n.innerType._def,e);let t=u(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var Rt=(n,e)=>{if(e.pipeStrategy==="input")return u(n.in._def,e);if(e.pipeStrategy==="output")return u(n.out._def,e);let t=u(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=u(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Pt(n,e){return u(n.type._def,e)}function Tt(n,e){let r={type:"array",uniqueItems:!0,items:u(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&d(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&d(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function wt(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:u(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>u(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Ct(){return{not:{}}}function kt(){return{}}var Et=(n,e)=>u(n.innerType._def,e);var At=(n,e,t)=>{switch(e){case m.ZodFirstPartyTypeKind.ZodString:return oe(n,t);case m.ZodFirstPartyTypeKind.ZodNumber:return _t(n,t);case m.ZodFirstPartyTypeKind.ZodObject:return xt(n,t);case m.ZodFirstPartyTypeKind.ZodBigInt:return nt(n,t);case m.ZodFirstPartyTypeKind.ZodBoolean:return ot();case m.ZodFirstPartyTypeKind.ZodDate:return _e(n,t);case m.ZodFirstPartyTypeKind.ZodUndefined:return Ct();case m.ZodFirstPartyTypeKind.ZodNull:return ft(t);case m.ZodFirstPartyTypeKind.ZodArray:return rt(n,t);case m.ZodFirstPartyTypeKind.ZodUnion:case m.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return bt(n,t);case m.ZodFirstPartyTypeKind.ZodIntersection:return lt(n,t);case m.ZodFirstPartyTypeKind.ZodTuple:return wt(n,t);case m.ZodFirstPartyTypeKind.ZodRecord:return se(n,t);case m.ZodFirstPartyTypeKind.ZodLiteral:return pt(n,t);case m.ZodFirstPartyTypeKind.ZodEnum:return ct(n);case m.ZodFirstPartyTypeKind.ZodNativeEnum:return dt(n);case m.ZodFirstPartyTypeKind.ZodNullable:return yt(n,t);case m.ZodFirstPartyTypeKind.ZodOptional:return St(n,t);case m.ZodFirstPartyTypeKind.ZodMap:return mt(n,t);case m.ZodFirstPartyTypeKind.ZodSet:return Tt(n,t);case m.ZodFirstPartyTypeKind.ZodLazy:return()=>n.getter()._def;case m.ZodFirstPartyTypeKind.ZodPromise:return Pt(n,t);case m.ZodFirstPartyTypeKind.ZodNaN:case m.ZodFirstPartyTypeKind.ZodNever:return ht();case m.ZodFirstPartyTypeKind.ZodEffects:return it(n,t);case m.ZodFirstPartyTypeKind.ZodAny:return et();case m.ZodFirstPartyTypeKind.ZodUnknown:return kt();case m.ZodFirstPartyTypeKind.ZodDefault:return at(n,t);case m.ZodFirstPartyTypeKind.ZodBranded:return ne(n,t);case m.ZodFirstPartyTypeKind.ZodReadonly:return Et(n,t);case m.ZodFirstPartyTypeKind.ZodCatch:return st(n,t);case m.ZodFirstPartyTypeKind.ZodPipeline:return Rt(n,t);case m.ZodFirstPartyTypeKind.ZodFunction:case m.ZodFirstPartyTypeKind.ZodVoid:case m.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function u(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==We)return i}if(r&&!t){let i=Ir(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=At(n,n.typeName,e),a=typeof c=="function"?u(c(),e):c;if(a&&Mr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Ir=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Nr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Nr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Mr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Se=(n,e)=>{let t=Qe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[h,f])=>({...l,[h]:u(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=u(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var O=require("zod");var jt=require("zod"),Re;(function(n){n.Completable="McpCompletable"})(Re||(Re={}));var j=class extends jt.ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Re.Completable,complete:e.complete,...Or(e)});function Or(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,h;let{message:f}=n;return a.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:(l=f??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(h=f??t)!==null&&h!==void 0?h:i.defaultError}},description:s}}var ie=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Se(t.inputSchema,{strictUnions:!0}):Lr}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new b(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new b(g.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new b(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ae;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ae;let a=await s._def.complete(e.params.argument.value);return It(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ae;throw new b(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ae;let c=await s(e.params.argument.value);return It(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new b(g.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new b(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Dr(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new b(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new b(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new b(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=O.z.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:O.z.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=O.z.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Lr={type:"object"};function Dr(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function It(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ae={completion:{values:[],hasMore:!1}};var Pe=Ut(require("process"),1);var ce=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
6
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),qr(t)}clear(){this._buffer=void 0}};function qr(n){return Ze.parse(JSON.parse(n))}function Nt(n){return JSON.stringify(n)+`
7
+ `}var le=class{constructor(e=Pe.default.stdin,t=Pe.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ce,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=Nt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};var we=require("zod");var Te=process.env.personalToken||""||"";function Mt(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var Ot=new ie({name:"F2C MCP",version:"0.0.1"});k("notification",{message:"MCP server instance created"});Ot.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:we.z.string().default(Te).describe("Your Figma personal access token"),figmaUrl:we.z.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{k("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=Mt(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return k("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Lt(){k("notification",{message:"Starting Figma-to-HTML service"});let n=new le;k("notification",{message:"Transport layer initialized"}),await Ot.connect(n),k("notification",{message:"MCP server connected to stdio"})}Lt().catch(n=>{k("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ function E(n,e){let t={jsonrpc:"2.0",...n==="notification"?{method:e.method||"log",params:e.params||{message:e.message}}:{id:e.id||null,error:{code:e.code||-32e3,message:e.message}}};console.log(JSON.stringify(t))}import{z as o}from"zod";var de="2024-11-05",Ee=[de,"2024-10-07"],L="2.0",Ae=o.union([o.string(),o.number().int()]),je=o.string(),S=o.object({_meta:o.optional(o.object({progressToken:o.optional(Ae)}).passthrough())}).passthrough(),v=o.object({method:o.string(),params:o.optional(S)}),N=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),C=o.object({method:o.string(),params:o.optional(N)}),R=o.object({_meta:o.optional(o.object({}).passthrough())}).passthrough(),D=o.union([o.string(),o.number().int()]),Ie=o.object({jsonrpc:o.literal(L),id:D}).merge(v).strict(),Ne=n=>Ie.safeParse(n).success,Me=o.object({jsonrpc:o.literal(L)}).merge(C).strict(),Oe=n=>Me.safeParse(n).success,Le=o.object({jsonrpc:o.literal(L),id:D,result:R}).strict(),he=n=>Le.safeParse(n).success,b;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(b||(b={}));var De=o.object({jsonrpc:o.literal(L),id:D,error:o.object({code:o.number().int(),message:o.string(),data:o.optional(o.unknown())})}).strict(),qe=n=>De.safeParse(n).success,He=o.union([Ie,Me,Le,De]),q=R.strict(),H=C.extend({method:o.literal("notifications/cancelled"),params:N.extend({requestId:D,reason:o.string().optional()})}),$e=o.object({name:o.string(),version:o.string()}).passthrough(),Ot=o.object({experimental:o.optional(o.object({}).passthrough()),sampling:o.optional(o.object({}).passthrough()),roots:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),fe=v.extend({method:o.literal("initialize"),params:S.extend({protocolVersion:o.string(),capabilities:Ot,clientInfo:$e})});var Lt=o.object({experimental:o.optional(o.object({}).passthrough()),logging:o.optional(o.object({}).passthrough()),completions:o.optional(o.object({}).passthrough()),prompts:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough()),resources:o.optional(o.object({subscribe:o.optional(o.boolean()),listChanged:o.optional(o.boolean())}).passthrough()),tools:o.optional(o.object({listChanged:o.optional(o.boolean())}).passthrough())}).passthrough(),Dt=R.extend({protocolVersion:o.string(),capabilities:Lt,serverInfo:$e,instructions:o.optional(o.string())}),ge=C.extend({method:o.literal("notifications/initialized")});var $=v.extend({method:o.literal("ping")}),qt=o.object({progress:o.number(),total:o.optional(o.number())}).passthrough(),Z=C.extend({method:o.literal("notifications/progress"),params:N.merge(qt).extend({progressToken:Ae})}),z=v.extend({params:S.extend({cursor:o.optional(je)}).optional()}),F=R.extend({nextCursor:o.optional(je)}),Ze=o.object({uri:o.string(),mimeType:o.optional(o.string())}).passthrough(),ze=Ze.extend({text:o.string()}),Fe=Ze.extend({blob:o.string().base64()}),Ht=o.object({uri:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),$t=o.object({uriTemplate:o.string(),name:o.string(),description:o.optional(o.string()),mimeType:o.optional(o.string())}).passthrough(),U=z.extend({method:o.literal("resources/list")}),Zt=F.extend({resources:o.array(Ht)}),V=z.extend({method:o.literal("resources/templates/list")}),zt=F.extend({resourceTemplates:o.array($t)}),J=v.extend({method:o.literal("resources/read"),params:S.extend({uri:o.string()})}),Ft=R.extend({contents:o.array(o.union([ze,Fe]))}),Ut=C.extend({method:o.literal("notifications/resources/list_changed")}),Vt=v.extend({method:o.literal("resources/subscribe"),params:S.extend({uri:o.string()})}),Jt=v.extend({method:o.literal("resources/unsubscribe"),params:S.extend({uri:o.string()})}),Bt=C.extend({method:o.literal("notifications/resources/updated"),params:N.extend({uri:o.string()})}),Gt=o.object({name:o.string(),description:o.optional(o.string()),required:o.optional(o.boolean())}).passthrough(),Kt=o.object({name:o.string(),description:o.optional(o.string()),arguments:o.optional(o.array(Gt))}).passthrough(),B=z.extend({method:o.literal("prompts/list")}),Xt=F.extend({prompts:o.array(Kt)}),G=v.extend({method:o.literal("prompts/get"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.string()))})}),K=o.object({type:o.literal("text"),text:o.string()}).passthrough(),X=o.object({type:o.literal("image"),data:o.string().base64(),mimeType:o.string()}).passthrough(),W=o.object({type:o.literal("audio"),data:o.string().base64(),mimeType:o.string()}).passthrough(),Ue=o.object({type:o.literal("resource"),resource:o.union([ze,Fe])}).passthrough(),Wt=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W,Ue])}).passthrough(),Yt=R.extend({description:o.optional(o.string()),messages:o.array(Wt)}),Qt=C.extend({method:o.literal("notifications/prompts/list_changed")}),er=o.object({name:o.string(),description:o.optional(o.string()),inputSchema:o.object({type:o.literal("object"),properties:o.optional(o.object({}).passthrough())}).passthrough()}).passthrough(),Y=z.extend({method:o.literal("tools/list")}),tr=F.extend({tools:o.array(er)}),Ve=R.extend({content:o.array(o.union([K,X,W,Ue])),isError:o.boolean().default(!1).optional()}),Or=Ve.or(R.extend({toolResult:o.unknown()})),Q=v.extend({method:o.literal("tools/call"),params:S.extend({name:o.string(),arguments:o.optional(o.record(o.unknown()))})}),rr=C.extend({method:o.literal("notifications/tools/list_changed")}),Je=o.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),nr=v.extend({method:o.literal("logging/setLevel"),params:S.extend({level:Je})}),or=C.extend({method:o.literal("notifications/message"),params:N.extend({level:Je,logger:o.optional(o.string()),data:o.unknown()})}),sr=o.object({name:o.string().optional()}).passthrough(),ar=o.object({hints:o.optional(o.array(sr)),costPriority:o.optional(o.number().min(0).max(1)),speedPriority:o.optional(o.number().min(0).max(1)),intelligencePriority:o.optional(o.number().min(0).max(1))}).passthrough(),ir=o.object({role:o.enum(["user","assistant"]),content:o.union([K,X,W])}).passthrough(),cr=v.extend({method:o.literal("sampling/createMessage"),params:S.extend({messages:o.array(ir),systemPrompt:o.optional(o.string()),includeContext:o.optional(o.enum(["none","thisServer","allServers"])),temperature:o.optional(o.number()),maxTokens:o.number().int(),stopSequences:o.optional(o.array(o.string())),metadata:o.optional(o.object({}).passthrough()),modelPreferences:o.optional(ar)})}),be=R.extend({model:o.string(),stopReason:o.optional(o.enum(["endTurn","stopSequence","maxTokens"]).or(o.string())),role:o.enum(["user","assistant"]),content:o.discriminatedUnion("type",[K,X,W])}),lr=o.object({type:o.literal("ref/resource"),uri:o.string()}).passthrough(),pr=o.object({type:o.literal("ref/prompt"),name:o.string()}).passthrough(),ee=v.extend({method:o.literal("completion/complete"),params:S.extend({ref:o.union([pr,lr]),argument:o.object({name:o.string(),value:o.string()}).passthrough()})}),ur=R.extend({completion:o.object({values:o.array(o.string()).max(100),total:o.optional(o.number().int()),hasMore:o.optional(o.boolean())}).passthrough()}),mr=o.object({uri:o.string().startsWith("file://"),name:o.optional(o.string())}).passthrough(),dr=v.extend({method:o.literal("roots/list")}),ye=R.extend({roots:o.array(mr)}),hr=C.extend({method:o.literal("notifications/roots/list_changed")}),Lr=o.union([$,fe,ee,nr,G,B,U,V,J,Vt,Jt,Q,Y]),Dr=o.union([H,Z,ge,hr]),qr=o.union([q,be,ye]),Hr=o.union([$,cr,dr]),$r=o.union([H,Z,or,Bt,Ut,rr,Qt]),Zr=o.union([q,Dt,ur,Yt,Xt,Zt,zt,Ft,Ve,tr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var fr=6e4,te=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(H,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(Z,t=>{this._onprogress(t)}),this.setRequestHandler($,t=>({}))}_setupTimeout(e,t,r,s,c=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:c,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new y(b.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,r)=>{he(t)||qe(t)?this._onresponse(t):Ne(t)?this._onrequest(t,r):Oe(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let r=new y(b.ConnectionClosed,"Connection closed");for(let s of t.values())s(r)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let r=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var r,s,c;let a=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(a===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:b.MethodNotFound,message:"Method not found"}}).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:(c=this._transport)===null||c===void 0?void 0:c.sessionId,sendNotification:f=>this.notification(f,{relatedRequestId:e.id}),sendRequest:(f,g,k)=>this.request(f,g,{...k,relatedRequestId:e.id}),authInfo:t?.authInfo};Promise.resolve().then(()=>a(e,l)).then(f=>{var g;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({result:f,jsonrpc:"2.0",id:e.id})},f=>{var g,k;if(!i.signal.aborted)return(g=this._transport)===null||g===void 0?void 0:g.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:b.InternalError,message:(k=f.message)!==null&&k!==void 0?k:"Internal error"}})}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,s=Number(t),c=this._progressHandlers.get(s);if(!c){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){a(l);return}c(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),he(e))r(e);else{let s=new y(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,r){let{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var f,g,k,ue,me;if(!this._transport){l(new Error("Not connected"));return}((f=this._options)===null||f===void 0?void 0:f.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(g=r?.signal)===null||g===void 0||g.throwIfAborted();let w=this._requestMessageId++,we={...e,jsonrpc:"2.0",id:w};r?.onprogress&&(this._progressHandlers.set(w,r.onprogress),we.params={...e.params,_meta:{progressToken:w}});let Ce=x=>{var A;this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(x)}},{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(x)};this._responseHandlers.set(w,x=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(x instanceof Error)return l(x);try{let I=t.parse(x.result);i(I)}catch(I){l(I)}}}),(k=r?.signal)===null||k===void 0||k.addEventListener("abort",()=>{var x;Ce((x=r?.signal)===null||x===void 0?void 0:x.reason)});let ke=(ue=r?.timeout)!==null&&ue!==void 0?ue:fr,Mt=()=>Ce(new y(b.RequestTimeout,"Request timed out",{timeout:ke}));this._setupTimeout(w,ke,r?.maxTotalTimeout,Mt,(me=r?.resetTimeoutOnProgress)!==null&&me!==void 0?me:!1),this._transport.send(we,{relatedRequestId:s,resumptionToken:c,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(w),l(x)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r,t)}setRequestHandler(e,t){let r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,c)=>Promise.resolve(t(e.parse(s),c)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Be(n,e){return Object.entries(e).reduce((t,[r,s])=>(s&&typeof s=="object"?t[r]=t[r]?{...t[r],...s}:s:t[r]=s,t),{...n})}var re=class extends te{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=(r=t?.capabilities)!==null&&r!==void 0?r:{},this._instructions=t?.instructions,this.setRequestHandler(fe,s=>this._oninitialize(s)),this.setNotificationHandler(ge,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Be(this._capabilities,e)}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ee.includes(t)?t:de,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},q)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},be,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},ye,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ke=Symbol("Let zodToJsonSchema decide on which parser to use");var Ge={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Xe=n=>typeof n=="string"?{...Ge,name:n}:{...Ge,...n};var We=n=>{let e=Xe(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function _e(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function h(n,e,t,r,s){n[e]=t,_e(n,e,r,s)}import{ZodFirstPartyTypeKind as d}from"zod";function Ye(){return{}}import{ZodFirstPartyTypeKind as gr}from"zod";function Qe(n,e){let t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==gr.ZodAny&&(t.items=m(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&h(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&h(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(h(t,"minItems",n.exactLength.value,n.exactLength.message,e),h(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function et(n,e){let t={type:"integer",format:"int64"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}function tt(){return{type:"boolean"}}function ne(n,e){return m(n.type._def,e)}var rt=(n,e)=>m(n.innerType._def,e);function ve(n,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,c)=>ve(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return br(n,e)}}var br=(n,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of n.checks)switch(r.kind){case"min":h(t,"minimum",r.value,r.message,e);break;case"max":h(t,"maximum",r.value,r.message,e);break}return t};function nt(n,e){return{...m(n.innerType._def,e),default:n.defaultValue()}}function ot(n,e){return e.effectStrategy==="input"?m(n.schema._def,e):{}}function st(n){return{type:"string",enum:Array.from(n.values)}}var yr=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function at(n,e){let t=[m(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(c=>!!c),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(c=>{if(yr(c))s.push(...c.allOf),c.unevaluatedProperties===void 0&&(r=void 0);else{let a=c;if("additionalProperties"in c&&c.additionalProperties===!1){let{additionalProperties:i,...l}=c;a=l}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function it(n,e){let t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}import{ZodFirstPartyTypeKind as M}from"zod";var xe,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(xe===void 0&&(xe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xe),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function oe(n,e){let t={type:"string"};if(n.checks)for(let r of n.checks)switch(r.kind){case"min":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":T(t,"email",r.message,e);break;case"format:idn-email":T(t,"idn-email",r.message,e);break;case"pattern:zod":_(t,P.email,r.message,e);break}break;case"url":T(t,"uri",r.message,e);break;case"uuid":T(t,"uuid",r.message,e);break;case"regex":_(t,r.regex,r.message,e);break;case"cuid":_(t,P.cuid,r.message,e);break;case"cuid2":_(t,P.cuid2,r.message,e);break;case"startsWith":_(t,RegExp(`^${Se(r.value,e)}`),r.message,e);break;case"endsWith":_(t,RegExp(`${Se(r.value,e)}$`),r.message,e);break;case"datetime":T(t,"date-time",r.message,e);break;case"date":T(t,"date",r.message,e);break;case"time":T(t,"time",r.message,e);break;case"duration":T(t,"duration",r.message,e);break;case"length":h(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),h(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{_(t,RegExp(Se(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&T(t,"ipv4",r.message,e),r.version!=="v4"&&T(t,"ipv6",r.message,e);break}case"base64url":_(t,P.base64url,r.message,e);break;case"jwt":_(t,P.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&_(t,P.ipv4Cidr,r.message,e),r.version!=="v4"&&_(t,P.ipv6Cidr,r.message,e);break}case"emoji":_(t,P.emoji(),r.message,e);break;case"ulid":{_(t,P.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{T(t,"binary",r.message,e);break}case"contentEncoding:base64":{h(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{_(t,P.base64,r.message,e);break}}break}case"nanoid":_(t,P.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Se(n,e){return e.patternStrategy==="escape"?vr(n):n}var _r=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vr(n){let e="";for(let t=0;t<n.length;t++)_r.has(n[t])||(e+="\\"),e+=n[t];return e}function T(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):h(n,"format",e,t,r)}function _(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:ct(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):h(n,"pattern",ct(e,r),t,r)}function ct(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;let t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source,s="",c=!1,a=!1,i=!1;for(let l=0;l<r.length;l++){if(c){s+=r[l],c=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){i?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),i=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],i=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){s+=`(^|(?<=[\r
2
+ ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
3
+ ]))`;continue}}if(t.s&&r[l]==="."){s+=a?`${r[l]}\r
4
+ `:`[${r[l]}\r
5
+ ]`;continue}s+=r[l],r[l]==="\\"?c=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return s}function se(n,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&n.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===M.ZodString&&n.keyType._def.checks?.length){let{type:r,...s}=oe(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===M.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===M.ZodBranded&&n.keyType._def.type._def.typeName===M.ZodString&&n.keyType._def.type._def.checks?.length){let{type:r,...s}=ne(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function lt(n,e){if(e.mapStrategy==="record")return se(n,e);let t=m(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function pt(n){let e=n.values,r=Object.keys(n.values).filter(c=>typeof e[e[c]]!="number").map(c=>e[c]),s=Array.from(new Set(r.map(c=>typeof c)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function ut(){return{not:{}}}function mt(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ht(n,e){if(e.target==="openApi3")return dt(n,e);let t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in O&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((s,c)=>{let a=O[c._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((s,c)=>{let a=typeof c._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(c._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){let s=r.filter((c,a,i)=>i.indexOf(c)===a);return{type:s.length>1?s:s[0],enum:t.reduce((c,a)=>c.includes(a._def.value)?c:[...c,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(c=>!r.includes(c))],[])};return dt(n,e)}var dt=(n,e)=>{let t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function ft(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:O[n.innerType._def.typeName],nullable:!0}:{type:[O[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function gt(n,e){let t={type:"number"};if(!n.checks)return t;for(let r of n.checks)switch(r.kind){case"int":t.type="integer",_e(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?h(t,"minimum",r.value,r.message,e):h(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),h(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?h(t,"maximum",r.value,r.message,e):h(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),h(t,"maximum",r.value,r.message,e));break;case"multipleOf":h(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as xr}from"zod";function bt(n,e){let t=e.target==="openAi",r={type:"object",properties:{}},s=[],c=n.shape();for(let i in c){let l=c[i];if(l===void 0||l._def===void 0)continue;let f=Rr(l);f&&t&&(l instanceof xr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),f=!1);let g=m(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});g!==void 0&&(r.properties[i]=g,f||s.push(i))}s.length&&(r.required=s);let a=Sr(n,e);return a!==void 0&&(r.additionalProperties=a),r}function Sr(n,e){if(n.catchall._def.typeName!=="ZodNever")return m(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Rr(n){try{return n.isOptional()}catch{return!0}}var yt=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(n.innerType._def,e);let t=m(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var _t=(n,e)=>{if(e.pipeStrategy==="input")return m(n.in._def,e);if(e.pipeStrategy==="output")return m(n.out._def,e);let t=m(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function vt(n,e){return m(n.type._def,e)}function xt(n,e){let r={type:"array",uniqueItems:!0,items:m(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&h(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&h(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function St(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Rt(){return{not:{}}}function Pt(){return{}}var Tt=(n,e)=>m(n.innerType._def,e);var wt=(n,e,t)=>{switch(e){case d.ZodString:return oe(n,t);case d.ZodNumber:return gt(n,t);case d.ZodObject:return bt(n,t);case d.ZodBigInt:return et(n,t);case d.ZodBoolean:return tt();case d.ZodDate:return ve(n,t);case d.ZodUndefined:return Rt();case d.ZodNull:return mt(t);case d.ZodArray:return Qe(n,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return ht(n,t);case d.ZodIntersection:return at(n,t);case d.ZodTuple:return St(n,t);case d.ZodRecord:return se(n,t);case d.ZodLiteral:return it(n,t);case d.ZodEnum:return st(n);case d.ZodNativeEnum:return pt(n);case d.ZodNullable:return ft(n,t);case d.ZodOptional:return yt(n,t);case d.ZodMap:return lt(n,t);case d.ZodSet:return xt(n,t);case d.ZodLazy:return()=>n.getter()._def;case d.ZodPromise:return vt(n,t);case d.ZodNaN:case d.ZodNever:return ut();case d.ZodEffects:return ot(n,t);case d.ZodAny:return Ye();case d.ZodUnknown:return Pt();case d.ZodDefault:return nt(n,t);case d.ZodBranded:return ne(n,t);case d.ZodReadonly:return Tt(n,t);case d.ZodCatch:return rt(n,t);case d.ZodPipeline:return _t(n,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(n,e,t=!1){let r=e.seen.get(n);if(e.override){let i=e.override?.(n,e,r,t);if(i!==Ke)return i}if(r&&!t){let i=Pr(r,e);if(i!==void 0)return i}let s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);let c=wt(n,n.typeName,e),a=typeof c=="function"?m(c(),e):c;if(a&&wr(n,e,a),e.postProcess){let i=e.postProcess(a,n,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}var Pr=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Tr(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Tr=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},wr=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t);var Re=(n,e)=>{let t=We(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[f,g])=>({...l,[f]:m(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,c=m(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(c.title=a);let i=s===void 0?r?{...c,[t.definitionPath]:r}:c:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:c}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};import{z as ae}from"zod";import{ZodType as Cr}from"zod";var Pe;(function(n){n.Completable="McpCompletable"})(Pe||(Pe={}));var j=class extends Cr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};j.create=(n,e)=>new j({type:n,typeName:Pe.Completable,complete:e.complete,...kr(e)});function kr(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{var l,f;let{message:g}=n;return a.code==="invalid_enum_value"?{message:g??i.defaultError}:typeof i.data>"u"?{message:(l=g??r)!==null&&l!==void 0?l:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(f=g??t)!==null&&f!==void 0?f:i.defaultError}},description:s}}var ce=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new re(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(Q.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Y,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Re(t.inputSchema,{strictUnions:!0}):Er}))})),this.server.setRequestHandler(Q,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(b.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;try{return await Promise.resolve(a(c,t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}else{let s=r.callback;try{return await Promise.resolve(s(t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.setRequestHandler(ee,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(b.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new y(b.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return ie;let s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof j))return ie;let a=await s._def.complete(e.params.argument.value);return Ct(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return ie;throw new y(b.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ie;let c=await s(e.params.argument.value);return Ct(c)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(U.shape.method.value),this.server.assertCanSetRequestHandler(V.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(U,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([c,a])=>a.enabled).map(([c,a])=>({uri:c,name:a.name,...a.metadata})),s=[];for(let c of Object.values(this._registeredResourceTemplates)){if(!c.resourceTemplate.listCallback)continue;let a=await c.resourceTemplate.listCallback(t);for(let i of a.resources)s.push({...i,...c.metadata})}return{resources:[...r,...s]}}),this.server.setRequestHandler(V,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(J,async(e,t)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new y(b.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(let c of Object.values(this._registeredResourceTemplates)){let a=c.resourceTemplate.uriTemplate.match(r.toString());if(a)return c.readCallback(r,a,t)}throw new y(b.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(B,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Ar(t.argsSchema):void 0}))})),this.server.setRequestHandler(G,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(b.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(b.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new y(b.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let c=s.data,a=r.callback;return await Promise.resolve(a(c,t))}else{let s=r.callback;return await Promise.resolve(s(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;typeof r[0]=="object"&&(s=r.shift());let c=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==t&&(delete this._registeredResources[t],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a={resourceTemplate:t,metadata:s,readCallback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,inputSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredTools[e],i.name&&(this._registeredTools[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.paramsSchema<"u"&&(a.inputSchema=ae.object(i.paramsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=a,this.setToolRequestHandlers(),this.sendToolListChanged(),a}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let s;t.length>1&&(s=t.shift());let c=t[0],a={description:r,argsSchema:s===void 0?void 0:ae.object(s),callback:c,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=ae.object(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Er={type:"object"};function Ar(n){return Object.entries(n.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Ct(n){return{completion:{values:n.slice(0,100),total:n.length,hasMore:n.length>100}}}var ie={completion:{values:[],hasMore:!1}};import Et from"node:process";var le=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
6
+ `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),jr(t)}clear(){this._buffer=void 0}};function jr(n){return He.parse(JSON.parse(n))}function kt(n){return JSON.stringify(n)+`
7
+ `}var pe=class{constructor(e=Et.stdin,t=Et.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new le,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(t=this.onerror)===null||t===void 0||t.call(this,r)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let r=kt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};import{z as jt}from"zod";var Te=process.env.personalToken||""||"";function At(n){try{let e=new URL(n),t=e.pathname,[,r]=t.match(/(?:file|design)\/([^/]+)/)||[],s=e.searchParams.get("node-id")||n.match(/node-id=([^&]+)/)||n.match(/#([^:]+:[^:]+)/),c=s?Array.isArray(s)?s[1]:s:"";if(!r)throw new Error("Invalid Figma link: fileKey not found");return{fileKey:r,nodeId:c||""}}catch{throw new Error("Invalid Figma link")}}var It=new ce({name:"F2C MCP",version:"0.0.1"});E("notification",{message:"MCP server instance created"});It.tool("figma_to_html","Convert Figma nodes to HTML content",{personalToken:jt.string().default(Te).describe("Your Figma personal access token"),figmaUrl:jt.string().describe("Figma design URL containing fileKey and nodeId")},async({personalToken:n=Te,figmaUrl:e})=>{E("notification",{message:"Tool call received",params:{figmaUrl:e}});try{let{fileKey:t,nodeId:r}=At(e);if(!t)throw new Error("fileKey \u4E0D\u80FD\u4E3A\u7A7A");let s=new URL("https://f2c-figma-api.yy.com/api/nodes");s.searchParams.append("fileKey",t),s.searchParams.append("nodeIds",r),s.searchParams.append("personal_token",n),s.searchParams.append("format","html");let c=await fetch(s.toString());if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);return{content:[{type:"text",text:await c.text()}]}}catch(t){return E("error",{message:`Error: ${t.message}`,code:-32e3}),{content:[{type:"text",text:`Error: ${t.message}`}]}}});async function Nt(){E("notification",{message:"Starting Figma-to-HTML service"});let n=new pe;E("notification",{message:"Transport layer initialized"}),await It.connect(n),E("notification",{message:"MCP server connected to stdio"})}Nt().catch(n=>{E("error",{message:`Server startup failed: ${n.message}`,code:-32e3}),process.exit(1)});
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@f2c/mcp",
3
+ "version": "0.0.4",
4
+ "description": "",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/f2c-ai/f2c-mcp",
8
+ "directory": "."
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "keywords": [
14
+ "f2c",
15
+ "mcp"
16
+ ],
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "main": "dist/index.js",
21
+ "types": "dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "import": {
25
+ "types": "./dist/index.d.mts",
26
+ "default": "./dist/index.mjs"
27
+ },
28
+ "require": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ }
32
+ }
33
+ },
34
+ "bin": {
35
+ "f2c-mcp": "dist/cli.js"
36
+ },
37
+ "author": "ken",
38
+ "maintainers": [
39
+ "ckken"
40
+ ],
41
+ "license": "ISC",
42
+ "dependencies": {
43
+ "zod": "^3.22.4"
44
+ },
45
+ "devDependencies": {
46
+ "@biomejs/biome": "^1.9.4",
47
+ "@empjs/biome-config": "^0.7.2",
48
+ "@modelcontextprotocol/sdk": "1.10.2",
49
+ "@types/node": "^22.15.0",
50
+ "dotenv": "^16.5.0",
51
+ "tsup": "^8.4.0",
52
+ "typescript": "^5.8.3"
53
+ },
54
+ "engines": {
55
+ "node": ">=16.0.0"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup",
59
+ "dev": "tsup --watch",
60
+ "inspector": "npx @modelcontextprotocol/inspector node ./dist/index.mjs",
61
+ "lint": "biome check . --fix"
62
+ }
63
+ }