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