@f2c/mcp 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@f2c/mcp",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -57,23 +57,22 @@
57
57
  "devDependencies": {
58
58
  "@biomejs/biome": "^1.9.4",
59
59
  "@empjs/biome-config": "^0.7.2",
60
- "@modelcontextprotocol/sdk": "1.11.2",
60
+ "@modelcontextprotocol/sdk": "1.12.1",
61
61
  "@types/bun": "^1.2.13",
62
62
  "@types/cors": "^2.8.18",
63
63
  "@types/express": "^5.0.1",
64
64
  "@types/node": "^22.15.0",
65
- "dotenv": "^16.5.0",
66
- "tsup": "^8.4.0",
67
65
  "typescript": "^5.8.3"
68
66
  },
69
67
  "engines": {
70
68
  "node": ">=16.0.0"
71
69
  },
72
70
  "scripts": {
73
- "build": "tsup",
74
- "dev": "tsup --watch",
71
+ "build": "bun run bun.build.script.ts",
72
+ "dev": "bun --watch run bun.build.script.ts",
75
73
  "http": "node ./dist/streamable-http.js",
76
74
  "http:dev": "bun --env-file=.env --watch run src/streamable-http.ts",
75
+ "http:prod": "bun --env-file= run src/streamable-http.ts",
77
76
  "inspector": "npx @modelcontextprotocol/inspector node ./dist/stdio.js",
78
77
  "lint": "biome check . --fix",
79
78
  "test": "bun test src/test/api.test.ts",
package/dist/cli.d.mts DELETED
@@ -1 +0,0 @@
1
- #!/usr/bin/env node
package/dist/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- #!/usr/bin/env node
package/dist/cli.mjs DELETED
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- import{z as s}from"zod";var ye="2025-03-26",He=[ye,"2024-11-05","2024-10-07"],$="2.0",$e=s.union([s.string(),s.number().int()]),qe=s.string(),Gt=s.object({progressToken:s.optional($e)}).passthrough(),R=s.object({_meta:s.optional(Gt)}).passthrough(),S=s.object({method:s.string(),params:s.optional(R)}),M=s.object({_meta:s.optional(s.object({}).passthrough())}).passthrough(),E=s.object({method:s.string(),params:s.optional(M)}),T=s.object({_meta:s.optional(s.object({}).passthrough())}).passthrough(),q=s.union([s.string(),s.number().int()]),Fe=s.object({jsonrpc:s.literal($),id:q}).merge(S).strict(),Ze=o=>Fe.safeParse(o).success,ze=s.object({jsonrpc:s.literal($)}).merge(E).strict(),Ue=o=>ze.safeParse(o).success,Ve=s.object({jsonrpc:s.literal($),id:q,result:T}).strict(),be=o=>Ve.safeParse(o).success,g;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(g||(g={}));var Xe=s.object({jsonrpc:s.literal($),id:q,error:s.object({code:s.number().int(),message:s.string(),data:s.optional(s.unknown())})}).strict(),Ge=o=>Xe.safeParse(o).success,Je=s.union([Fe,ze,Ve,Xe]),F=T.strict(),Z=E.extend({method:s.literal("notifications/cancelled"),params:M.extend({requestId:q,reason:s.string().optional()})}),Be=s.object({name:s.string(),version:s.string()}).passthrough(),Jt=s.object({experimental:s.optional(s.object({}).passthrough()),sampling:s.optional(s.object({}).passthrough()),roots:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough())}).passthrough(),_e=S.extend({method:s.literal("initialize"),params:R.extend({protocolVersion:s.string(),capabilities:Jt,clientInfo:Be})});var Bt=s.object({experimental:s.optional(s.object({}).passthrough()),logging:s.optional(s.object({}).passthrough()),completions:s.optional(s.object({}).passthrough()),prompts:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough()),resources:s.optional(s.object({subscribe:s.optional(s.boolean()),listChanged:s.optional(s.boolean())}).passthrough()),tools:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough())}).passthrough(),Kt=T.extend({protocolVersion:s.string(),capabilities:Bt,serverInfo:Be,instructions:s.optional(s.string())}),ve=E.extend({method:s.literal("notifications/initialized")});var z=S.extend({method:s.literal("ping")}),Wt=s.object({progress:s.number(),total:s.optional(s.number())}).passthrough(),U=E.extend({method:s.literal("notifications/progress"),params:M.merge(Wt).extend({progressToken:$e})}),V=S.extend({params:R.extend({cursor:s.optional(qe)}).optional()}),X=T.extend({nextCursor:s.optional(qe)}),Ke=s.object({uri:s.string(),mimeType:s.optional(s.string())}).passthrough(),We=Ke.extend({text:s.string()}),Ye=Ke.extend({blob:s.string().base64()}),Yt=s.object({uri:s.string(),name:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string())}).passthrough(),Qt=s.object({uriTemplate:s.string(),name:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string())}).passthrough(),G=V.extend({method:s.literal("resources/list")}),er=X.extend({resources:s.array(Yt)}),J=V.extend({method:s.literal("resources/templates/list")}),tr=X.extend({resourceTemplates:s.array(Qt)}),B=S.extend({method:s.literal("resources/read"),params:R.extend({uri:s.string()})}),rr=T.extend({contents:s.array(s.union([We,Ye]))}),or=E.extend({method:s.literal("notifications/resources/list_changed")}),sr=S.extend({method:s.literal("resources/subscribe"),params:R.extend({uri:s.string()})}),nr=S.extend({method:s.literal("resources/unsubscribe"),params:R.extend({uri:s.string()})}),ar=E.extend({method:s.literal("notifications/resources/updated"),params:M.extend({uri:s.string()})}),ir=s.object({name:s.string(),description:s.optional(s.string()),required:s.optional(s.boolean())}).passthrough(),cr=s.object({name:s.string(),description:s.optional(s.string()),arguments:s.optional(s.array(ir))}).passthrough(),K=V.extend({method:s.literal("prompts/list")}),lr=X.extend({prompts:s.array(cr)}),W=S.extend({method:s.literal("prompts/get"),params:R.extend({name:s.string(),arguments:s.optional(s.record(s.string()))})}),Y=s.object({type:s.literal("text"),text:s.string()}).passthrough(),Q=s.object({type:s.literal("image"),data:s.string().base64(),mimeType:s.string()}).passthrough(),ee=s.object({type:s.literal("audio"),data:s.string().base64(),mimeType:s.string()}).passthrough(),Qe=s.object({type:s.literal("resource"),resource:s.union([We,Ye])}).passthrough(),pr=s.object({role:s.enum(["user","assistant"]),content:s.union([Y,Q,ee,Qe])}).passthrough(),ur=T.extend({description:s.optional(s.string()),messages:s.array(pr)}),mr=E.extend({method:s.literal("notifications/prompts/list_changed")}),dr=s.object({title:s.optional(s.string()),readOnlyHint:s.optional(s.boolean()),destructiveHint:s.optional(s.boolean()),idempotentHint:s.optional(s.boolean()),openWorldHint:s.optional(s.boolean())}).passthrough(),fr=s.object({name:s.string(),description:s.optional(s.string()),inputSchema:s.object({type:s.literal("object"),properties:s.optional(s.object({}).passthrough())}).passthrough(),annotations:s.optional(dr)}).passthrough(),te=V.extend({method:s.literal("tools/list")}),hr=X.extend({tools:s.array(fr)}),et=T.extend({content:s.array(s.union([Y,Q,ee,Qe])),isError:s.boolean().default(!1).optional()}),Jr=et.or(T.extend({toolResult:s.unknown()})),re=S.extend({method:s.literal("tools/call"),params:R.extend({name:s.string(),arguments:s.optional(s.record(s.unknown()))})}),gr=E.extend({method:s.literal("notifications/tools/list_changed")}),tt=s.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),yr=S.extend({method:s.literal("logging/setLevel"),params:R.extend({level:tt})}),br=E.extend({method:s.literal("notifications/message"),params:M.extend({level:tt,logger:s.optional(s.string()),data:s.unknown()})}),_r=s.object({name:s.string().optional()}).passthrough(),vr=s.object({hints:s.optional(s.array(_r)),costPriority:s.optional(s.number().min(0).max(1)),speedPriority:s.optional(s.number().min(0).max(1)),intelligencePriority:s.optional(s.number().min(0).max(1))}).passthrough(),xr=s.object({role:s.enum(["user","assistant"]),content:s.union([Y,Q,ee])}).passthrough(),Sr=S.extend({method:s.literal("sampling/createMessage"),params:R.extend({messages:s.array(xr),systemPrompt:s.optional(s.string()),includeContext:s.optional(s.enum(["none","thisServer","allServers"])),temperature:s.optional(s.number()),maxTokens:s.number().int(),stopSequences:s.optional(s.array(s.string())),metadata:s.optional(s.object({}).passthrough()),modelPreferences:s.optional(vr)})}),xe=T.extend({model:s.string(),stopReason:s.optional(s.enum(["endTurn","stopSequence","maxTokens"]).or(s.string())),role:s.enum(["user","assistant"]),content:s.discriminatedUnion("type",[Y,Q,ee])}),Pr=s.object({type:s.literal("ref/resource"),uri:s.string()}).passthrough(),Rr=s.object({type:s.literal("ref/prompt"),name:s.string()}).passthrough(),oe=S.extend({method:s.literal("completion/complete"),params:R.extend({ref:s.union([Rr,Pr]),argument:s.object({name:s.string(),value:s.string()}).passthrough()})}),Tr=T.extend({completion:s.object({values:s.array(s.string()).max(100),total:s.optional(s.number().int()),hasMore:s.optional(s.boolean())}).passthrough()}),wr=s.object({uri:s.string().startsWith("file://"),name:s.optional(s.string())}).passthrough(),Cr=S.extend({method:s.literal("roots/list")}),Se=T.extend({roots:s.array(wr)}),kr=E.extend({method:s.literal("notifications/roots/list_changed")}),Br=s.union([z,_e,oe,yr,W,K,G,J,B,sr,nr,re,te]),Kr=s.union([Z,U,ve,kr]),Wr=s.union([F,xe,Se]),Yr=s.union([z,Sr,Cr]),Qr=s.union([Z,U,br,ar,or,gr,mr]),eo=s.union([F,Kt,Tr,ur,lr,er,tr,rr,et,hr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Er=6e4,se=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(Z,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_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(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)=>{be(t)||Ge(t)?this._onresponse(t):Ze(t)?this._onrequest(t,r):Ue(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(g.ConnectionClosed,"Connection closed");for(let n of t.values())n(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(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){var r,n,i,a;let c=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(c===void 0){(n=this._transport)===null||n===void 0||n.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 l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let _={signal:l.signal,sessionId:(i=this._transport)===null||i===void 0?void 0:i.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,x,j)=>this.request(h,x,{...j,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>c(e,_)).then(h=>{var x;if(!l.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var x,j;if(!l.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(j=h.message)!==null&&j!==void 0?j:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),c=this._timeoutInfo.get(n);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){a(l);return}i(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),be(e))r(e);else{let n=new y(e.error.code,e.error.message,e.error.data);r(n)}}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:n,resumptionToken:i,onresumptiontoken:a}=r??{};return new Promise((c,l)=>{var _,h,x,j,ge;if(!this._transport){l(new Error("Not connected"));return}((_=this._options)===null||_===void 0?void 0:_.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(h=r?.signal)===null||h===void 0||h.throwIfAborted();let k=this._requestMessageId++,Me={...e,jsonrpc:"2.0",id:k};r?.onprogress&&(this._progressHandlers.set(k,r.onprogress),Me.params={...e.params,_meta:{progressToken:k}});let Le=P=>{var A;this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(P)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(P)};this._responseHandlers.set(k,P=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(P instanceof Error)return l(P);try{let I=t.parse(P.result);c(I)}catch(I){l(I)}}}),(x=r?.signal)===null||x===void 0||x.addEventListener("abort",()=>{var P;Le((P=r?.signal)===null||P===void 0?void 0:P.reason)});let De=(j=r?.timeout)!==null&&j!==void 0?j:Er,Xt=()=>Le(new y(g.RequestTimeout,"Request timed out",{timeout:De}));this._setupTimeout(k,De,r?.maxTotalTimeout,Xt,(ge=r?.resetTimeoutOnProgress)!==null&&ge!==void 0?ge:!1),this._transport.send(Me,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(P=>{this._cleanupTimeout(k),l(P)})})}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,(n,i)=>Promise.resolve(t(e.parse(n),i)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function rt(o,e){return Object.entries(e).reduce((t,[r,n])=>(n&&typeof n=="object"?t[r]=t[r]?{...t[r],...n}:n:t[r]=n,t),{...o})}var ne=class extends se{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(_e,n=>this._oninitialize(n)),this.setNotificationHandler(ve,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rt(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:He.includes(t)?t:ye,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"},F)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},xe,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Se,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 st=Symbol("Let zodToJsonSchema decide on which parser to use");var ot={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"},nt=o=>typeof o=="string"?{...ot,name:o}:{...ot,...o};var at=o=>{let e=nt(o),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Pe(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function f(o,e,t,r,n){o[e]=t,Pe(o,e,r,n)}import{ZodFirstPartyTypeKind as d}from"zod";function it(){return{}}import{ZodFirstPartyTypeKind as jr}from"zod";function ct(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==jr.ZodAny&&(t.items=m(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&f(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&f(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(f(t,"minItems",o.exactLength.value,o.exactLength.message,e),f(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function lt(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}function pt(){return{type:"boolean"}}function ae(o,e){return m(o.type._def,e)}var ut=(o,e)=>m(o.innerType._def,e);function Re(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,i)=>Re(o,e,n))};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 Ar(o,e)}}var Ar=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.checks)switch(r.kind){case"min":f(t,"minimum",r.value,r.message,e);break;case"max":f(t,"maximum",r.value,r.message,e);break}return t};function mt(o,e){return{...m(o.innerType._def,e),default:o.defaultValue()}}function dt(o,e){return e.effectStrategy==="input"?m(o.schema._def,e):{}}function ft(o){return{type:"string",enum:Array.from(o.values)}}var Nr=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ht(o,e){let t=[m(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return t.forEach(i=>{if(Nr(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:c,...l}=i;a=l}else r=void 0;n.push(a)}}),n.length?{allOf:n,...r}:void 0}function gt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}import{ZodFirstPartyTypeKind as L}from"zod";var Te,w={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Te===void 0&&(Te=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Te),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.checks)switch(r.kind){case"min":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":C(t,"email",r.message,e);break;case"format:idn-email":C(t,"idn-email",r.message,e);break;case"pattern:zod":v(t,w.email,r.message,e);break}break;case"url":C(t,"uri",r.message,e);break;case"uuid":C(t,"uuid",r.message,e);break;case"regex":v(t,r.regex,r.message,e);break;case"cuid":v(t,w.cuid,r.message,e);break;case"cuid2":v(t,w.cuid2,r.message,e);break;case"startsWith":v(t,RegExp(`^${we(r.value,e)}`),r.message,e);break;case"endsWith":v(t,RegExp(`${we(r.value,e)}$`),r.message,e);break;case"datetime":C(t,"date-time",r.message,e);break;case"date":C(t,"date",r.message,e);break;case"time":C(t,"time",r.message,e);break;case"duration":C(t,"duration",r.message,e);break;case"length":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{v(t,RegExp(we(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&C(t,"ipv4",r.message,e),r.version!=="v4"&&C(t,"ipv6",r.message,e);break}case"base64url":v(t,w.base64url,r.message,e);break;case"jwt":v(t,w.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&v(t,w.ipv4Cidr,r.message,e),r.version!=="v4"&&v(t,w.ipv6Cidr,r.message,e);break}case"emoji":v(t,w.emoji(),r.message,e);break;case"ulid":{v(t,w.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{C(t,"binary",r.message,e);break}case"contentEncoding:base64":{f(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{v(t,w.base64,r.message,e);break}}break}case"nanoid":v(t,w.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function we(o,e){return e.patternStrategy==="escape"?Ir(o):o}var Or=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ir(o){let e="";for(let t=0;t<o.length;t++)Or.has(o[t])||(e+="\\"),e+=o[t];return e}function C(o,e,t,r){o.format||o.anyOf?.some(n=>n.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):f(o,"format",e,t,r)}function v(o,e,t,r){o.pattern||o.allOf?.some(n=>n.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:yt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):f(o,"pattern",yt(e,r),t,r)}function yt(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,n="",i=!1,a=!1,c=!1;for(let l=0;l<r.length;l++){if(i){n+=r[l],i=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){c?(n+=r[l],n+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(n+=r[l],c=!0):n+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){n+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){n+=`(^|(?<=[\r
3
- ]))`;continue}else if(r[l]==="$"){n+=`($|(?=[\r
4
- ]))`;continue}}if(t.s&&r[l]==="."){n+=a?`${r[l]}\r
5
- `:`[${r[l]}\r
6
- ]`;continue}n+=r[l],r[l]==="\\"?i=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),o.source}return n}function ce(o,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&o.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,n)=>({...r,[n]:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===L.ZodString&&o.keyType._def.checks?.length){let{type:r,...n}=ie(o.keyType._def,e);return{...t,propertyNames:n}}else{if(o.keyType?._def.typeName===L.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===L.ZodBranded&&o.keyType._def.type._def.typeName===L.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...n}=ae(o.keyType._def,e);return{...t,propertyNames:n}}}return t}function bt(o,e){if(e.mapStrategy==="record")return ce(o,e);let t=m(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function _t(o){let e=o.values,r=Object.keys(o.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(r.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:r}}function vt(){return{not:{}}}function xt(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pt(o,e){if(e.target==="openApi3")return St(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in D&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((n,i)=>{let a=D[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(r.length===t.length){let n=r.filter((i,a,c)=>c.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,n)=>[...r,...n._def.values.filter(i=>!r.includes(i))],[])};return St(o,e)}var St=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.options).map((r,n)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function Rt(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:D[o.innerType._def.typeName],nullable:!0}:{type:[D[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Tt(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"int":t.type="integer",Pe(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as Mr}from"zod";function wt(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},n=[],i=o.shape();for(let c in i){let l=i[c];if(l===void 0||l._def===void 0)continue;let _=Dr(l);_&&t&&(l instanceof Mr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),_=!1);let h=m(l._def,{...e,currentPath:[...e.currentPath,"properties",c],propertyPath:[...e.currentPath,"properties",c]});h!==void 0&&(r.properties[c]=h,_||n.push(c))}n.length&&(r.required=n);let a=Lr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function Lr(o,e){if(o.catchall._def.typeName!=="ZodNever")return m(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dr(o){try{return o.isOptional()}catch{return!0}}var Ct=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(o.innerType._def,e);let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var kt=(o,e)=>{if(e.pipeStrategy==="input")return m(o.in._def,e);if(e.pipeStrategy==="output")return m(o.out._def,e);let t=m(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(n=>n!==void 0)}};function Et(o,e){return m(o.type._def,e)}function jt(o,e){let r={type:"array",uniqueItems:!0,items:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&f(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&f(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function At(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Nt(){return{not:{}}}function Ot(){return{}}var It=(o,e)=>m(o.innerType._def,e);var Mt=(o,e,t)=>{switch(e){case d.ZodString:return ie(o,t);case d.ZodNumber:return Tt(o,t);case d.ZodObject:return wt(o,t);case d.ZodBigInt:return lt(o,t);case d.ZodBoolean:return pt();case d.ZodDate:return Re(o,t);case d.ZodUndefined:return Nt();case d.ZodNull:return xt(t);case d.ZodArray:return ct(o,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return Pt(o,t);case d.ZodIntersection:return ht(o,t);case d.ZodTuple:return At(o,t);case d.ZodRecord:return ce(o,t);case d.ZodLiteral:return gt(o,t);case d.ZodEnum:return ft(o);case d.ZodNativeEnum:return _t(o);case d.ZodNullable:return Rt(o,t);case d.ZodOptional:return Ct(o,t);case d.ZodMap:return bt(o,t);case d.ZodSet:return jt(o,t);case d.ZodLazy:return()=>o.getter()._def;case d.ZodPromise:return Et(o,t);case d.ZodNaN:case d.ZodNever:return vt();case d.ZodEffects:return dt(o,t);case d.ZodAny:return it();case d.ZodUnknown:return Ot();case d.ZodDefault:return mt(o,t);case d.ZodBranded:return ae(o,t);case d.ZodReadonly:return It(o,t);case d.ZodCatch:return ut(o,t);case d.ZodPipeline:return kt(o,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(o,e,t=!1){let r=e.seen.get(o);if(e.override){let c=e.override?.(o,e,r,t);if(c!==st)return c}if(r&&!t){let c=Hr(r,e);if(c!==void 0)return c}let n={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,n);let i=Mt(o,o.typeName,e),a=typeof i=="function"?m(i(),e):i;if(a&&qr(o,e,a),e.postProcess){let c=e.postProcess(a,o,e);return n.jsonSchema=a,c}return n.jsonSchema=a,a}var Hr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:$r(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},$r=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},qr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Ce=(o,e)=>{let t=at(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[_,h])=>({...l,[_]:m(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,_]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=m(o._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a);let c=n===void 0?r?{...i,[t.definitionPath]:r}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...r,[n]:i}};return t.target==="jsonSchema7"?c.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c};import{z as le}from"zod";import{ZodType as Fr}from"zod";var ke;(function(o){o.Completable="McpCompletable"})(ke||(ke={}));var O=class extends Fr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};O.create=(o,e)=>new O({type:o,typeName:ke.Completable,complete:e.complete,...Zr(e)});function Zr(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:n}=o;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,c)=>{var l,_;let{message:h}=o;return a.code==="invalid_enum_value"?{message:h??c.defaultError}:typeof c.data>"u"?{message:(l=h??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(_=h??t)!==null&&_!==void 0?_:c.defaultError}},description:n}}var ue=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ne(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Ce(t.inputSchema,{strictUnions:!0}):zr,annotations:t.annotations}))})),this.server.setRequestHandler(re,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let n=await r.inputSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new y(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${n.error.message}`);let i=n.data,a=r.callback;try{return await Promise.resolve(a(i,t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}else{let n=r.callback;try{return await Promise.resolve(n(t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(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 y(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return pe;let n=r.argsSchema.shape[e.params.argument.name];if(!(n instanceof O))return pe;let a=await n._def.complete(e.params.argument.value);return Dt(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return pe;throw new y(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return pe;let i=await n(e.params.argument.value);return Dt(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(G,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),n=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(t);for(let c of a.resources)n.push({...c,...i.metadata})}return{resources:[...r,...n]}}),this.server.setRequestHandler(J,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(B,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new y(g.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(r.toString());if(a)return i.readCallback(r,a,t)}throw new y(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(K,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Vr(t.argsSchema):void 0}))})),this.server.setRequestHandler(W,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=await r.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new y(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);let i=n.data,a=r.callback;return await Promise.resolve(a(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;typeof r[0]=="object"&&(n=r.shift());let i=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:c=>{typeof c.uri<"u"&&c.uri!==t&&(delete this._registeredResources[t],c.uri&&(this._registeredResources[c.uri]=a)),typeof c.name<"u"&&(a.name=c.name),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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 n,i;if(t.length>1){let l=t[0];Lt(l)?(n=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!Lt(t[0])&&(i=t.shift())):typeof l=="object"&&l!==null&&(i=t.shift())}let a=t[0],c={description:r,inputSchema:n===void 0?void 0:le.object(n),annotations:i,callback:a,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=c)),typeof l.description<"u"&&(c.description=l.description),typeof l.paramsSchema<"u"&&(c.inputSchema=le.object(l.paramsSchema)),typeof l.callback<"u"&&(c.callback=l.callback),typeof l.annotations<"u"&&(c.annotations=l.annotations),typeof l.enabled<"u"&&(c.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}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 n;t.length>1&&(n=t.shift());let i=t[0],a={description:r,argsSchema:n===void 0?void 0:le.object(n),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredPrompts[e],c.name&&(this._registeredPrompts[c.name]=a)),typeof c.description<"u"&&(a.description=c.description),typeof c.argsSchema<"u"&&(a.argsSchema=le.object(c.argsSchema)),typeof c.callback<"u"&&(a.callback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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 zr={type:"object"};function Lt(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(Ur)}function Ur(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Vr(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Dt(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var pe={completion:{values:[],hasMore:!1}};var me=process.env.personalToken||""||"",Ht="F2C MCP",$t="0.2.0";var Ee=class{constructor(){this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=me}async nodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,option:{cssFramework:"inlinecss",imgFormat:e.imgFormat||"png",scaleSize:e.scaleSize||2},format:"files"};e.format==="react-cssmodules"?t.option.cssFramework="cssmodules":e.format==="react-tailwind"&&(t.option.cssFramework="tailwindcss");let r=this.opToUrl(`${this.f2cHost}/nodes`,t);return this.fetch(r,"json")}async fetch(e,t="json"){try{let n=await fetch(e,{method:"GET"});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return t==="text"?await n.text():await n.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={}){if(Object.keys(t).length===0)return e;let r=new URL(e);for(let[n,i]of Object.entries(t))if(typeof i=="object"&&i!==null)for(let[a,c]of Object.entries(i))r.searchParams.append(`${n}[${a}]`,c);else r.searchParams.append(n,i);return r.toString()}},qt=new Ee;import{z as N}from"zod";import je from"fs";import H from"path";var Ae=class{constructor(){this.imgFormat="png"}setImgFormat(e){this.imgFormat=e}async downloadImage(e,t){try{je.existsSync(t.localPath)||je.mkdirSync(t.localPath,{recursive:!0});let r=`${t.fileName}.${this.imgFormat}`,n=H.join(t.localPath,r),i=await fetch(e);if(!i.ok)throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${i.status} ${i.statusText}`);let a=await i.arrayBuffer();return je.writeFileSync(n,new Uint8Array(a)),H.join(H.basename(t.localPath),r).replace(/\\/g,"/")}catch(r){throw console.error("\u56FE\u7247\u4E0B\u8F7D\u9519\u8BEF:",r),r}}async processContent(e,t){t=H.join(t,"images");try{let r=/https:\/\/figma-alpha-api\.s3\.us-west-2\.amazonaws\.com\/images\/[a-f0-9-]+/g,n=e.match(r);if(!n)return e;let i=e;for(let a of n){let c=H.basename(a),l=await this.downloadImage(a,{localPath:t,fileName:c});i=i.replace(a,l)}return i}catch(r){throw console.error("\u5185\u5BB9\u5904\u7406\u9519\u8BEF:",r),r}}},Ne=new Ae;var Ft=o=>{o.tool("figma_to_code","Transform Figma designs into production-ready code. This tool converts selected Figma nodes into HTML, React with CSS Modules, or React with Tailwind CSS, enabling seamless design-to-code workflow.",{fileKey:N.string().describe("The Figma file identifier found in the file URL (e.g., https://www.figma.com/file/XXXXXXXXXXXX/). Extract the XXXXXXXXXXXX portion as the fileKey."),ids:N.string().describe('Comma-separated list of Figma node IDs for conversion. To obtain node IDs, select elements in Figma, right-click and select "Copy/Paste as" \u2192 "Copy ID".'),format:N.enum(["html","react-cssmodules","react-tailwind"]).default("html").describe('Specify the output format: "html" generates semantic HTML/CSS, "react-cssmodules" creates React components with scoped CSS modules, "react-tailwind" produces React components with utility-first Tailwind classes.'),personalToken:N.string().optional().describe("Figma personal access token for API authentication"),localPath:N.string().optional().describe("Absolute path for image asset storage. Directory will be created if non-existent. Path must follow OS-specific format without special character escaping."),imgFormat:N.enum(["png","jpg","svg"]).default("png").describe('Export format for image assets: "png" for lossless quality, "jpg" for compressed files, or "svg" for vector graphics.'),scaleSize:N.number().min(1).max(4).default(2).describe("Image export scale factor (1-4). Higher values yield better quality at the cost of larger file sizes.")},async e=>{try{let t=await qt.nodeToCode(e)||[];return e.localPath&&(Ne.setImgFormat(e.imgFormat),await Promise.all(t.map(async r=>{r.content=await Ne.processContent(r.content,e.localPath)}))),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return console.error("Tool execution error:",t),{content:[{type:"text",text:`Error: ${t.message}`}]}}})};var Oe=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.personalToken=me}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},n=await fetch(e,r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return t==="text"?await n.text():await n.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let n=new URL(e);for(let[i,a]of Object.entries(t))r.includes(i)||n.searchParams.append(i,a);return n.toString()}},Ie=new Oe;import{z as b}from"zod";var Zt=o=>{o.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:b.string().describe("Unique identifier of the Figma file"),ids:b.string().describe("List of node IDs to retrieve, comma separated"),personalToken:b.string().optional().describe("Your Figma personal access token"),version:b.string().optional().describe("Specify the version to return"),depth:b.number().optional().describe("Specify the depth of nodes to return"),geometry:b.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:b.string().optional().describe("Specify plugin data to return"),branch_data:b.boolean().optional().describe("Specify whether to return branch data")},async e=>{try{let t=await Ie.files(e);return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}]}}}),o.tool("figma_get_images","Get images of Figma nodes",{fileKey:b.string().describe("Unique identifier of the Figma file"),ids:b.string().describe("Node IDs to get images for, comma separated"),format:b.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:b.number().optional().describe("Image scale factor"),svg_include_id:b.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:b.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:b.boolean().optional().describe("Whether to use absolute bounds"),version:b.string().optional().describe("Specify the version to return"),personalToken:b.string().optional().describe("Your Figma personal access token")},async e=>{try{let t=await Ie.images(e);return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}]}}})};var de=new ue({name:Ht,version:$t},{capabilities:{logging:{}}});Zt(de);Ft(de);import Ut from"node:process";var fe=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),Xr(t)}clear(){this._buffer=void 0}};function Xr(o){return Je.parse(JSON.parse(o))}function zt(o){return JSON.stringify(o)+`
8
- `}var he=class{constructor(e=Ut.stdin,t=Ut.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new fe,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var n;(n=this.onerror)===null||n===void 0||n.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=zt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};async function Vt(o){try{let e=new he;await o.connect(e)}catch(e){console.log(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32e3,message:`Server startup failed: ${e.message}`}})),process.exit(1)}}Vt(de);
package/dist/stdio.d.mts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/stdio.d.ts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/stdio.mjs DELETED
@@ -1,7 +0,0 @@
1
- import{z as s}from"zod";var ye="2025-03-26",He=[ye,"2024-11-05","2024-10-07"],$="2.0",$e=s.union([s.string(),s.number().int()]),qe=s.string(),Gt=s.object({progressToken:s.optional($e)}).passthrough(),R=s.object({_meta:s.optional(Gt)}).passthrough(),S=s.object({method:s.string(),params:s.optional(R)}),M=s.object({_meta:s.optional(s.object({}).passthrough())}).passthrough(),E=s.object({method:s.string(),params:s.optional(M)}),T=s.object({_meta:s.optional(s.object({}).passthrough())}).passthrough(),q=s.union([s.string(),s.number().int()]),Fe=s.object({jsonrpc:s.literal($),id:q}).merge(S).strict(),Ze=o=>Fe.safeParse(o).success,ze=s.object({jsonrpc:s.literal($)}).merge(E).strict(),Ue=o=>ze.safeParse(o).success,Ve=s.object({jsonrpc:s.literal($),id:q,result:T}).strict(),be=o=>Ve.safeParse(o).success,g;(function(o){o[o.ConnectionClosed=-32e3]="ConnectionClosed",o[o.RequestTimeout=-32001]="RequestTimeout",o[o.ParseError=-32700]="ParseError",o[o.InvalidRequest=-32600]="InvalidRequest",o[o.MethodNotFound=-32601]="MethodNotFound",o[o.InvalidParams=-32602]="InvalidParams",o[o.InternalError=-32603]="InternalError"})(g||(g={}));var Xe=s.object({jsonrpc:s.literal($),id:q,error:s.object({code:s.number().int(),message:s.string(),data:s.optional(s.unknown())})}).strict(),Ge=o=>Xe.safeParse(o).success,Je=s.union([Fe,ze,Ve,Xe]),F=T.strict(),Z=E.extend({method:s.literal("notifications/cancelled"),params:M.extend({requestId:q,reason:s.string().optional()})}),Be=s.object({name:s.string(),version:s.string()}).passthrough(),Jt=s.object({experimental:s.optional(s.object({}).passthrough()),sampling:s.optional(s.object({}).passthrough()),roots:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough())}).passthrough(),_e=S.extend({method:s.literal("initialize"),params:R.extend({protocolVersion:s.string(),capabilities:Jt,clientInfo:Be})});var Bt=s.object({experimental:s.optional(s.object({}).passthrough()),logging:s.optional(s.object({}).passthrough()),completions:s.optional(s.object({}).passthrough()),prompts:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough()),resources:s.optional(s.object({subscribe:s.optional(s.boolean()),listChanged:s.optional(s.boolean())}).passthrough()),tools:s.optional(s.object({listChanged:s.optional(s.boolean())}).passthrough())}).passthrough(),Kt=T.extend({protocolVersion:s.string(),capabilities:Bt,serverInfo:Be,instructions:s.optional(s.string())}),ve=E.extend({method:s.literal("notifications/initialized")});var z=S.extend({method:s.literal("ping")}),Wt=s.object({progress:s.number(),total:s.optional(s.number())}).passthrough(),U=E.extend({method:s.literal("notifications/progress"),params:M.merge(Wt).extend({progressToken:$e})}),V=S.extend({params:R.extend({cursor:s.optional(qe)}).optional()}),X=T.extend({nextCursor:s.optional(qe)}),Ke=s.object({uri:s.string(),mimeType:s.optional(s.string())}).passthrough(),We=Ke.extend({text:s.string()}),Ye=Ke.extend({blob:s.string().base64()}),Yt=s.object({uri:s.string(),name:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string())}).passthrough(),Qt=s.object({uriTemplate:s.string(),name:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string())}).passthrough(),G=V.extend({method:s.literal("resources/list")}),er=X.extend({resources:s.array(Yt)}),J=V.extend({method:s.literal("resources/templates/list")}),tr=X.extend({resourceTemplates:s.array(Qt)}),B=S.extend({method:s.literal("resources/read"),params:R.extend({uri:s.string()})}),rr=T.extend({contents:s.array(s.union([We,Ye]))}),or=E.extend({method:s.literal("notifications/resources/list_changed")}),sr=S.extend({method:s.literal("resources/subscribe"),params:R.extend({uri:s.string()})}),nr=S.extend({method:s.literal("resources/unsubscribe"),params:R.extend({uri:s.string()})}),ar=E.extend({method:s.literal("notifications/resources/updated"),params:M.extend({uri:s.string()})}),ir=s.object({name:s.string(),description:s.optional(s.string()),required:s.optional(s.boolean())}).passthrough(),cr=s.object({name:s.string(),description:s.optional(s.string()),arguments:s.optional(s.array(ir))}).passthrough(),K=V.extend({method:s.literal("prompts/list")}),lr=X.extend({prompts:s.array(cr)}),W=S.extend({method:s.literal("prompts/get"),params:R.extend({name:s.string(),arguments:s.optional(s.record(s.string()))})}),Y=s.object({type:s.literal("text"),text:s.string()}).passthrough(),Q=s.object({type:s.literal("image"),data:s.string().base64(),mimeType:s.string()}).passthrough(),ee=s.object({type:s.literal("audio"),data:s.string().base64(),mimeType:s.string()}).passthrough(),Qe=s.object({type:s.literal("resource"),resource:s.union([We,Ye])}).passthrough(),pr=s.object({role:s.enum(["user","assistant"]),content:s.union([Y,Q,ee,Qe])}).passthrough(),ur=T.extend({description:s.optional(s.string()),messages:s.array(pr)}),mr=E.extend({method:s.literal("notifications/prompts/list_changed")}),dr=s.object({title:s.optional(s.string()),readOnlyHint:s.optional(s.boolean()),destructiveHint:s.optional(s.boolean()),idempotentHint:s.optional(s.boolean()),openWorldHint:s.optional(s.boolean())}).passthrough(),fr=s.object({name:s.string(),description:s.optional(s.string()),inputSchema:s.object({type:s.literal("object"),properties:s.optional(s.object({}).passthrough())}).passthrough(),annotations:s.optional(dr)}).passthrough(),te=V.extend({method:s.literal("tools/list")}),hr=X.extend({tools:s.array(fr)}),et=T.extend({content:s.array(s.union([Y,Q,ee,Qe])),isError:s.boolean().default(!1).optional()}),Jr=et.or(T.extend({toolResult:s.unknown()})),re=S.extend({method:s.literal("tools/call"),params:R.extend({name:s.string(),arguments:s.optional(s.record(s.unknown()))})}),gr=E.extend({method:s.literal("notifications/tools/list_changed")}),tt=s.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),yr=S.extend({method:s.literal("logging/setLevel"),params:R.extend({level:tt})}),br=E.extend({method:s.literal("notifications/message"),params:M.extend({level:tt,logger:s.optional(s.string()),data:s.unknown()})}),_r=s.object({name:s.string().optional()}).passthrough(),vr=s.object({hints:s.optional(s.array(_r)),costPriority:s.optional(s.number().min(0).max(1)),speedPriority:s.optional(s.number().min(0).max(1)),intelligencePriority:s.optional(s.number().min(0).max(1))}).passthrough(),xr=s.object({role:s.enum(["user","assistant"]),content:s.union([Y,Q,ee])}).passthrough(),Sr=S.extend({method:s.literal("sampling/createMessage"),params:R.extend({messages:s.array(xr),systemPrompt:s.optional(s.string()),includeContext:s.optional(s.enum(["none","thisServer","allServers"])),temperature:s.optional(s.number()),maxTokens:s.number().int(),stopSequences:s.optional(s.array(s.string())),metadata:s.optional(s.object({}).passthrough()),modelPreferences:s.optional(vr)})}),xe=T.extend({model:s.string(),stopReason:s.optional(s.enum(["endTurn","stopSequence","maxTokens"]).or(s.string())),role:s.enum(["user","assistant"]),content:s.discriminatedUnion("type",[Y,Q,ee])}),Pr=s.object({type:s.literal("ref/resource"),uri:s.string()}).passthrough(),Rr=s.object({type:s.literal("ref/prompt"),name:s.string()}).passthrough(),oe=S.extend({method:s.literal("completion/complete"),params:R.extend({ref:s.union([Rr,Pr]),argument:s.object({name:s.string(),value:s.string()}).passthrough()})}),Tr=T.extend({completion:s.object({values:s.array(s.string()).max(100),total:s.optional(s.number().int()),hasMore:s.optional(s.boolean())}).passthrough()}),wr=s.object({uri:s.string().startsWith("file://"),name:s.optional(s.string())}).passthrough(),Cr=S.extend({method:s.literal("roots/list")}),Se=T.extend({roots:s.array(wr)}),kr=E.extend({method:s.literal("notifications/roots/list_changed")}),Br=s.union([z,_e,oe,yr,W,K,G,J,B,sr,nr,re,te]),Kr=s.union([Z,U,ve,kr]),Wr=s.union([F,xe,Se]),Yr=s.union([z,Sr,Cr]),Qr=s.union([Z,U,br,ar,or,gr,mr]),eo=s.union([F,Kt,Tr,ur,lr,er,tr,rr,et,hr]),y=class extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}};var Er=6e4,se=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(Z,t=>{let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}),this.setNotificationHandler(U,t=>{this._onprogress(t)}),this.setRequestHandler(z,t=>({}))}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_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(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)=>{be(t)||Ge(t)?this._onresponse(t):Ze(t)?this._onrequest(t,r):Ue(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(g.ConnectionClosed,"Connection closed");for(let n of t.values())n(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(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){var r,n,i,a;let c=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(c===void 0){(n=this._transport)===null||n===void 0||n.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 l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let _={signal:l.signal,sessionId:(i=this._transport)===null||i===void 0?void 0:i.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:h=>this.notification(h,{relatedRequestId:e.id}),sendRequest:(h,x,j)=>this.request(h,x,{...j,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>c(e,_)).then(h=>{var x;if(!l.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({result:h,jsonrpc:"2.0",id:e.id})},h=>{var x,j;if(!l.signal.aborted)return(x=this._transport)===null||x===void 0?void 0:x.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:g.InternalError,message:(j=h.message)!==null&&j!==void 0?j:"Internal error"}})}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),c=this._timeoutInfo.get(n);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){a(l);return}i(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),be(e))r(e);else{let n=new y(e.error.code,e.error.message,e.error.data);r(n)}}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:n,resumptionToken:i,onresumptiontoken:a}=r??{};return new Promise((c,l)=>{var _,h,x,j,ge;if(!this._transport){l(new Error("Not connected"));return}((_=this._options)===null||_===void 0?void 0:_.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(h=r?.signal)===null||h===void 0||h.throwIfAborted();let k=this._requestMessageId++,Me={...e,jsonrpc:"2.0",id:k};r?.onprogress&&(this._progressHandlers.set(k,r.onprogress),Me.params={...e.params,_meta:{progressToken:k}});let Le=P=>{var A;this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(P)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(P)};this._responseHandlers.set(k,P=>{var A;if(!(!((A=r?.signal)===null||A===void 0)&&A.aborted)){if(P instanceof Error)return l(P);try{let I=t.parse(P.result);c(I)}catch(I){l(I)}}}),(x=r?.signal)===null||x===void 0||x.addEventListener("abort",()=>{var P;Le((P=r?.signal)===null||P===void 0?void 0:P.reason)});let De=(j=r?.timeout)!==null&&j!==void 0?j:Er,Xt=()=>Le(new y(g.RequestTimeout,"Request timed out",{timeout:De}));this._setupTimeout(k,De,r?.maxTotalTimeout,Xt,(ge=r?.resetTimeoutOnProgress)!==null&&ge!==void 0?ge:!1),this._transport.send(Me,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(P=>{this._cleanupTimeout(k),l(P)})})}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,(n,i)=>Promise.resolve(t(e.parse(n),i)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function rt(o,e){return Object.entries(e).reduce((t,[r,n])=>(n&&typeof n=="object"?t[r]=t[r]?{...t[r],...n}:n:t[r]=n,t),{...o})}var ne=class extends se{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(_e,n=>this._oninitialize(n)),this.setNotificationHandler(ve,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rt(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:He.includes(t)?t:ye,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"},F)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},xe,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Se,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 st=Symbol("Let zodToJsonSchema decide on which parser to use");var ot={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"},nt=o=>typeof o=="string"?{...ot,name:o}:{...ot,...o};var at=o=>{let e=nt(o),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Pe(o,e,t,r){r?.errorMessages&&t&&(o.errorMessage={...o.errorMessage,[e]:t})}function f(o,e,t,r,n){o[e]=t,Pe(o,e,r,n)}import{ZodFirstPartyTypeKind as d}from"zod";function it(){return{}}import{ZodFirstPartyTypeKind as jr}from"zod";function ct(o,e){let t={type:"array"};return o.type?._def&&o.type?._def?.typeName!==jr.ZodAny&&(t.items=m(o.type._def,{...e,currentPath:[...e.currentPath,"items"]})),o.minLength&&f(t,"minItems",o.minLength.value,o.minLength.message,e),o.maxLength&&f(t,"maxItems",o.maxLength.value,o.maxLength.message,e),o.exactLength&&(f(t,"minItems",o.exactLength.value,o.exactLength.message,e),f(t,"maxItems",o.exactLength.value,o.exactLength.message,e)),t}function lt(o,e){let t={type:"integer",format:"int64"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}function pt(){return{type:"boolean"}}function ae(o,e){return m(o.type._def,e)}var ut=(o,e)=>m(o.innerType._def,e);function Re(o,e,t){let r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,i)=>Re(o,e,n))};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 Ar(o,e)}}var Ar=(o,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let r of o.checks)switch(r.kind){case"min":f(t,"minimum",r.value,r.message,e);break;case"max":f(t,"maximum",r.value,r.message,e);break}return t};function mt(o,e){return{...m(o.innerType._def,e),default:o.defaultValue()}}function dt(o,e){return e.effectStrategy==="input"?m(o.schema._def,e):{}}function ft(o){return{type:"string",enum:Array.from(o.values)}}var Nr=o=>"type"in o&&o.type==="string"?!1:"allOf"in o;function ht(o,e){let t=[m(o.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),m(o.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return t.forEach(i=>{if(Nr(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:c,...l}=i;a=l}else r=void 0;n.push(a)}}),n.length?{allOf:n,...r}:void 0}function gt(o,e){let t=typeof o.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(o.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[o.value]}:{type:t==="bigint"?"integer":t,const:o.value}}import{ZodFirstPartyTypeKind as L}from"zod";var Te,w={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Te===void 0&&(Te=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Te),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ie(o,e){let t={type:"string"};if(o.checks)for(let r of o.checks)switch(r.kind){case"min":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":C(t,"email",r.message,e);break;case"format:idn-email":C(t,"idn-email",r.message,e);break;case"pattern:zod":v(t,w.email,r.message,e);break}break;case"url":C(t,"uri",r.message,e);break;case"uuid":C(t,"uuid",r.message,e);break;case"regex":v(t,r.regex,r.message,e);break;case"cuid":v(t,w.cuid,r.message,e);break;case"cuid2":v(t,w.cuid2,r.message,e);break;case"startsWith":v(t,RegExp(`^${we(r.value,e)}`),r.message,e);break;case"endsWith":v(t,RegExp(`${we(r.value,e)}$`),r.message,e);break;case"datetime":C(t,"date-time",r.message,e);break;case"date":C(t,"date",r.message,e);break;case"time":C(t,"time",r.message,e);break;case"duration":C(t,"duration",r.message,e);break;case"length":f(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),f(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{v(t,RegExp(we(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&C(t,"ipv4",r.message,e),r.version!=="v4"&&C(t,"ipv6",r.message,e);break}case"base64url":v(t,w.base64url,r.message,e);break;case"jwt":v(t,w.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&v(t,w.ipv4Cidr,r.message,e),r.version!=="v4"&&v(t,w.ipv6Cidr,r.message,e);break}case"emoji":v(t,w.emoji(),r.message,e);break;case"ulid":{v(t,w.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{C(t,"binary",r.message,e);break}case"contentEncoding:base64":{f(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{v(t,w.base64,r.message,e);break}}break}case"nanoid":v(t,w.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function we(o,e){return e.patternStrategy==="escape"?Ir(o):o}var Or=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ir(o){let e="";for(let t=0;t<o.length;t++)Or.has(o[t])||(e+="\\"),e+=o[t];return e}function C(o,e,t,r){o.format||o.anyOf?.some(n=>n.format)?(o.anyOf||(o.anyOf=[]),o.format&&(o.anyOf.push({format:o.format,...o.errorMessage&&r.errorMessages&&{errorMessage:{format:o.errorMessage.format}}}),delete o.format,o.errorMessage&&(delete o.errorMessage.format,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):f(o,"format",e,t,r)}function v(o,e,t,r){o.pattern||o.allOf?.some(n=>n.pattern)?(o.allOf||(o.allOf=[]),o.pattern&&(o.allOf.push({pattern:o.pattern,...o.errorMessage&&r.errorMessages&&{errorMessage:{pattern:o.errorMessage.pattern}}}),delete o.pattern,o.errorMessage&&(delete o.errorMessage.pattern,Object.keys(o.errorMessage).length===0&&delete o.errorMessage)),o.allOf.push({pattern:yt(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):f(o,"pattern",yt(e,r),t,r)}function yt(o,e){if(!e.applyRegexFlags||!o.flags)return o.source;let t={i:o.flags.includes("i"),m:o.flags.includes("m"),s:o.flags.includes("s")},r=t.i?o.source.toLowerCase():o.source,n="",i=!1,a=!1,c=!1;for(let l=0;l<r.length;l++){if(i){n+=r[l],i=!1;continue}if(t.i){if(a){if(r[l].match(/[a-z]/)){c?(n+=r[l],n+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(n+=r[l],c=!0):n+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){n+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(t.m){if(r[l]==="^"){n+=`(^|(?<=[\r
2
- ]))`;continue}else if(r[l]==="$"){n+=`($|(?=[\r
3
- ]))`;continue}}if(t.s&&r[l]==="."){n+=a?`${r[l]}\r
4
- `:`[${r[l]}\r
5
- ]`;continue}n+=r[l],r[l]==="\\"?i=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),o.source}return n}function ce(o,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&o.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:o.keyType._def.values,properties:o.keyType._def.values.reduce((r,n)=>({...r,[n]:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(o.keyType?._def.typeName===L.ZodString&&o.keyType._def.checks?.length){let{type:r,...n}=ie(o.keyType._def,e);return{...t,propertyNames:n}}else{if(o.keyType?._def.typeName===L.ZodEnum)return{...t,propertyNames:{enum:o.keyType._def.values}};if(o.keyType?._def.typeName===L.ZodBranded&&o.keyType._def.type._def.typeName===L.ZodString&&o.keyType._def.type._def.checks?.length){let{type:r,...n}=ae(o.keyType._def,e);return{...t,propertyNames:n}}}return t}function bt(o,e){if(e.mapStrategy==="record")return ce(o,e);let t=m(o.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function _t(o){let e=o.values,r=Object.keys(o.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(r.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:r}}function vt(){return{not:{}}}function xt(o){return o.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pt(o,e){if(e.target==="openApi3")return St(o,e);let t=o.options instanceof Map?Array.from(o.options.values()):o.options;if(t.every(r=>r._def.typeName in D&&(!r._def.checks||!r._def.checks.length))){let r=t.reduce((n,i)=>{let a=D[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=t.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(r.length===t.length){let n=r.filter((i,a,c)=>c.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,n)=>[...r,...n._def.values.filter(i=>!r.includes(i))],[])};return St(o,e)}var St=(o,e)=>{let t=(o.options instanceof Map?Array.from(o.options.values()):o.options).map((r,n)=>m(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function Rt(o,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(o.innerType._def.typeName)&&(!o.innerType._def.checks||!o.innerType._def.checks.length))return e.target==="openApi3"?{type:D[o.innerType._def.typeName],nullable:!0}:{type:[D[o.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=m(o.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Tt(o,e){let t={type:"number"};if(!o.checks)return t;for(let r of o.checks)switch(r.kind){case"int":t.type="integer",Pe(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?f(t,"minimum",r.value,r.message,e):f(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),f(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?f(t,"maximum",r.value,r.message,e):f(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),f(t,"maximum",r.value,r.message,e));break;case"multipleOf":f(t,"multipleOf",r.value,r.message,e);break}return t}import{ZodOptional as Mr}from"zod";function wt(o,e){let t=e.target==="openAi",r={type:"object",properties:{}},n=[],i=o.shape();for(let c in i){let l=i[c];if(l===void 0||l._def===void 0)continue;let _=Dr(l);_&&t&&(l instanceof Mr&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),_=!1);let h=m(l._def,{...e,currentPath:[...e.currentPath,"properties",c],propertyPath:[...e.currentPath,"properties",c]});h!==void 0&&(r.properties[c]=h,_||n.push(c))}n.length&&(r.required=n);let a=Lr(o,e);return a!==void 0&&(r.additionalProperties=a),r}function Lr(o,e){if(o.catchall._def.typeName!=="ZodNever")return m(o.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(o.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dr(o){try{return o.isOptional()}catch{return!0}}var Ct=(o,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return m(o.innerType._def,e);let t=m(o.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var kt=(o,e)=>{if(e.pipeStrategy==="input")return m(o.in._def,e);if(e.pipeStrategy==="output")return m(o.out._def,e);let t=m(o.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=m(o.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(n=>n!==void 0)}};function Et(o,e){return m(o.type._def,e)}function jt(o,e){let r={type:"array",uniqueItems:!0,items:m(o.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return o.minSize&&f(r,"minItems",o.minSize.value,o.minSize.message,e),o.maxSize&&f(r,"maxItems",o.maxSize.value,o.maxSize.message,e),r}function At(o,e){return o.rest?{type:"array",minItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:m(o.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:o.items.length,maxItems:o.items.length,items:o.items.map((t,r)=>m(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Nt(){return{not:{}}}function Ot(){return{}}var It=(o,e)=>m(o.innerType._def,e);var Mt=(o,e,t)=>{switch(e){case d.ZodString:return ie(o,t);case d.ZodNumber:return Tt(o,t);case d.ZodObject:return wt(o,t);case d.ZodBigInt:return lt(o,t);case d.ZodBoolean:return pt();case d.ZodDate:return Re(o,t);case d.ZodUndefined:return Nt();case d.ZodNull:return xt(t);case d.ZodArray:return ct(o,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return Pt(o,t);case d.ZodIntersection:return ht(o,t);case d.ZodTuple:return At(o,t);case d.ZodRecord:return ce(o,t);case d.ZodLiteral:return gt(o,t);case d.ZodEnum:return ft(o);case d.ZodNativeEnum:return _t(o);case d.ZodNullable:return Rt(o,t);case d.ZodOptional:return Ct(o,t);case d.ZodMap:return bt(o,t);case d.ZodSet:return jt(o,t);case d.ZodLazy:return()=>o.getter()._def;case d.ZodPromise:return Et(o,t);case d.ZodNaN:case d.ZodNever:return vt();case d.ZodEffects:return dt(o,t);case d.ZodAny:return it();case d.ZodUnknown:return Ot();case d.ZodDefault:return mt(o,t);case d.ZodBranded:return ae(o,t);case d.ZodReadonly:return It(o,t);case d.ZodCatch:return ut(o,t);case d.ZodPipeline:return kt(o,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return;default:return(r=>{})(e)}};function m(o,e,t=!1){let r=e.seen.get(o);if(e.override){let c=e.override?.(o,e,r,t);if(c!==st)return c}if(r&&!t){let c=Hr(r,e);if(c!==void 0)return c}let n={def:o,path:e.currentPath,jsonSchema:void 0};e.seen.set(o,n);let i=Mt(o,o.typeName,e),a=typeof i=="function"?m(i(),e):i;if(a&&qr(o,e,a),e.postProcess){let c=e.postProcess(a,o,e);return n.jsonSchema=a,c}return n.jsonSchema=a,a}var Hr=(o,e)=>{switch(e.$refStrategy){case"root":return{$ref:o.path.join("/")};case"relative":return{$ref:$r(e.currentPath,o.path)};case"none":case"seen":return o.path.length<e.currentPath.length&&o.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},$r=(o,e)=>{let t=0;for(;t<o.length&&t<e.length&&o[t]===e[t];t++);return[(o.length-t).toString(),...e.slice(t)].join("/")},qr=(o,e,t)=>(o.description&&(t.description=o.description,e.markdownDescription&&(t.markdownDescription=o.description)),t);var Ce=(o,e)=>{let t=at(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[_,h])=>({...l,[_]:m(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,_]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=m(o._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a);let c=n===void 0?r?{...i,[t.definitionPath]:r}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...r,[n]:i}};return t.target==="jsonSchema7"?c.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c};import{z as le}from"zod";import{ZodType as Fr}from"zod";var ke;(function(o){o.Completable="McpCompletable"})(ke||(ke={}));var O=class extends Fr{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};O.create=(o,e)=>new O({type:o,typeName:ke.Completable,complete:e.complete,...Zr(e)});function Zr(o){if(!o)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:n}=o;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,c)=>{var l,_;let{message:h}=o;return a.code==="invalid_enum_value"?{message:h??c.defaultError}:typeof c.data>"u"?{message:(l=h??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(_=h??t)!==null&&_!==void 0?_:c.defaultError}},description:n}}var ue=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ne(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(te.shape.method.value),this.server.assertCanSetRequestHandler(re.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(te,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Ce(t.inputSchema,{strictUnions:!0}):zr,annotations:t.annotations}))})),this.server.setRequestHandler(re,async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new y(g.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Tool ${e.params.name} disabled`);if(r.inputSchema){let n=await r.inputSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new y(g.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${n.error.message}`);let i=n.data,a=r.callback;try{return await Promise.resolve(a(i,t))}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}else{let n=r.callback;try{return await Promise.resolve(n(t))}catch(i){return{content:[{type:"text",text:i instanceof Error?i.message:String(i)}],isError:!0}}}}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(oe.shape.method.value),this.server.setRequestHandler(oe,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new y(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 y(g.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return pe;let n=r.argsSchema.shape[e.params.argument.name];if(!(n instanceof O))return pe;let a=await n._def.complete(e.params.argument.value);return Dt(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return pe;throw new y(g.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return pe;let i=await n(e.params.argument.value);return Dt(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(G.shape.method.value),this.server.assertCanSetRequestHandler(J.shape.method.value),this.server.assertCanSetRequestHandler(B.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(G,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),n=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(t);for(let c of a.resources)n.push({...c,...i.metadata})}return{resources:[...r,...n]}}),this.server.setRequestHandler(J,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(B,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new y(g.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(r.toString());if(a)return i.readCallback(r,a,t)}throw new y(g.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.assertCanSetRequestHandler(W.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(K,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,description:t.description,arguments:t.argsSchema?Vr(t.argsSchema):void 0}))})),this.server.setRequestHandler(W,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new y(g.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new y(g.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=await r.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new y(g.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);let i=n.data,a=r.callback;return await Promise.resolve(a(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;typeof r[0]=="object"&&(n=r.shift());let i=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a={name:e,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:c=>{typeof c.uri<"u"&&c.uri!==t&&(delete this._registeredResources[t],c.uri&&(this._registeredResources[c.uri]=a)),typeof c.name<"u"&&(a.name=c.name),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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 n,i;if(t.length>1){let l=t[0];Lt(l)?(n=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!Lt(t[0])&&(i=t.shift())):typeof l=="object"&&l!==null&&(i=t.shift())}let a=t[0],c={description:r,inputSchema:n===void 0?void 0:le.object(n),annotations:i,callback:a,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=c)),typeof l.description<"u"&&(c.description=l.description),typeof l.paramsSchema<"u"&&(c.inputSchema=le.object(l.paramsSchema)),typeof l.callback<"u"&&(c.callback=l.callback),typeof l.annotations<"u"&&(c.annotations=l.annotations),typeof l.enabled<"u"&&(c.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}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 n;t.length>1&&(n=t.shift());let i=t[0],a={description:r,argsSchema:n===void 0?void 0:le.object(n),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredPrompts[e],c.name&&(this._registeredPrompts[c.name]=a)),typeof c.description<"u"&&(a.description=c.description),typeof c.argsSchema<"u"&&(a.argsSchema=le.object(c.argsSchema)),typeof c.callback<"u"&&(a.callback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.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 zr={type:"object"};function Lt(o){return typeof o!="object"||o===null?!1:Object.keys(o).length===0||Object.values(o).some(Ur)}function Ur(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function Vr(o){return Object.entries(o.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))}function Dt(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var pe={completion:{values:[],hasMore:!1}};var me=process.env.personalToken||""||"",Ht="F2C MCP",$t="0.2.0";var Ee=class{constructor(){this.f2cHost="https://f2c-figma-api.yy.com/api";this.personalToken=me}async nodeToCode(e){let t={fileKey:e.fileKey,nodeIds:e.ids,personal_token:e.personalToken||this.personalToken,option:{cssFramework:"inlinecss",imgFormat:e.imgFormat||"png",scaleSize:e.scaleSize||2},format:"files"};e.format==="react-cssmodules"?t.option.cssFramework="cssmodules":e.format==="react-tailwind"&&(t.option.cssFramework="tailwindcss");let r=this.opToUrl(`${this.f2cHost}/nodes`,t);return this.fetch(r,"json")}async fetch(e,t="json"){try{let n=await fetch(e,{method:"GET"});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return t==="text"?await n.text():await n.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={}){if(Object.keys(t).length===0)return e;let r=new URL(e);for(let[n,i]of Object.entries(t))if(typeof i=="object"&&i!==null)for(let[a,c]of Object.entries(i))r.searchParams.append(`${n}[${a}]`,c);else r.searchParams.append(n,i);return r.toString()}},qt=new Ee;import{z as N}from"zod";import je from"fs";import H from"path";var Ae=class{constructor(){this.imgFormat="png"}setImgFormat(e){this.imgFormat=e}async downloadImage(e,t){try{je.existsSync(t.localPath)||je.mkdirSync(t.localPath,{recursive:!0});let r=`${t.fileName}.${this.imgFormat}`,n=H.join(t.localPath,r),i=await fetch(e);if(!i.ok)throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${i.status} ${i.statusText}`);let a=await i.arrayBuffer();return je.writeFileSync(n,new Uint8Array(a)),H.join(H.basename(t.localPath),r).replace(/\\/g,"/")}catch(r){throw console.error("\u56FE\u7247\u4E0B\u8F7D\u9519\u8BEF:",r),r}}async processContent(e,t){t=H.join(t,"images");try{let r=/https:\/\/figma-alpha-api\.s3\.us-west-2\.amazonaws\.com\/images\/[a-f0-9-]+/g,n=e.match(r);if(!n)return e;let i=e;for(let a of n){let c=H.basename(a),l=await this.downloadImage(a,{localPath:t,fileName:c});i=i.replace(a,l)}return i}catch(r){throw console.error("\u5185\u5BB9\u5904\u7406\u9519\u8BEF:",r),r}}},Ne=new Ae;var Ft=o=>{o.tool("figma_to_code","Transform Figma designs into production-ready code. This tool converts selected Figma nodes into HTML, React with CSS Modules, or React with Tailwind CSS, enabling seamless design-to-code workflow.",{fileKey:N.string().describe("The Figma file identifier found in the file URL (e.g., https://www.figma.com/file/XXXXXXXXXXXX/). Extract the XXXXXXXXXXXX portion as the fileKey."),ids:N.string().describe('Comma-separated list of Figma node IDs for conversion. To obtain node IDs, select elements in Figma, right-click and select "Copy/Paste as" \u2192 "Copy ID".'),format:N.enum(["html","react-cssmodules","react-tailwind"]).default("html").describe('Specify the output format: "html" generates semantic HTML/CSS, "react-cssmodules" creates React components with scoped CSS modules, "react-tailwind" produces React components with utility-first Tailwind classes.'),personalToken:N.string().optional().describe("Figma personal access token for API authentication"),localPath:N.string().optional().describe("Absolute path for image asset storage. Directory will be created if non-existent. Path must follow OS-specific format without special character escaping."),imgFormat:N.enum(["png","jpg","svg"]).default("png").describe('Export format for image assets: "png" for lossless quality, "jpg" for compressed files, or "svg" for vector graphics.'),scaleSize:N.number().min(1).max(4).default(2).describe("Image export scale factor (1-4). Higher values yield better quality at the cost of larger file sizes.")},async e=>{try{let t=await qt.nodeToCode(e)||[];return e.localPath&&(Ne.setImgFormat(e.imgFormat),await Promise.all(t.map(async r=>{r.content=await Ne.processContent(r.content,e.localPath)}))),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return console.error("Tool execution error:",t),{content:[{type:"text",text:`Error: ${t.message}`}]}}})};var Oe=class{constructor(){this.figmaHost="https://api.figma.com/v1";this.personalToken=me}async files(e){let t;return e.ids?t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/nodes`,e):t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}`,e),this.fetch(t)}async images(e){let t=this.opToUrl(`${this.figmaHost}/images/${e.fileKey}`,e);return this.fetch(t)}async imageFills(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/images`,e);return this.fetch(t)}async meta(e){let t=this.opToUrl(`${this.figmaHost}/files/${e.fileKey}/meta`,e);return this.fetch(t)}async fetch(e,t="json"){try{let r={method:"GET",headers:{"X-FIGMA-TOKEN":this.personalToken}},n=await fetch(e,r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return t==="text"?await n.text():await n.json()}catch(r){throw console.error("HTTP error",r),r}}opToUrl(e,t={},r=["fileKey","personalToken"]){if(Object.keys(t).length===0)return e;t.personalToken&&(this.personalToken=t.personalToken);let n=new URL(e);for(let[i,a]of Object.entries(t))r.includes(i)||n.searchParams.append(i,a);return n.toString()}},Ie=new Oe;import{z as b}from"zod";var Zt=o=>{o.tool("figma_get_file_data","Get detailed information about a Figma file",{fileKey:b.string().describe("Unique identifier of the Figma file"),ids:b.string().describe("List of node IDs to retrieve, comma separated"),personalToken:b.string().optional().describe("Your Figma personal access token"),version:b.string().optional().describe("Specify the version to return"),depth:b.number().optional().describe("Specify the depth of nodes to return"),geometry:b.enum(["paths"]).optional().describe("Specify whether to include geometry path data"),plugin_data:b.string().optional().describe("Specify plugin data to return"),branch_data:b.boolean().optional().describe("Specify whether to return branch data")},async e=>{try{let t=await Ie.files(e);return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}]}}}),o.tool("figma_get_images","Get images of Figma nodes",{fileKey:b.string().describe("Unique identifier of the Figma file"),ids:b.string().describe("Node IDs to get images for, comma separated"),format:b.enum(["jpg","png","svg","pdf"]).optional().describe("Image format, e.g., png, jpg, svg"),scale:b.number().optional().describe("Image scale factor"),svg_include_id:b.boolean().optional().describe("Whether SVG includes ID"),svg_simplify_stroke:b.boolean().optional().describe("Whether to simplify SVG strokes"),use_absolute_bounds:b.boolean().optional().describe("Whether to use absolute bounds"),version:b.string().optional().describe("Specify the version to return"),personalToken:b.string().optional().describe("Your Figma personal access token")},async e=>{try{let t=await Ie.images(e);return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}]}}})};var de=new ue({name:Ht,version:$t},{capabilities:{logging:{}}});Zt(de);Ft(de);import Ut from"node:process";var fe=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),Xr(t)}clear(){this._buffer=void 0}};function Xr(o){return Je.parse(JSON.parse(o))}function zt(o){return JSON.stringify(o)+`
7
- `}var he=class{constructor(e=Ut.stdin,t=Ut.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new fe,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{var n;(n=this.onerror)===null||n===void 0||n.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=zt(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}};async function Vt(o){try{let e=new he;await o.connect(e)}catch(e){console.log(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32e3,message:`Server startup failed: ${e.message}`}})),process.exit(1)}}Vt(de);
@@ -1,2 +0,0 @@
1
-
2
- export { }
@@ -1,2 +0,0 @@
1
-
2
- export { }