@youware-labs/figma-pilot-mcp 0.1.6 → 0.1.7

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 CHANGED
@@ -1,6 +1,8 @@
1
1
  # @youware-labs/figma-pilot-mcp
2
2
 
3
- MCP server that enables AI agents (Claude, etc.) to create and modify Figma designs through natural language.
3
+ MCP server that enables AI agents (Claude, Cursor, Codex, and any MCP-compatible client) to create and modify Figma designs through natural language.
4
+
5
+ **English** | [中文](../../README.zh-CN.md)
4
6
 
5
7
  ## Quick Start
6
8
 
@@ -11,9 +13,17 @@ MCP server that enables AI agents (Claude, etc.) to create and modify Figma desi
11
13
  claude mcp add figma-pilot -- npx @youware-labs/figma-pilot-mcp
12
14
  ```
13
15
 
14
- **Claude Desktop / Cursor / Other MCP Clients:**
16
+ **Claude Desktop:**
17
+
18
+ Add to your MCP config file (usually `~/.config/claude/claude_desktop_config.json` on macOS/Linux, or `%APPDATA%\Claude\claude_desktop_config.json` on Windows):
19
+
20
+ **Cursor:**
21
+
22
+ Add to your Cursor MCP config file (usually `~/.cursor/mcp.json` or in Cursor settings):
23
+
24
+ **Codex / Other MCP Clients:**
15
25
 
16
- Add to your MCP config file:
26
+ Add to your MCP config file (location varies by client):
17
27
  ```json
18
28
  {
19
29
  "mcpServers": {
@@ -35,7 +45,7 @@ Add to your MCP config file:
35
45
 
36
46
  ### 3. Start Using
37
47
 
38
- Once the MCP is configured and the Figma plugin is running, you can ask Claude to:
48
+ Once the MCP is configured and the Figma plugin is running, you can ask your AI agent to:
39
49
  - "Create a login form in Figma"
40
50
  - "Add a navigation bar with logo and menu items"
41
51
  - "Change the selected element's color to blue"
@@ -88,9 +98,10 @@ figma_export({ target: "selection", format: "png", scale: 2 })
88
98
 
89
99
  ```
90
100
  ┌─────────────┐ stdio ┌─────────────────┐ HTTP ┌──────────────┐
91
- Claude │ ◄────────────► │ MCP Server │ ◄───────────► │ Figma Plugin │
92
- (or AI) │ │ (with bridge) │ port 38451 │ │
93
- └─────────────┘ └─────────────────┘ └──────────────┘
101
+ MCP Client │ ◄────────────► │ MCP Server │ ◄───────────► │ Figma Plugin │
102
+ │(Claude/Cursor│ │ (with bridge) │ port 38451 │ │
103
+ │ /Codex/etc)│ └─────────────────┘ └──────────────┘
104
+ └─────────────┘
94
105
  ```
95
106
 
96
107
  The MCP server includes a built-in HTTP bridge that the Figma plugin connects to. No separate server process needed.
package/dist/index.js CHANGED
@@ -46,4 +46,4 @@ var N3=Object.create;var{getPrototypeOf:q3,defineProperty:Q6,getOwnPropertyNames
46
46
 
47
47
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of Q.seen.entries()){let $=H[1];if(X===H[0]){G(H);continue}if(Q.external){let z=Q.external.registry.get(H[0])?.id;if(X!==H[0]&&z){G(H);continue}}if(Q.metadataRegistry.get(H[0])?.id){G(H);continue}if($.cycle){G(H);continue}if($.count>1){if(Q.reused==="ref"){G(H);continue}}}}function _6(Q,X){let Y=Q.seen.get(X);if(!Y)throw Error("Unprocessed schema. This is a bug in Zod.");let W=(H)=>{let $=Q.seen.get(H);if($.ref===null)return;let K=$.def??$.schema,z={...K},B=$.ref;if($.ref=null,B){W(B);let F=Q.seen.get(B),L=F.schema;if(L.$ref&&(Q.target==="draft-07"||Q.target==="draft-04"||Q.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(L);else Object.assign(K,L);if(Object.assign(K,z),H._zod.parent===B)for(let Z in K){if(Z==="$ref"||Z==="allOf")continue;if(!(Z in z))delete K[Z]}if(L.$ref)for(let Z in K){if(Z==="$ref"||Z==="allOf")continue;if(Z in F.def&&JSON.stringify(K[Z])===JSON.stringify(F.def[Z]))delete K[Z]}}let A=H._zod.parent;if(A&&A!==B){W(A);let F=Q.seen.get(A);if(F?.schema.$ref){if(K.$ref=F.schema.$ref,F.def)for(let L in K){if(L==="$ref"||L==="allOf")continue;if(L in F.def&&JSON.stringify(K[L])===JSON.stringify(F.def[L]))delete K[L]}}}Q.override({zodSchema:H,jsonSchema:K,path:$.path??[]})};for(let H of[...Q.seen.entries()].reverse())W(H[0]);let J={};if(Q.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";else if(Q.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";else if(Q.target==="openapi-3.0");if(Q.external?.uri){let H=Q.external.registry.get(X)?.id;if(!H)throw Error("Schema is missing an `id` property");J.$id=Q.external.uri(H)}Object.assign(J,Y.def??Y.schema);let G=Q.external?.defs??{};for(let H of Q.seen.entries()){let $=H[1];if($.def&&$.defId)G[$.defId]=$.def}if(Q.external);else if(Object.keys(G).length>0)if(Q.target==="draft-2020-12")J.$defs=G;else J.definitions=G;try{let H=JSON.parse(JSON.stringify(J));return Object.defineProperty(H,"~standard",{value:{...X["~standard"],jsonSchema:{input:r1(X,"input",Q.processors),output:r1(X,"output",Q.processors)}},enumerable:!1,writable:!1}),H}catch(H){throw Error("Error converting schema to JSON.")}}function K0(Q,X){let Y=X??{seen:new Set};if(Y.seen.has(Q))return!1;Y.seen.add(Q);let W=Q._zod.def;if(W.type==="transform")return!0;if(W.type==="array")return K0(W.element,Y);if(W.type==="set")return K0(W.valueType,Y);if(W.type==="lazy")return K0(W.getter(),Y);if(W.type==="promise"||W.type==="optional"||W.type==="nonoptional"||W.type==="nullable"||W.type==="readonly"||W.type==="default"||W.type==="prefault")return K0(W.innerType,Y);if(W.type==="intersection")return K0(W.left,Y)||K0(W.right,Y);if(W.type==="record"||W.type==="map")return K0(W.keyType,Y)||K0(W.valueType,Y);if(W.type==="pipe")return K0(W.in,Y)||K0(W.out,Y);if(W.type==="object"){for(let J in W.shape)if(K0(W.shape[J],Y))return!0;return!1}if(W.type==="union"){for(let J of W.options)if(K0(J,Y))return!0;return!1}if(W.type==="tuple"){for(let J of W.items)if(K0(J,Y))return!0;if(W.rest&&K0(W.rest,Y))return!0;return!1}return!1}var MW=(Q,X={})=>(Y)=>{let W=k6({...Y,processors:X});return a(Q,W),v6(W,Q),_6(W,Q)},r1=(Q,X,Y={})=>(W)=>{let{libraryOptions:J,target:G}=W??{},H=k6({...J??{},target:G,io:X,processors:Y});return a(Q,H),v6(H,Q),_6(H,Q)};var G$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},OW=(Q,X,Y,W)=>{let J=Y;J.type="string";let{minimum:G,maximum:H,format:$,patterns:K,contentEncoding:z}=Q._zod.bag;if(typeof G==="number")J.minLength=G;if(typeof H==="number")J.maxLength=H;if($){if(J.format=G$[$]??$,J.format==="")delete J.format;if($==="time")delete J.format}if(z)J.contentEncoding=z;if(K&&K.size>0){let B=[...K];if(B.length===1)J.pattern=B[0].source;else if(B.length>1)J.allOf=[...B.map((A)=>({...X.target==="draft-07"||X.target==="draft-04"||X.target==="openapi-3.0"?{type:"string"}:{},pattern:A.source}))]}},NW=(Q,X,Y,W)=>{let J=Y,{minimum:G,maximum:H,format:$,multipleOf:K,exclusiveMaximum:z,exclusiveMinimum:B}=Q._zod.bag;if(typeof $==="string"&&$.includes("int"))J.type="integer";else J.type="number";if(typeof B==="number")if(X.target==="draft-04"||X.target==="openapi-3.0")J.minimum=B,J.exclusiveMinimum=!0;else J.exclusiveMinimum=B;if(typeof G==="number"){if(J.minimum=G,typeof B==="number"&&X.target!=="draft-04")if(B>=G)delete J.minimum;else delete J.exclusiveMinimum}if(typeof z==="number")if(X.target==="draft-04"||X.target==="openapi-3.0")J.maximum=z,J.exclusiveMaximum=!0;else J.exclusiveMaximum=z;if(typeof H==="number"){if(J.maximum=H,typeof z==="number"&&X.target!=="draft-04")if(z<=H)delete J.maximum;else delete J.exclusiveMaximum}if(typeof K==="number")J.multipleOf=K},qW=(Q,X,Y,W)=>{Y.type="boolean"};var wW=(Q,X,Y,W)=>{if(X.target==="openapi-3.0")Y.type="string",Y.nullable=!0,Y.enum=[null];else Y.type="null"};var PW=(Q,X,Y,W)=>{Y.not={}};var EW=(Q,X,Y,W)=>{};var IW=(Q,X,Y,W)=>{let J=Q._zod.def,G=y1(J.entries);if(G.every((H)=>typeof H==="number"))Y.type="number";if(G.every((H)=>typeof H==="string"))Y.type="string";Y.enum=G},bW=(Q,X,Y,W)=>{let J=Q._zod.def,G=[];for(let H of J.values)if(H===void 0){if(X.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof H==="bigint")if(X.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else G.push(Number(H));else G.push(H);if(G.length===0);else if(G.length===1){let H=G[0];if(Y.type=H===null?"null":typeof H,X.target==="draft-04"||X.target==="openapi-3.0")Y.enum=[H];else Y.const=H}else{if(G.every((H)=>typeof H==="number"))Y.type="number";if(G.every((H)=>typeof H==="string"))Y.type="string";if(G.every((H)=>typeof H==="boolean"))Y.type="boolean";if(G.every((H)=>H===null))Y.type="null";Y.enum=G}};var TW=(Q,X,Y,W)=>{if(X.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var jW=(Q,X,Y,W)=>{if(X.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var RW=(Q,X,Y,W)=>{let J=Y,G=Q._zod.def,{minimum:H,maximum:$}=Q._zod.bag;if(typeof H==="number")J.minItems=H;if(typeof $==="number")J.maxItems=$;J.type="array",J.items=a(G.element,X,{...W,path:[...W.path,"items"]})},SW=(Q,X,Y,W)=>{let J=Y,G=Q._zod.def;J.type="object",J.properties={};let H=G.shape;for(let z in H)J.properties[z]=a(H[z],X,{...W,path:[...W.path,"properties",z]});let $=new Set(Object.keys(H)),K=new Set([...$].filter((z)=>{let B=G.shape[z]._zod;if(X.io==="input")return B.optin===void 0;else return B.optout===void 0}));if(K.size>0)J.required=Array.from(K);if(G.catchall?._zod.def.type==="never")J.additionalProperties=!1;else if(!G.catchall){if(X.io==="output")J.additionalProperties=!1}else if(G.catchall)J.additionalProperties=a(G.catchall,X,{...W,path:[...W.path,"additionalProperties"]})},CW=(Q,X,Y,W)=>{let J=Q._zod.def,G=J.inclusive===!1,H=J.options.map(($,K)=>a($,X,{...W,path:[...W.path,G?"oneOf":"anyOf",K]}));if(G)Y.oneOf=H;else Y.anyOf=H},kW=(Q,X,Y,W)=>{let J=Q._zod.def,G=a(J.left,X,{...W,path:[...W.path,"allOf",0]}),H=a(J.right,X,{...W,path:[...W.path,"allOf",1]}),$=(z)=>("allOf"in z)&&Object.keys(z).length===1,K=[...$(G)?G.allOf:[G],...$(H)?H.allOf:[H]];Y.allOf=K};var vW=(Q,X,Y,W)=>{let J=Y,G=Q._zod.def;J.type="object";let H=G.keyType,K=H._zod.bag?.patterns;if(G.mode==="loose"&&K&&K.size>0){let B=a(G.valueType,X,{...W,path:[...W.path,"patternProperties","*"]});J.patternProperties={};for(let A of K)J.patternProperties[A.source]=B}else{if(X.target==="draft-07"||X.target==="draft-2020-12")J.propertyNames=a(G.keyType,X,{...W,path:[...W.path,"propertyNames"]});J.additionalProperties=a(G.valueType,X,{...W,path:[...W.path,"additionalProperties"]})}let z=H._zod.values;if(z){let B=[...z].filter((A)=>typeof A==="string"||typeof A==="number");if(B.length>0)J.required=B}},_W=(Q,X,Y,W)=>{let J=Q._zod.def,G=a(J.innerType,X,W),H=X.seen.get(Q);if(X.target==="openapi-3.0")H.ref=J.innerType,Y.nullable=!0;else Y.anyOf=[G,{type:"null"}]},xW=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);G.ref=J.innerType},gW=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);G.ref=J.innerType,Y.default=JSON.parse(JSON.stringify(J.defaultValue))},yW=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);if(G.ref=J.innerType,X.io==="input")Y._prefault=JSON.parse(JSON.stringify(J.defaultValue))},hW=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);G.ref=J.innerType;let H;try{H=J.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Y.default=H},uW=(Q,X,Y,W)=>{let J=Q._zod.def,G=X.io==="input"?J.in._zod.def.type==="transform"?J.out:J.in:J.out;a(G,X,W);let H=X.seen.get(Q);H.ref=G},fW=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);G.ref=J.innerType,Y.readOnly=!0};var x6=(Q,X,Y,W)=>{let J=Q._zod.def;a(J.innerType,X,W);let G=X.seen.get(Q);G.ref=J.innerType};function O1(Q){return!!Q._zod}function a0(Q,X){if(O1(Q))return m1(Q,X);return Q.safeParse(X)}function o9(Q){if(!Q)return;let X;if(O1(Q))X=Q._zod?.def?.shape;else X=Q.shape;if(!X)return;if(typeof X==="function")try{return X()}catch{return}return X}function lW(Q){if(O1(Q)){let G=Q._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let Y=Q._def;if(Y){if(Y.value!==void 0)return Y.value;if(Array.isArray(Y.values)&&Y.values.length>0)return Y.values[0]}let W=Q.value;if(W!==void 0)return W;return}var o1={};EX(o1,{time:()=>h6,duration:()=>u6,datetime:()=>g6,date:()=>y6,ZodISOTime:()=>pW,ZodISODuration:()=>dW,ZodISODateTime:()=>mW,ZodISODate:()=>cW});var mW=D("ZodISODateTime",(Q,X)=>{a4.init(Q,X),i.init(Q,X)});function g6(Q){return JW(mW,Q)}var cW=D("ZodISODate",(Q,X)=>{s4.init(Q,X),i.init(Q,X)});function y6(Q){return GW(cW,Q)}var pW=D("ZodISOTime",(Q,X)=>{e4.init(Q,X),i.init(Q,X)});function h6(Q){return HW(pW,Q)}var dW=D("ZodISODuration",(Q,X)=>{QY.init(Q,X),i.init(Q,X)});function u6(Q){return $W(dW,Q)}var iW=(Q,X)=>{x9.init(Q,X),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(Y)=>xX(Q,Y)},flatten:{value:(Y)=>_X(Q,Y)},addIssue:{value:(Y)=>{Q.issues.push(Y),Q.message=JSON.stringify(Q.issues,D1,2)}},addIssues:{value:(Y)=>{Q.issues.push(...Y),Q.message=JSON.stringify(Q.issues,D1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},LO=D("ZodError",iW),Z0=D("ZodError",iW,{Parent:Error});var rW=g9(Z0),nW=y9(Z0),oW=l1(Z0),tW=c1(Z0),aW=gX(Z0),sW=yX(Z0),eW=hX(Z0),QJ=uX(Z0),XJ=fX(Z0),YJ=lX(Z0),WJ=mX(Z0),JJ=cX(Z0);var n=D("ZodType",(Q,X)=>{return c.init(Q,X),Object.assign(Q["~standard"],{jsonSchema:{input:r1(Q,"input"),output:r1(Q,"output")}}),Q.toJSONSchema=MW(Q,{}),Q.def=X,Q.type=X.type,Object.defineProperty(Q,"_def",{value:X}),Q.check=(...Y)=>{return Q.clone(y.mergeDefs(X,{checks:[...X.checks??[],...Y.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},Q.with=Q.check,Q.clone=(Y,W)=>b0(Q,Y,W),Q.brand=()=>Q,Q.register=(Y,W)=>{return Y.add(Q,W),Q},Q.parse=(Y,W)=>rW(Q,Y,W,{callee:Q.parse}),Q.safeParse=(Y,W)=>oW(Q,Y,W),Q.parseAsync=async(Y,W)=>nW(Q,Y,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(Y,W)=>tW(Q,Y,W),Q.spa=Q.safeParseAsync,Q.encode=(Y,W)=>aW(Q,Y,W),Q.decode=(Y,W)=>sW(Q,Y,W),Q.encodeAsync=async(Y,W)=>eW(Q,Y,W),Q.decodeAsync=async(Y,W)=>QJ(Q,Y,W),Q.safeEncode=(Y,W)=>XJ(Q,Y,W),Q.safeDecode=(Y,W)=>YJ(Q,Y,W),Q.safeEncodeAsync=async(Y,W)=>WJ(Q,Y,W),Q.safeDecodeAsync=async(Y,W)=>JJ(Q,Y,W),Q.refine=(Y,W)=>Q.check(JK(Y,W)),Q.superRefine=(Y)=>Q.check(GK(Y)),Q.overwrite=(Y)=>Q.check(t0(Y)),Q.optional=()=>t(Q),Q.exactOptional=()=>i$(Q),Q.nullable=()=>$J(Q),Q.nullish=()=>t($J(Q)),Q.nonoptional=(Y)=>s$(Q,Y),Q.array=()=>v(Q),Q.or=(Y)=>m([Q,Y]),Q.and=(Y)=>a9(Q,Y),Q.transform=(Y)=>l6(Q,LJ(Y)),Q.default=(Y)=>o$(Q,Y),Q.prefault=(Y)=>a$(Q,Y),Q.catch=(Y)=>QK(Q,Y),Q.pipe=(Y)=>l6(Q,Y),Q.readonly=()=>WK(Q),Q.describe=(Y)=>{let W=Q.clone();return K1.add(W,{description:Y}),W},Object.defineProperty(Q,"description",{get(){return K1.get(Q)?.description},configurable:!0}),Q.meta=(...Y)=>{if(Y.length===0)return K1.get(Q);let W=Q.clone();return K1.add(W,Y[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q.apply=(Y)=>Y(Q),Q}),KJ=D("_ZodString",(Q,X)=>{c9.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(W,J,G)=>OW(Q,W,J,G);let Y=Q._zod.bag;Q.format=Y.format??null,Q.minLength=Y.minimum??null,Q.maxLength=Y.maximum??null,Q.regex=(...W)=>Q.check(q6(...W)),Q.includes=(...W)=>Q.check(E6(...W)),Q.startsWith=(...W)=>Q.check(I6(...W)),Q.endsWith=(...W)=>Q.check(b6(...W)),Q.min=(...W)=>Q.check(M1(...W)),Q.max=(...W)=>Q.check(r9(...W)),Q.length=(...W)=>Q.check(n9(...W)),Q.nonempty=(...W)=>Q.check(M1(1,...W)),Q.lowercase=(W)=>Q.check(w6(W)),Q.uppercase=(W)=>Q.check(P6(W)),Q.trim=()=>Q.check(j6()),Q.normalize=(...W)=>Q.check(T6(...W)),Q.toLowerCase=()=>Q.check(R6()),Q.toUpperCase=()=>Q.check(S6()),Q.slugify=()=>Q.check(C6())}),D$=D("ZodString",(Q,X)=>{c9.init(Q,X),KJ.init(Q,X),Q.email=(Y)=>Q.check(yY(V$,Y)),Q.url=(Y)=>Q.check(mY(Z$,Y)),Q.jwt=(Y)=>Q.check(WW(k$,Y)),Q.emoji=(Y)=>Q.check(cY(M$,Y)),Q.guid=(Y)=>Q.check(N6(GJ,Y)),Q.uuid=(Y)=>Q.check(hY(t9,Y)),Q.uuidv4=(Y)=>Q.check(uY(t9,Y)),Q.uuidv6=(Y)=>Q.check(fY(t9,Y)),Q.uuidv7=(Y)=>Q.check(lY(t9,Y)),Q.nanoid=(Y)=>Q.check(pY(O$,Y)),Q.guid=(Y)=>Q.check(N6(GJ,Y)),Q.cuid=(Y)=>Q.check(dY(N$,Y)),Q.cuid2=(Y)=>Q.check(iY(q$,Y)),Q.ulid=(Y)=>Q.check(rY(w$,Y)),Q.base64=(Y)=>Q.check(QW(R$,Y)),Q.base64url=(Y)=>Q.check(XW(S$,Y)),Q.xid=(Y)=>Q.check(nY(P$,Y)),Q.ksuid=(Y)=>Q.check(oY(E$,Y)),Q.ipv4=(Y)=>Q.check(tY(I$,Y)),Q.ipv6=(Y)=>Q.check(aY(b$,Y)),Q.cidrv4=(Y)=>Q.check(sY(T$,Y)),Q.cidrv6=(Y)=>Q.check(eY(j$,Y)),Q.e164=(Y)=>Q.check(YW(C$,Y)),Q.datetime=(Y)=>Q.check(g6(Y)),Q.date=(Y)=>Q.check(y6(Y)),Q.time=(Y)=>Q.check(h6(Y)),Q.duration=(Y)=>Q.check(u6(Y))});function U(Q){return gY(D$,Q)}var i=D("ZodStringFormat",(Q,X)=>{p.init(Q,X),KJ.init(Q,X)}),V$=D("ZodEmail",(Q,X)=>{m4.init(Q,X),i.init(Q,X)});var GJ=D("ZodGUID",(Q,X)=>{f4.init(Q,X),i.init(Q,X)});var t9=D("ZodUUID",(Q,X)=>{l4.init(Q,X),i.init(Q,X)});var Z$=D("ZodURL",(Q,X)=>{c4.init(Q,X),i.init(Q,X)});var M$=D("ZodEmoji",(Q,X)=>{p4.init(Q,X),i.init(Q,X)});var O$=D("ZodNanoID",(Q,X)=>{d4.init(Q,X),i.init(Q,X)});var N$=D("ZodCUID",(Q,X)=>{i4.init(Q,X),i.init(Q,X)});var q$=D("ZodCUID2",(Q,X)=>{r4.init(Q,X),i.init(Q,X)});var w$=D("ZodULID",(Q,X)=>{n4.init(Q,X),i.init(Q,X)});var P$=D("ZodXID",(Q,X)=>{o4.init(Q,X),i.init(Q,X)});var E$=D("ZodKSUID",(Q,X)=>{t4.init(Q,X),i.init(Q,X)});var I$=D("ZodIPv4",(Q,X)=>{XY.init(Q,X),i.init(Q,X)});var b$=D("ZodIPv6",(Q,X)=>{YY.init(Q,X),i.init(Q,X)});var T$=D("ZodCIDRv4",(Q,X)=>{WY.init(Q,X),i.init(Q,X)});var j$=D("ZodCIDRv6",(Q,X)=>{JY.init(Q,X),i.init(Q,X)});var R$=D("ZodBase64",(Q,X)=>{HY.init(Q,X),i.init(Q,X)});var S$=D("ZodBase64URL",(Q,X)=>{$Y.init(Q,X),i.init(Q,X)});var C$=D("ZodE164",(Q,X)=>{KY.init(Q,X),i.init(Q,X)});var k$=D("ZodJWT",(Q,X)=>{zY.init(Q,X),i.init(Q,X)});var zJ=D("ZodNumber",(Q,X)=>{V6.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(W,J,G)=>NW(Q,W,J,G),Q.gt=(W,J)=>Q.check(d9(W,J)),Q.gte=(W,J)=>Q.check(i1(W,J)),Q.min=(W,J)=>Q.check(i1(W,J)),Q.lt=(W,J)=>Q.check(p9(W,J)),Q.lte=(W,J)=>Q.check(d1(W,J)),Q.max=(W,J)=>Q.check(d1(W,J)),Q.int=(W)=>Q.check(HJ(W)),Q.safe=(W)=>Q.check(HJ(W)),Q.positive=(W)=>Q.check(d9(0,W)),Q.nonnegative=(W)=>Q.check(i1(0,W)),Q.negative=(W)=>Q.check(p9(0,W)),Q.nonpositive=(W)=>Q.check(d1(0,W)),Q.multipleOf=(W,J)=>Q.check(i9(W,J)),Q.step=(W,J)=>Q.check(i9(W,J)),Q.finite=()=>Q;let Y=Q._zod.bag;Q.minValue=Math.max(Y.minimum??Number.NEGATIVE_INFINITY,Y.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(Y.maximum??Number.POSITIVE_INFINITY,Y.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(Y.format??"").includes("int")||Number.isSafeInteger(Y.multipleOf??0.5),Q.isFinite=!0,Q.format=Y.format??null});function f(Q){return KW(zJ,Q)}var v$=D("ZodNumberFormat",(Q,X)=>{BY.init(Q,X),zJ.init(Q,X)});function HJ(Q){return zW(v$,Q)}var _$=D("ZodBoolean",(Q,X)=>{AY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>qW(Q,Y,W,J)});function e(Q){return BW(_$,Q)}var x$=D("ZodNull",(Q,X)=>{LY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>wW(Q,Y,W,J)});function m6(Q){return AW(x$,Q)}var g$=D("ZodUnknown",(Q,X)=>{FY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>EW(Q,Y,W,J)});function r(){return LW(g$)}var y$=D("ZodNever",(Q,X)=>{UY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>PW(Q,Y,W,J)});function h$(Q){return FW(y$,Q)}var u$=D("ZodArray",(Q,X)=>{DY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>RW(Q,Y,W,J),Q.element=X.element,Q.min=(Y,W)=>Q.check(M1(Y,W)),Q.nonempty=(Y)=>Q.check(M1(1,Y)),Q.max=(Y,W)=>Q.check(r9(Y,W)),Q.length=(Y,W)=>Q.check(n9(Y,W)),Q.unwrap=()=>Q.element});function v(Q,X){return UW(u$,Q,X)}var BJ=D("ZodObject",(Q,X)=>{MY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>SW(Q,Y,W,J),y.defineLazy(Q,"shape",()=>{return X.shape}),Q.keyof=()=>L0(Object.keys(Q._zod.def.shape)),Q.catchall=(Y)=>Q.clone({...Q._zod.def,catchall:Y}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:r()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:r()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:h$()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(Y)=>{return y.extend(Q,Y)},Q.safeExtend=(Y)=>{return y.safeExtend(Q,Y)},Q.merge=(Y)=>y.merge(Q,Y),Q.pick=(Y)=>y.pick(Q,Y),Q.omit=(Y)=>y.omit(Q,Y),Q.partial=(...Y)=>y.partial(FJ,Q,Y[0]),Q.required=(...Y)=>y.required(UJ,Q,Y[0])});function q(Q,X){let Y={type:"object",shape:Q??{},...y.normalizeParams(X)};return new BJ(Y)}function z0(Q,X){return new BJ({type:"object",shape:Q,catchall:r(),...y.normalizeParams(X)})}var AJ=D("ZodUnion",(Q,X)=>{Z6.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>CW(Q,Y,W,J),Q.options=X.options});function m(Q,X){return new AJ({type:"union",options:Q,...y.normalizeParams(X)})}var f$=D("ZodDiscriminatedUnion",(Q,X)=>{AJ.init(Q,X),OY.init(Q,X)});function c6(Q,X,Y){return new f$({type:"union",options:X,discriminator:Q,...y.normalizeParams(Y)})}var l$=D("ZodIntersection",(Q,X)=>{NY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>kW(Q,Y,W,J)});function a9(Q,X){return new l$({type:"intersection",left:Q,right:X})}var m$=D("ZodRecord",(Q,X)=>{qY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>vW(Q,Y,W,J),Q.keyType=X.keyType,Q.valueType=X.valueType});function o(Q,X,Y){return new m$({type:"record",keyType:Q,valueType:X,...y.normalizeParams(Y)})}var f6=D("ZodEnum",(Q,X)=>{wY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(W,J,G)=>IW(Q,W,J,G),Q.enum=X.entries,Q.options=Object.values(X.entries);let Y=new Set(Object.keys(X.entries));Q.extract=(W,J)=>{let G={};for(let H of W)if(Y.has(H))G[H]=X.entries[H];else throw Error(`Key ${H} not found in enum`);return new f6({...X,checks:[],...y.normalizeParams(J),entries:G})},Q.exclude=(W,J)=>{let G={...X.entries};for(let H of W)if(Y.has(H))delete G[H];else throw Error(`Key ${H} not found in enum`);return new f6({...X,checks:[],...y.normalizeParams(J),entries:G})}});function L0(Q,X){let Y=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new f6({type:"enum",entries:Y,...y.normalizeParams(X)})}var c$=D("ZodLiteral",(Q,X)=>{PY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>bW(Q,Y,W,J),Q.values=new Set(X.values),Object.defineProperty(Q,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function w(Q,X){return new c$({type:"literal",values:Array.isArray(Q)?Q:[Q],...y.normalizeParams(X)})}var p$=D("ZodTransform",(Q,X)=>{EY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>jW(Q,Y,W,J),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")throw new x1(Q.constructor.name);Y.addIssue=(G)=>{if(typeof G==="string")Y.issues.push(y.issue(G,Y.value,X));else{let H=G;if(H.fatal)H.continue=!1;H.code??(H.code="custom"),H.input??(H.input=Y.value),H.inst??(H.inst=Q),Y.issues.push(y.issue(H))}};let J=X.transform(Y.value,Y);if(J instanceof Promise)return J.then((G)=>{return Y.value=G,Y});return Y.value=J,Y}});function LJ(Q){return new p$({type:"transform",transform:Q})}var FJ=D("ZodOptional",(Q,X)=>{M6.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>x6(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function t(Q){return new FJ({type:"optional",innerType:Q})}var d$=D("ZodExactOptional",(Q,X)=>{IY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>x6(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function i$(Q){return new d$({type:"optional",innerType:Q})}var r$=D("ZodNullable",(Q,X)=>{bY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>_W(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function $J(Q){return new r$({type:"nullable",innerType:Q})}var n$=D("ZodDefault",(Q,X)=>{TY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>gW(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function o$(Q,X){return new n$({type:"default",innerType:Q,get defaultValue(){return typeof X==="function"?X():y.shallowClone(X)}})}var t$=D("ZodPrefault",(Q,X)=>{jY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>yW(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function a$(Q,X){return new t$({type:"prefault",innerType:Q,get defaultValue(){return typeof X==="function"?X():y.shallowClone(X)}})}var UJ=D("ZodNonOptional",(Q,X)=>{RY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>xW(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function s$(Q,X){return new UJ({type:"nonoptional",innerType:Q,...y.normalizeParams(X)})}var e$=D("ZodCatch",(Q,X)=>{SY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>hW(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function QK(Q,X){return new e$({type:"catch",innerType:Q,catchValue:typeof X==="function"?X:()=>X})}var XK=D("ZodPipe",(Q,X)=>{CY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>uW(Q,Y,W,J),Q.in=X.in,Q.out=X.out});function l6(Q,X){return new XK({type:"pipe",in:Q,out:X})}var YK=D("ZodReadonly",(Q,X)=>{kY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>fW(Q,Y,W,J),Q.unwrap=()=>Q._zod.def.innerType});function WK(Q){return new YK({type:"readonly",innerType:Q})}var DJ=D("ZodCustom",(Q,X)=>{vY.init(Q,X),n.init(Q,X),Q._zod.processJSONSchema=(Y,W,J)=>TW(Q,Y,W,J)});function VJ(Q,X){return DW(DJ,Q??(()=>!0),X)}function JK(Q,X={}){return VW(DJ,Q,X)}function GK(Q){return ZW(Q)}function p6(Q,X){return l6(LJ(Q),X)}O0(O6());var d6="2025-11-25";var ZJ=[d6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],s0="io.modelcontextprotocol/related-task",e9="2.0",X0=VJ((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),MJ=m([U(),f().int()]),OJ=U(),RN=z0({ttl:m([f(),m6()]).optional(),pollInterval:f().optional()}),HK=q({ttl:f().optional()}),$K=q({taskId:U()}),i6=z0({progressToken:MJ.optional(),[s0]:$K.optional()}),M0=q({_meta:i6.optional()}),t1=M0.extend({task:HK.optional()}),NJ=(Q)=>t1.safeParse(Q).success,Y0=q({method:U(),params:M0.loose().optional()}),N0=q({_meta:i6.optional()}),q0=q({method:U(),params:N0.loose().optional()}),W0=z0({_meta:i6.optional()}),QQ=m([U(),f().int()]),qJ=q({jsonrpc:w(e9),id:QQ,...Y0.shape}).strict(),r6=(Q)=>qJ.safeParse(Q).success,wJ=q({jsonrpc:w(e9),...q0.shape}).strict(),PJ=(Q)=>wJ.safeParse(Q).success,n6=q({jsonrpc:w(e9),id:QQ,result:W0}).strict(),a1=(Q)=>n6.safeParse(Q).success;var _;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(_||(_={}));var o6=q({jsonrpc:w(e9),id:QQ.optional(),error:q({code:f().int(),message:U(),data:r().optional()})}).strict();var EJ=(Q)=>o6.safeParse(Q).success;var IJ=m([qJ,wJ,n6,o6]),SN=m([n6,o6]),XQ=W0.strict(),KK=N0.extend({requestId:QQ.optional(),reason:U().optional()}),YQ=q0.extend({method:w("notifications/cancelled"),params:KK}),zK=q({src:U(),mimeType:U().optional(),sizes:v(U()).optional(),theme:L0(["light","dark"]).optional()}),s1=q({icons:v(zK).optional()}),N1=q({name:U(),title:U().optional()}),bJ=N1.extend({...N1.shape,...s1.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),BK=a9(q({applyDefaults:e().optional()}),o(U(),r())),AK=p6((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},a9(q({form:BK.optional(),url:X0.optional()}),o(U(),r()).optional())),LK=z0({list:X0.optional(),cancel:X0.optional(),requests:z0({sampling:z0({createMessage:X0.optional()}).optional(),elicitation:z0({create:X0.optional()}).optional()}).optional()}),FK=z0({list:X0.optional(),cancel:X0.optional(),requests:z0({tools:z0({call:X0.optional()}).optional()}).optional()}),UK=q({experimental:o(U(),X0).optional(),sampling:q({context:X0.optional(),tools:X0.optional()}).optional(),elicitation:AK.optional(),roots:q({listChanged:e().optional()}).optional(),tasks:LK.optional()}),DK=M0.extend({protocolVersion:U(),capabilities:UK,clientInfo:bJ}),t6=Y0.extend({method:w("initialize"),params:DK});var VK=q({experimental:o(U(),X0).optional(),logging:X0.optional(),completions:X0.optional(),prompts:q({listChanged:e().optional()}).optional(),resources:q({subscribe:e().optional(),listChanged:e().optional()}).optional(),tools:q({listChanged:e().optional()}).optional(),tasks:FK.optional()}),ZK=W0.extend({protocolVersion:U(),capabilities:VK,serverInfo:bJ,instructions:U().optional()}),a6=q0.extend({method:w("notifications/initialized"),params:N0.optional()});var WQ=Y0.extend({method:w("ping"),params:M0.optional()}),MK=q({progress:f(),total:t(f()),message:t(U())}),OK=q({...N0.shape,...MK.shape,progressToken:MJ}),JQ=q0.extend({method:w("notifications/progress"),params:OK}),NK=M0.extend({cursor:OJ.optional()}),e1=Y0.extend({params:NK.optional()}),Q9=W0.extend({nextCursor:OJ.optional()}),qK=L0(["working","input_required","completed","failed","cancelled"]),X9=q({taskId:U(),status:qK,ttl:m([f(),m6()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:t(f()),statusMessage:t(U())}),q1=W0.extend({task:X9}),wK=N0.merge(X9),Y9=q0.extend({method:w("notifications/tasks/status"),params:wK}),GQ=Y0.extend({method:w("tasks/get"),params:M0.extend({taskId:U()})}),HQ=W0.merge(X9),$Q=Y0.extend({method:w("tasks/result"),params:M0.extend({taskId:U()})}),CN=W0.loose(),KQ=e1.extend({method:w("tasks/list")}),zQ=Q9.extend({tasks:v(X9)}),BQ=Y0.extend({method:w("tasks/cancel"),params:M0.extend({taskId:U()})}),TJ=W0.merge(X9),jJ=q({uri:U(),mimeType:t(U()),_meta:o(U(),r()).optional()}),RJ=jJ.extend({text:U()}),s6=U().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),SJ=jJ.extend({blob:s6}),W9=L0(["user","assistant"]),w1=q({audience:v(W9).optional(),priority:f().min(0).max(1).optional(),lastModified:o1.datetime({offset:!0}).optional()}),CJ=q({...N1.shape,...s1.shape,uri:U(),description:t(U()),mimeType:t(U()),annotations:w1.optional(),_meta:t(z0({}))}),PK=q({...N1.shape,...s1.shape,uriTemplate:U(),description:t(U()),mimeType:t(U()),annotations:w1.optional(),_meta:t(z0({}))}),EK=e1.extend({method:w("resources/list")}),IK=Q9.extend({resources:v(CJ)}),bK=e1.extend({method:w("resources/templates/list")}),TK=Q9.extend({resourceTemplates:v(PK)}),e6=M0.extend({uri:U()}),jK=e6,RK=Y0.extend({method:w("resources/read"),params:jK}),SK=W0.extend({contents:v(m([RJ,SJ]))}),CK=q0.extend({method:w("notifications/resources/list_changed"),params:N0.optional()}),kK=e6,vK=Y0.extend({method:w("resources/subscribe"),params:kK}),_K=e6,xK=Y0.extend({method:w("resources/unsubscribe"),params:_K}),gK=N0.extend({uri:U()}),yK=q0.extend({method:w("notifications/resources/updated"),params:gK}),hK=q({name:U(),description:t(U()),required:t(e())}),uK=q({...N1.shape,...s1.shape,description:t(U()),arguments:t(v(hK)),_meta:t(z0({}))}),fK=e1.extend({method:w("prompts/list")}),lK=Q9.extend({prompts:v(uK)}),mK=M0.extend({name:U(),arguments:o(U(),U()).optional()}),cK=Y0.extend({method:w("prompts/get"),params:mK}),Q8=q({type:w("text"),text:U(),annotations:w1.optional(),_meta:o(U(),r()).optional()}),X8=q({type:w("image"),data:s6,mimeType:U(),annotations:w1.optional(),_meta:o(U(),r()).optional()}),Y8=q({type:w("audio"),data:s6,mimeType:U(),annotations:w1.optional(),_meta:o(U(),r()).optional()}),pK=q({type:w("tool_use"),name:U(),id:U(),input:o(U(),r()),_meta:o(U(),r()).optional()}),dK=q({type:w("resource"),resource:m([RJ,SJ]),annotations:w1.optional(),_meta:o(U(),r()).optional()}),iK=CJ.extend({type:w("resource_link")}),W8=m([Q8,X8,Y8,iK,dK]),rK=q({role:W9,content:W8}),nK=W0.extend({description:U().optional(),messages:v(rK)}),oK=q0.extend({method:w("notifications/prompts/list_changed"),params:N0.optional()}),tK=q({title:U().optional(),readOnlyHint:e().optional(),destructiveHint:e().optional(),idempotentHint:e().optional(),openWorldHint:e().optional()}),aK=q({taskSupport:L0(["required","optional","forbidden"]).optional()}),kJ=q({...N1.shape,...s1.shape,description:U().optional(),inputSchema:q({type:w("object"),properties:o(U(),X0).optional(),required:v(U()).optional()}).catchall(r()),outputSchema:q({type:w("object"),properties:o(U(),X0).optional(),required:v(U()).optional()}).catchall(r()).optional(),annotations:tK.optional(),execution:aK.optional(),_meta:o(U(),r()).optional()}),J8=e1.extend({method:w("tools/list")}),sK=Q9.extend({tools:v(kJ)}),AQ=W0.extend({content:v(W8).default([]),structuredContent:o(U(),r()).optional(),isError:e().optional()}),kN=AQ.or(W0.extend({toolResult:r()})),eK=t1.extend({name:U(),arguments:o(U(),r()).optional()}),J9=Y0.extend({method:w("tools/call"),params:eK}),Qz=q0.extend({method:w("notifications/tools/list_changed"),params:N0.optional()}),vN=q({autoRefresh:e().default(!0),debounceMs:f().int().nonnegative().default(300)}),G9=L0(["debug","info","notice","warning","error","critical","alert","emergency"]),Xz=M0.extend({level:G9}),G8=Y0.extend({method:w("logging/setLevel"),params:Xz}),Yz=N0.extend({level:G9,logger:U().optional(),data:r()}),Wz=q0.extend({method:w("notifications/message"),params:Yz}),Jz=q({name:U().optional()}),Gz=q({hints:v(Jz).optional(),costPriority:f().min(0).max(1).optional(),speedPriority:f().min(0).max(1).optional(),intelligencePriority:f().min(0).max(1).optional()}),Hz=q({mode:L0(["auto","required","none"]).optional()}),$z=q({type:w("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:v(W8).default([]),structuredContent:q({}).loose().optional(),isError:e().optional(),_meta:o(U(),r()).optional()}),Kz=c6("type",[Q8,X8,Y8]),s9=c6("type",[Q8,X8,Y8,pK,$z]),zz=q({role:W9,content:m([s9,v(s9)]),_meta:o(U(),r()).optional()}),Bz=t1.extend({messages:v(zz),modelPreferences:Gz.optional(),systemPrompt:U().optional(),includeContext:L0(["none","thisServer","allServers"]).optional(),temperature:f().optional(),maxTokens:f().int(),stopSequences:v(U()).optional(),metadata:X0.optional(),tools:v(kJ).optional(),toolChoice:Hz.optional()}),Az=Y0.extend({method:w("sampling/createMessage"),params:Bz}),H8=W0.extend({model:U(),stopReason:t(L0(["endTurn","stopSequence","maxTokens"]).or(U())),role:W9,content:Kz}),$8=W0.extend({model:U(),stopReason:t(L0(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:W9,content:m([s9,v(s9)])}),Lz=q({type:w("boolean"),title:U().optional(),description:U().optional(),default:e().optional()}),Fz=q({type:w("string"),title:U().optional(),description:U().optional(),minLength:f().optional(),maxLength:f().optional(),format:L0(["email","uri","date","date-time"]).optional(),default:U().optional()}),Uz=q({type:L0(["number","integer"]),title:U().optional(),description:U().optional(),minimum:f().optional(),maximum:f().optional(),default:f().optional()}),Dz=q({type:w("string"),title:U().optional(),description:U().optional(),enum:v(U()),default:U().optional()}),Vz=q({type:w("string"),title:U().optional(),description:U().optional(),oneOf:v(q({const:U(),title:U()})),default:U().optional()}),Zz=q({type:w("string"),title:U().optional(),description:U().optional(),enum:v(U()),enumNames:v(U()).optional(),default:U().optional()}),Mz=m([Dz,Vz]),Oz=q({type:w("array"),title:U().optional(),description:U().optional(),minItems:f().optional(),maxItems:f().optional(),items:q({type:w("string"),enum:v(U())}),default:v(U()).optional()}),Nz=q({type:w("array"),title:U().optional(),description:U().optional(),minItems:f().optional(),maxItems:f().optional(),items:q({anyOf:v(q({const:U(),title:U()}))}),default:v(U()).optional()}),qz=m([Oz,Nz]),wz=m([Zz,Mz,qz]),Pz=m([wz,Lz,Fz,Uz]),Ez=t1.extend({mode:w("form").optional(),message:U(),requestedSchema:q({type:w("object"),properties:o(U(),Pz),required:v(U()).optional()})}),Iz=t1.extend({mode:w("url"),message:U(),elicitationId:U(),url:U().url()}),bz=m([Ez,Iz]),Tz=Y0.extend({method:w("elicitation/create"),params:bz}),jz=N0.extend({elicitationId:U()}),Rz=q0.extend({method:w("notifications/elicitation/complete"),params:jz}),LQ=W0.extend({action:L0(["accept","decline","cancel"]),content:p6((Q)=>Q===null?void 0:Q,o(U(),m([U(),f(),e(),v(U())])).optional())}),Sz=q({type:w("ref/resource"),uri:U()});var Cz=q({type:w("ref/prompt"),name:U()}),kz=M0.extend({ref:m([Cz,Sz]),argument:q({name:U(),value:U()}),context:q({arguments:o(U(),U()).optional()}).optional()}),vz=Y0.extend({method:w("completion/complete"),params:kz});var _z=W0.extend({completion:z0({values:v(U()).max(100),total:t(f().int()),hasMore:t(e())})}),xz=q({uri:U().startsWith("file://"),name:U().optional(),_meta:o(U(),r()).optional()}),gz=Y0.extend({method:w("roots/list"),params:M0.optional()}),K8=W0.extend({roots:v(xz)}),yz=q0.extend({method:w("notifications/roots/list_changed"),params:N0.optional()}),_N=m([WQ,t6,vz,G8,cK,fK,EK,bK,RK,vK,xK,J9,J8,GQ,$Q,KQ,BQ]),xN=m([YQ,JQ,a6,yz,Y9]),gN=m([XQ,H8,$8,LQ,K8,HQ,zQ,q1]),yN=m([WQ,Az,Tz,gz,GQ,$Q,KQ,BQ]),hN=m([YQ,JQ,Wz,yK,CK,Qz,oK,Y9,Rz]),uN=m([XQ,ZK,_z,nK,lK,IK,TK,SK,AQ,sK,HQ,zQ,q1]);class C extends Error{constructor(Q,X,Y){super(`MCP error ${Q}: ${X}`);this.code=Q,this.data=Y,this.name="McpError"}static fromError(Q,X,Y){if(Q===_.UrlElicitationRequired&&Y){let W=Y;if(W.elicitations)return new vJ(W.elicitations,X)}return new C(Q,X,Y)}}class vJ extends C{constructor(Q,X=`URL elicitation${Q.length>1?"s":""} required`){super(_.UrlElicitationRequired,X,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function e0(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var hz=Symbol("Let zodToJsonSchema decide on which parser to use");var Mq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z8(Q){let Y=o9(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=lW(Y);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function B8(Q,X){let Y=a0(Q,X);if(!Y.success)throw Y.error;return Y.data}var pz=60000;class A8{constructor(Q){if(this._options=Q,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._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(YQ,(X)=>{this._oncancel(X)}),this.setNotificationHandler(JQ,(X)=>{this._onprogress(X)}),this.setRequestHandler(WQ,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(GQ,async(X,Y)=>{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(_.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler($Q,async(X,Y)=>{let W=async()=>{let J=X.params.taskId;if(this._taskMessageQueue){let H;while(H=await this._taskMessageQueue.dequeue(J,Y.sessionId)){if(H.type==="response"||H.type==="error"){let $=H.message,K=$.id,z=this._requestResolvers.get(K);if(z)if(this._requestResolvers.delete(K),H.type==="response")z($);else{let B=$,A=new C(B.error.code,B.error.message,B.error.data);z(A)}else{let B=H.type==="response"?"Response":"Error";this._onerror(Error(`${B} handler missing for request ${K}`))}continue}await this._transport?.send(H.message,{relatedRequestId:Y.requestId})}}let G=await this._taskStore.getTask(J,Y.sessionId);if(!G)throw new C(_.InvalidParams,`Task not found: ${J}`);if(!e0(G.status))return await this._waitForTaskUpdate(J,Y.signal),await W();if(e0(G.status)){let H=await this._taskStore.getTaskResult(J,Y.sessionId);return this._clearTaskQueue(J),{...H,_meta:{...H._meta,[s0]:{taskId:J}}}}return await W()};return await W()}),this.setRequestHandler(KQ,async(X,Y)=>{try{let{tasks:W,nextCursor:J}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:W,nextCursor:J,_meta:{}}}catch(W){throw new C(_.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(BQ,async(X,Y)=>{try{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(_.InvalidParams,`Task not found: ${X.params.taskId}`);if(e0(W.status))throw new C(_.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let J=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!J)throw new C(_.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...J}}catch(W){if(W instanceof C)throw W;throw new C(_.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,W,J=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:J,onTimeout:W})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),C.fromError(_.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=(J)=>{Y?.(J),this._onerror(J)};let W=this._transport?.onmessage;this._transport.onmessage=(J,G)=>{if(W?.(J,G),a1(J)||EJ(J))this._onresponse(J);else if(r6(J))this._onrequest(J,G);else if(PJ(J))this._onnotification(J);else this._onerror(Error(`Unknown message type: ${JSON.stringify(J)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let X=C.fromError(_.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,J=Q.params?._meta?.[s0]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:_.MethodNotFound,message:"Method not found"}};if(J&&this._taskMessageQueue)this._enqueueTaskMessage(J,{type:"error",message:z,timestamp:Date.now()},W?.sessionId).catch((B)=>this._onerror(Error(`Failed to enqueue error response: ${B}`)));else W?.send(z).catch((B)=>this._onerror(Error(`Failed to send an error response: ${B}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(Q.id,G);let H=NJ(Q.params)?Q.params.task:void 0,$=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,K={signal:G.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{let B={relatedRequestId:Q.id};if(J)B.relatedTask={taskId:J};await this.notification(z,B)},sendRequest:async(z,B,A)=>{let F={...A,relatedRequestId:Q.id};if(J&&!F.relatedTask)F.relatedTask={taskId:J};let L=F.relatedTask?.taskId??J;if(L&&$)await $.updateTaskStatus(L,"input_required");return await this.request(z,B,F)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:J,taskStore:$,taskRequestedTtl:H?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(H)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,K)).then(async(z)=>{if(G.signal.aborted)return;let B={result:z,jsonrpc:"2.0",id:Q.id};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"response",message:B,timestamp:Date.now()},W?.sessionId);else await W?.send(B)},async(z)=>{if(G.signal.aborted)return;let B={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:_.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"error",message:B,timestamp:Date.now()},W?.sessionId);else await W?.send(B)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,W=Number(X),J=this._progressHandlers.get(W);if(!J){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let G=this._responseHandlers.get(W),H=this._timeoutInfo.get(W);if(H&&G&&H.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch($){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G($);return}J(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),a1(Q))Y(Q);else{let G=new C(Q.error.code,Q.error.message,Q.error.data);Y(G)}return}let W=this._responseHandlers.get(X);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let J=!1;if(a1(Q)&&Q.result&&typeof Q.result==="object"){let G=Q.result;if(G.task&&typeof G.task==="object"){let H=G.task;if(typeof H.taskId==="string")J=!0,this._taskProgressTokens.set(H.taskId,X)}}if(!J)this._progressHandlers.delete(X);if(a1(Q))W(Q);else{let G=C.fromError(Q.error.code,Q.error.message,Q.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:W}=Y??{};if(!W){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(G){yield{type:"error",error:G instanceof C?G:new C(_.InternalError,String(G))}}return}let J;try{let G=await this.request(Q,q1,Y);if(G.task)J=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new C(_.InternalError,"Task creation did not return a task");while(!0){let H=await this.getTask({taskId:J},Y);if(yield{type:"taskStatus",task:H},e0(H.status)){if(H.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:J},X,Y)};else if(H.status==="failed")yield{type:"error",error:new C(_.InternalError,`Task ${J} failed`)};else if(H.status==="cancelled")yield{type:"error",error:new C(_.InternalError,`Task ${J} was cancelled`)};return}if(H.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:J},X,Y)};return}let $=H.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((K)=>setTimeout(K,$)),Y?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof C?G:new C(_.InternalError,String(G))}}}request(Q,X,Y){let{relatedRequestId:W,resumptionToken:J,onresumptiontoken:G,task:H,relatedTask:$}=Y??{};return new Promise((K,z)=>{let B=(M)=>{z(M)};if(!this._transport){B(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),H)this.assertTaskCapability(Q.method)}catch(M){B(M);return}Y?.signal?.throwIfAborted();let A=this._requestMessageId++,F={...Q,jsonrpc:"2.0",id:A};if(Y?.onprogress)this._progressHandlers.set(A,Y.onprogress),F.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:A}};if(H)F.params={...F.params,task:H};if($)F.params={...F.params,_meta:{...F.params?._meta||{},[s0]:$}};let L=(M)=>{this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(M)}},{relatedRequestId:W,resumptionToken:J,onresumptiontoken:G}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let T=M instanceof C?M:new C(_.RequestTimeout,String(M));z(T)};this._responseHandlers.set(A,(M)=>{if(Y?.signal?.aborted)return;if(M instanceof Error)return z(M);try{let T=a0(X,M.result);if(!T.success)z(T.error);else K(T.data)}catch(T){z(T)}}),Y?.signal?.addEventListener("abort",()=>{L(Y?.signal?.reason)});let V=Y?.timeout??pz,Z=()=>L(C.fromError(_.RequestTimeout,"Request timed out",{timeout:V}));this._setupTimeout(A,V,Y?.maxTotalTimeout,Z,Y?.resetTimeoutOnProgress??!1);let O=$?.taskId;if(O){let M=(T)=>{let I=this._responseHandlers.get(A);if(I)I(T);else this._onerror(Error(`Response handler missing for side-channeled request ${A}`))};this._requestResolvers.set(A,M),this._enqueueTaskMessage(O,{type:"request",message:F,timestamp:Date.now()}).catch((T)=>{this._cleanupTimeout(A),z(T)})}else this._transport.send(F,{relatedRequestId:W,resumptionToken:J,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(A),z(M)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},HQ,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},zQ,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},TJ,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let H={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[s0]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:H,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let H={...Q,jsonrpc:"2.0"};if(X?.relatedTask)H={...H,params:{...H.params,_meta:{...H.params?._meta||{},[s0]:X.relatedTask}}};this._transport?.send(H,X).catch(($)=>this._onerror($))});return}let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[s0]:X.relatedTask}}};await this._transport.send(G,X)}setRequestHandler(Q,X){let Y=z8(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,(W,J)=>{let G=B8(Q,W);return Promise.resolve(X(G,J))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=z8(Q);this._notificationHandlers.set(Y,(W)=>{let J=B8(Q,W);return Promise.resolve(X(J))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,W)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let W of Y)if(W.type==="request"&&r6(W.message)){let J=W.message.id,G=this._requestResolvers.get(J);if(G)G(new C(_.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(J);else this._onerror(Error(`Resolver missing for request ${J} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)Y=W.pollInterval}catch{}return new Promise((W,J)=>{if(X.aborted){J(new C(_.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,Y);X.addEventListener("abort",()=>{clearTimeout(G),J(new C(_.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await Y.createTask(W,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(W)=>{let J=await Y.getTask(W,X);if(!J)throw new C(_.InvalidParams,"Failed to retrieve task: Task not found");return J},storeTaskResult:async(W,J,G)=>{await Y.storeTaskResult(W,J,G,X);let H=await Y.getTask(W,X);if(H){let $=Y9.parse({method:"notifications/tasks/status",params:H});if(await this.notification($),e0(H.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Y.getTaskResult(W,X)},updateTaskStatus:async(W,J,G)=>{let H=await Y.getTask(W,X);if(!H)throw new C(_.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(e0(H.status))throw new C(_.InvalidParams,`Cannot update task "${W}" from terminal status "${H.status}" to "${J}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus(W,J,G,X);let $=await Y.getTask(W,X);if($){let K=Y9.parse({method:"notifications/tasks/status",params:$});if(await this.notification(K),e0($.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Y.listTasks(W,X)}}}}function _J(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function xJ(Q,X){let Y={...Q};for(let W in X){let J=W,G=X[J];if(G===void 0)continue;let H=Y[J];if(_J(H)&&_J(G))Y[J]={...H,...G};else Y[J]=G}return Y}var L3=PX(GX(),1),F3=PX(A3(),1);function eZ(){let Q=new L3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return F3.default(Q),Q}class DX{constructor(Q){this._ajv=Q??eZ()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class VX{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function U3(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function D3(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class ZX extends A8{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(G9.options.map((Y,W)=>[Y,W])),this.isMessageIgnored=(Y,W)=>{let J=this._loggingLevels.get(W);return J?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get(J):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new DX,this.setRequestHandler(t6,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(a6,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(G8,async(Y,W)=>{let J=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=Y.params,H=G9.safeParse(G);if(H.success)this._loggingLevels.set(J,H.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new VX(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=xJ(this._capabilities,Q)}setRequestHandler(Q,X){let W=o9(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let J;if(O1(W)){let H=W;J=H._zod?.def?.value??H.value}else{let H=W;J=H._def?.value??H.value}if(typeof J!=="string")throw Error("Schema method literal must be a string");if(J==="tools/call"){let H=async($,K)=>{let z=a0(J9,$);if(!z.success){let L=z.error instanceof Error?z.error.message:String(z.error);throw new C(_.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:B}=z.data,A=await Promise.resolve(X($,K));if(B.task){let L=a0(q1,A);if(!L.success){let V=L.error instanceof Error?L.error.message:String(L.error);throw new C(_.InvalidParams,`Invalid task creation result: ${V}`)}return L.data}let F=a0(AQ,A);if(!F.success){let L=F.error instanceof Error?F.error.message:String(F.error);throw new C(_.InvalidParams,`Invalid tools/call result: ${L}`)}return F.data};return super.setRequestHandler(Q,H)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){D3(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;U3(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:ZJ.includes(X)?X:d6,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"},XQ)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],W=Array.isArray(Y.content)?Y.content:[Y.content],J=W.some((K)=>K.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=G?Array.isArray(G.content)?G.content:[G.content]:[],$=H.some((K)=>K.type==="tool_use");if(J){if(W.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!$)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if($){let K=new Set(H.filter((B)=>B.type==="tool_use").map((B)=>B.id)),z=new Set(W.filter((B)=>B.type==="tool_result").map((B)=>B.toolUseId));if(K.size!==z.size||![...K].every((B)=>z.has(B)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},$8,X);return this.request({method:"sampling/createMessage",params:Q},H8,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},LQ,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},J=await this.request({method:"elicitation/create",params:W},LQ,X);if(J.action==="accept"&&J.content&&W.requestedSchema)try{let H=this._jsonSchemaValidator.getValidator(W.requestedSchema)(J.content);if(!H.valid)throw new C(_.InvalidParams,`Elicitation response content does not match requested schema: ${H.errorMessage}`)}catch(G){if(G instanceof C)throw G;throw new C(_.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return J}}}createElicitationCompletionNotifier(Q,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},K8,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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"})}}import Z3 from"node:process";class MX{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
48
48
  `);if(Q===-1)return null;let X=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),QM(X)}clear(){this._buffer=void 0}}function QM(Q){return IJ.parse(JSON.parse(Q))}function V3(Q){return JSON.stringify(Q)+`
49
- `}class OX{constructor(Q=Z3.stdin,X=Z3.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new MX,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}async start(){if(this._started)throw 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(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(Q){return new Promise((X)=>{let Y=V3(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}var H0={DEFAULT_PORT:38451,DEFAULT_HOST:"localhost",TIMEOUT_MS:1e4,PING_INTERVAL_MS:5000,HEALTH_TTL_MS:15000,MAX_QUEUE:100,MAX_PENDING:100,MAX_BODY_BYTES:1e6};function NX(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}import{createServer as XM}from"http";class M3{server=null;pendingRequests=new Map;requestQueue=[];isRunning=!1;lastPollAt=null;lastResponseAt=null;lastRequestAt=null;async start(){if(this.isRunning)return;return new Promise((Q,X)=>{this.server=XM((Y,W)=>this.handleRequest(Y,W)),this.server.on("error",(Y)=>{if(Y.code==="EADDRINUSE")console.error(`Bridge port ${H0.DEFAULT_PORT} already in use - connecting to existing bridge`),this.isRunning=!1,Q();else X(Y)}),this.server.listen(H0.DEFAULT_PORT,H0.DEFAULT_HOST,()=>{this.isRunning=!0,console.error(`Bridge server started on http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}`),Q()})})}async stop(){if(this.server)this.server.close(),this.server=null;this.isRunning=!1;for(let[,Q]of this.pendingRequests)clearTimeout(Q.timeout),Q.reject(Error("Bridge stopped"));this.pendingRequests.clear(),this.requestQueue=[]}handleRequest(Q,X){let Y={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type","Content-Type":"application/json"};for(let[J,G]of Object.entries(Y))X.setHeader(J,G);if(Q.method==="OPTIONS"){X.writeHead(204),X.end();return}let W=new URL(Q.url||"/",`http://${Q.headers.host}`);if(W.pathname==="/poll"&&Q.method==="GET"){this.lastPollAt=Date.now();let J=[...this.requestQueue];this.requestQueue=[],X.writeHead(200),X.end(JSON.stringify({requests:J}));return}if(W.pathname==="/response"&&Q.method==="POST"){this.readJsonBody(Q,X).then((J)=>{if(!J)return;this.lastResponseAt=Date.now(),this.handleResponse(J),X.writeHead(200),X.end(JSON.stringify({success:!0}))});return}if(W.pathname==="/health"){let J=this.getHealthSummary();X.writeHead(200),X.end(JSON.stringify(J));return}if(W.pathname==="/queue"&&Q.method==="POST"){this.readJsonBody(Q,X).then(async(J)=>{if(!J)return;if(this.requestQueue.length>=H0.MAX_QUEUE){X.writeHead(429),X.end(JSON.stringify({success:!1,error:"Bridge queue is full"}));return}if(this.pendingRequests.size>=H0.MAX_PENDING){X.writeHead(429),X.end(JSON.stringify({success:!1,error:"Too many pending requests"}));return}this.lastRequestAt=Date.now();try{let{operation:G,params:H,timeout:$}=J,K={id:NX(),operation:G,params:H},z=$||H0.TIMEOUT_MS,B=await new Promise((A,F)=>{let L=setTimeout(()=>{this.pendingRequests.delete(K.id),F(Error(`Request timeout: ${G}`))},z);this.pendingRequests.set(K.id,{resolve:(V)=>A(V),reject:F,timeout:L}),this.requestQueue.push(K)});if(B.success)X.writeHead(200),X.end(JSON.stringify({success:!0,data:B.data}));else X.writeHead(200),X.end(JSON.stringify({success:!1,error:B.error}))}catch(G){X.writeHead(500),X.end(JSON.stringify({success:!1,error:G instanceof Error?G.message:"Unknown error"}))}});return}X.writeHead(404),X.end(JSON.stringify({error:"Not found"}))}handleResponse(Q){let X=this.pendingRequests.get(Q.id);if(!X){console.error(`No pending request for response: ${Q.id}`);return}clearTimeout(X.timeout),this.pendingRequests.delete(Q.id),X.resolve(Q)}async sendRequest(Q,X){if(!this.isRunning)return this.sendToExternalBridge(Q,X);let Y={id:NX(),operation:Q,params:X};return new Promise((W,J)=>{let G=setTimeout(()=>{this.pendingRequests.delete(Y.id),J(Error(`Request timeout: ${Q}`))},H0.TIMEOUT_MS);this.pendingRequests.set(Y.id,{resolve:(H)=>{if(H.success)W(H.data);else J(Error(H.error||"Unknown error"))},reject:J,timeout:G}),this.requestQueue.push(Y)})}async sendToExternalBridge(Q,X){let Y=`http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}`,W=await fetch(`${Y}/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:Q,params:X,timeout:H0.TIMEOUT_MS})});if(!W.ok)throw Error(`Bridge request failed: ${W.statusText}`);let J=await W.json();if(!J.success)throw Error(J.error||"Unknown error");return J.data}async checkHealth(){if(this.isRunning)return this.getHealthSummary().pluginConnected;try{let Q=await fetch(`http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}/health`);if(!Q.ok)return!1;let X=await Q.json();return Boolean(X.pluginConnected)}catch{return!1}}getIsRunning(){return this.isRunning}getHealthSummary(){let Q=Date.now();return{status:"ok",pluginConnected:this.lastPollAt!==null?Q-this.lastPollAt<=H0.HEALTH_TTL_MS:!1,pendingRequests:this.pendingRequests.size,queuedRequests:this.requestQueue.length,lastPollAt:this.lastPollAt,lastResponseAt:this.lastResponseAt,lastRequestAt:this.lastRequestAt}}async readJsonBody(Q,X){return new Promise((Y)=>{let W="",J=0,G=H0.MAX_BODY_BYTES;Q.on("data",(H)=>{if(J+=H.length,J>G){X.writeHead(413),X.end(JSON.stringify({error:"Payload too large"})),Q.destroy(),Y(null);return}W+=H}),Q.on("end",()=>{try{let H=JSON.parse(W);Y(H)}catch{X.writeHead(400),X.end(JSON.stringify({error:"Invalid JSON body"})),Y(null)}}),Q.on("error",()=>{X.writeHead(400),X.end(JSON.stringify({error:"Invalid request body"})),Y(null)})})}}var YM=[{name:"figma_status",description:"Check connection status to Figma plugin. Call this first to verify the plugin is running.",inputSchema:{type:"object",properties:{},required:[]}},{name:"figma_list_components",description:"List all available components in the Figma file. Use this to discover reusable components before creating instances.",inputSchema:{type:"object",properties:{filter:{type:"string",description:"Optional filter to search components by name (case-insensitive)"}},required:[]}},{name:"figma_create",description:"Create a new element in Figma. Supports frames, text, rectangles, ellipses, and semantic types like card, button, nav.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["frame","text","rect","ellipse","line","card","button","form","nav","input"],description:"Element type to create"},name:{type:"string",description:"Name for the element"},width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},x:{type:"number",description:"X position"},y:{type:"number",description:"Y position"},parent:{type:"string",description:"Parent element (ID, 'selection', or 'name:ElementName')"},fill:{type:"string",description:"Fill color (hex, e.g., '#FF0000')"},stroke:{type:"string",description:"Stroke color (hex)"},strokeWidth:{type:"number",description:"Stroke width"},cornerRadius:{type:"number",description:"Corner radius"},content:{type:"string",description:"Text content (for text elements)"},fontSize:{type:"number",description:"Font size (for text elements)"},fontWeight:{type:"number",description:"Font weight (for text elements)"},textColor:{type:"string",description:"Text color (hex). For text elements, preferred over 'fill' for clarity."},layout:{type:"object",description:"Auto-layout configuration",properties:{direction:{type:"string",enum:["row","column"]},gap:{type:"number"},padding:{type:"number"},alignItems:{type:"string",enum:["start","center","end","baseline"]},justifyContent:{type:"string",enum:["start","center","end","space-between"]}}},children:{type:"array",description:"Nested child elements to create",items:{type:"object"}}},required:["type"]}},{name:"figma_modify",description:"Modify existing elements in Figma. Target by ID, name, or selection.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to modify (ID, 'selection', or 'name:ElementName')"},name:{type:"string",description:"New name"},width:{type:"number",description:"New width"},height:{type:"number",description:"New height"},x:{type:"number",description:"New X position"},y:{type:"number",description:"New Y position"},fill:{type:"string",description:"New fill color (hex)"},stroke:{type:"string",description:"New stroke color (hex)"},cornerRadius:{type:"number",description:"New corner radius"},opacity:{type:"number",description:"Opacity (0-1)"},visible:{type:"boolean",description:"Visibility"},content:{type:"string",description:"New text content"},fontSize:{type:"number",description:"New font size"},layout:{type:"object",description:"Layout updates"}},required:["target"]}},{name:"figma_delete",description:"Delete elements from Figma.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to delete (ID, 'selection', or 'name:ElementName')"}},required:["target"]}},{name:"figma_append",description:"Move element(s) into a container frame.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to move (ID, 'selection', or 'name:ElementName')"},parent:{type:"string",description:"Container to move into (ID, 'selection', or 'name:ContainerName')"}},required:["target","parent"]}},{name:"figma_instantiate",description:"Create an instance of a component. Use list_components first to discover available components.",inputSchema:{type:"object",properties:{component:{type:"string",description:"Component ID or 'name:ComponentName'"},x:{type:"number",description:"X position"},y:{type:"number",description:"Y position"},parent:{type:"string",description:"Parent element to add instance to"}},required:["component"]}},{name:"figma_selection",description:"Get information about the current selection in Figma.",inputSchema:{type:"object",properties:{},required:[]}},{name:"figma_query",description:"Get detailed information about a specific element.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to query (ID, 'selection', or 'name:ElementName')"}},required:["target"]}},{name:"figma_to_component",description:"Convert an element to a reusable component.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to convert (ID, 'selection', or 'name:ElementName')"},name:{type:"string",description:"Component name (e.g., 'Button/Primary')"}},required:["target"]}},{name:"figma_create_variants",description:"Create component variants with different property values.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Component to create variants from"},property:{type:"string",description:"Variant property name (e.g., 'state', 'size')"},values:{type:"array",items:{type:"string"},description:"Variant values (e.g., ['default', 'hover', 'pressed'])"}},required:["target","property","values"]}},{name:"figma_ensure_accessibility",description:"Check and optionally fix accessibility issues.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to check (ID, 'selection', 'page', or 'name:ElementName')"},level:{type:"string",enum:["AA","AAA"],description:"WCAG conformance level"},autoFix:{type:"boolean",description:"Automatically fix issues"}},required:["target","level"]}},{name:"figma_audit_accessibility",description:"Audit accessibility issues without fixing them.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to audit (ID, 'selection', 'page', or 'name:ElementName')"},output:{type:"string",enum:["json","text"],description:"Output format (default: json)"}},required:["target"]}},{name:"figma_bind_token",description:"Bind a design token to a node property.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to bind token to (ID, 'selection', or 'name:ElementName')"},property:{type:"string",enum:["fill","stroke","fontSize","fontFamily","fontWeight","cornerRadius","gap","padding"],description:"Property to bind"},token:{type:"string",description:"Token name or ID"}},required:["target","property","token"]}},{name:"figma_create_token",description:"Create a new design token.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Token collection name"},name:{type:"string",description:"Token name"},type:{type:"string",enum:["COLOR","NUMBER","STRING","BOOLEAN"],description:"Token type"},value:{description:"Token value",anyOf:[{type:"string"},{type:"number"},{type:"boolean"}]}},required:["collection","name","type","value"]}},{name:"figma_sync_tokens",description:"Import or export design tokens to/from JSON files.",inputSchema:{type:"object",properties:{from:{type:"string",description:"Import from JSON file path"},to:{type:"string",description:"Export to JSON file path"}},required:[]}},{name:"figma_export",description:"Export elements as images (PNG, SVG, PDF). Use after finishing a request to review a PNG.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to export"},format:{type:"string",enum:["png","svg","pdf","jpg"],description:"Export format"},scale:{type:"number",description:"Scale factor (default: 1)"}},required:["target","format"]}}],WM={figma_status:"status",figma_list_components:"list-components",figma_create:"create",figma_modify:"modify",figma_delete:"delete",figma_append:"append",figma_instantiate:"instantiate",figma_selection:"selection",figma_query:"query",figma_to_component:"to-component",figma_create_variants:"create-variants",figma_ensure_accessibility:"ensure-accessibility",figma_audit_accessibility:"audit-a11y",figma_bind_token:"bind-token",figma_create_token:"create-token",figma_sync_tokens:"sync-tokens",figma_export:"export"};async function JM(){let Q=new M3;await Q.start();let X=new ZX({name:"figma-pilot",version:"0.1.0"},{capabilities:{tools:{}}});X.setRequestHandler(J8,async()=>({tools:YM})),X.setRequestHandler(J9,async(W)=>{let{name:J,arguments:G}=W.params;if(!await Q.checkHealth())return{content:[{type:"text",text:JSON.stringify({error:"Figma plugin not connected. Please open Figma Desktop and run the figma-pilot plugin."})}],isError:!0};let $=WM[J];if(!$)return{content:[{type:"text",text:JSON.stringify({error:`Unknown tool: ${J}`})}],isError:!0};try{let K=G||{},z=await Q.sendRequest($,K);return{content:[{type:"text",text:JSON.stringify(z,null,2)}]}}catch(K){return{content:[{type:"text",text:JSON.stringify({error:K instanceof Error?K.message:"Unknown error"})}],isError:!0}}}),process.on("SIGINT",async()=>{await Q.stop(),process.exit(0)}),process.on("SIGTERM",async()=>{await Q.stop(),process.exit(0)});let Y=new OX;await X.connect(Y),console.error("figma-pilot MCP server running (bridge included)")}JM().catch(console.error);
49
+ `}class OX{constructor(Q=Z3.stdin,X=Z3.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new MX,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}async start(){if(this._started)throw 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(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(Q){return new Promise((X)=>{let Y=V3(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}var H0={DEFAULT_PORT:38451,DEFAULT_HOST:"localhost",TIMEOUT_MS:1e4,PING_INTERVAL_MS:5000,HEALTH_TTL_MS:15000,MAX_QUEUE:100,MAX_PENDING:100,MAX_BODY_BYTES:1e6};function NX(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}import{createServer as XM}from"http";class M3{server=null;pendingRequests=new Map;requestQueue=[];isRunning=!1;lastPollAt=null;lastResponseAt=null;lastRequestAt=null;async start(){if(this.isRunning)return;return new Promise((Q,X)=>{this.server=XM((Y,W)=>this.handleRequest(Y,W)),this.server.on("error",(Y)=>{if(Y.code==="EADDRINUSE")console.error(`Bridge port ${H0.DEFAULT_PORT} already in use - connecting to existing bridge`),this.isRunning=!1,Q();else X(Y)}),this.server.listen(H0.DEFAULT_PORT,H0.DEFAULT_HOST,()=>{this.isRunning=!0,console.error(`Bridge server started on http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}`),Q()})})}async stop(){if(this.server)this.server.close(),this.server=null;this.isRunning=!1;for(let[,Q]of this.pendingRequests)clearTimeout(Q.timeout),Q.reject(Error("Bridge stopped"));this.pendingRequests.clear(),this.requestQueue=[]}handleRequest(Q,X){let Y={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type","Content-Type":"application/json"};for(let[J,G]of Object.entries(Y))X.setHeader(J,G);if(Q.method==="OPTIONS"){X.writeHead(204),X.end();return}let W=new URL(Q.url||"/",`http://${Q.headers.host}`);if(W.pathname==="/poll"&&Q.method==="GET"){this.lastPollAt=Date.now();let J=[...this.requestQueue];this.requestQueue=[],X.writeHead(200),X.end(JSON.stringify({requests:J}));return}if(W.pathname==="/response"&&Q.method==="POST"){this.readJsonBody(Q,X).then((J)=>{if(!J)return;this.lastResponseAt=Date.now(),this.handleResponse(J),X.writeHead(200),X.end(JSON.stringify({success:!0}))});return}if(W.pathname==="/health"){let J=this.getHealthSummary();X.writeHead(200),X.end(JSON.stringify(J));return}if(W.pathname==="/queue"&&Q.method==="POST"){this.readJsonBody(Q,X).then(async(J)=>{if(!J)return;if(this.requestQueue.length>=H0.MAX_QUEUE){X.writeHead(429),X.end(JSON.stringify({success:!1,error:"Bridge queue is full"}));return}if(this.pendingRequests.size>=H0.MAX_PENDING){X.writeHead(429),X.end(JSON.stringify({success:!1,error:"Too many pending requests"}));return}this.lastRequestAt=Date.now();try{let{operation:G,params:H,timeout:$}=J,K={id:NX(),operation:G,params:H},z=$||H0.TIMEOUT_MS,B=await new Promise((A,F)=>{let L=setTimeout(()=>{this.pendingRequests.delete(K.id),F(Error(`Request timeout: ${G}`))},z);this.pendingRequests.set(K.id,{resolve:(V)=>A(V),reject:F,timeout:L}),this.requestQueue.push(K)});if(B.success)X.writeHead(200),X.end(JSON.stringify({success:!0,data:B.data}));else X.writeHead(200),X.end(JSON.stringify({success:!1,error:B.error}))}catch(G){X.writeHead(500),X.end(JSON.stringify({success:!1,error:G instanceof Error?G.message:"Unknown error"}))}});return}X.writeHead(404),X.end(JSON.stringify({error:"Not found"}))}handleResponse(Q){let X=this.pendingRequests.get(Q.id);if(!X){console.error(`No pending request for response: ${Q.id}`);return}clearTimeout(X.timeout),this.pendingRequests.delete(Q.id),X.resolve(Q)}async sendRequest(Q,X){if(!this.isRunning)return this.sendToExternalBridge(Q,X);let Y={id:NX(),operation:Q,params:X};return new Promise((W,J)=>{let G=setTimeout(()=>{this.pendingRequests.delete(Y.id),J(Error(`Request timeout: ${Q}`))},H0.TIMEOUT_MS);this.pendingRequests.set(Y.id,{resolve:(H)=>{if(H.success)W(H.data);else J(Error(H.error||"Unknown error"))},reject:J,timeout:G}),this.requestQueue.push(Y)})}async sendToExternalBridge(Q,X){let Y=`http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}`,W=await fetch(`${Y}/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:Q,params:X,timeout:H0.TIMEOUT_MS})});if(!W.ok)throw Error(`Bridge request failed: ${W.statusText}`);let J=await W.json();if(!J.success)throw Error(J.error||"Unknown error");return J.data}async checkHealth(){if(this.isRunning)return this.getHealthSummary().pluginConnected;try{let Q=await fetch(`http://${H0.DEFAULT_HOST}:${H0.DEFAULT_PORT}/health`);if(!Q.ok)return!1;let X=await Q.json();return Boolean(X.pluginConnected)}catch{return!1}}getIsRunning(){return this.isRunning}getHealthSummary(){let Q=Date.now();return{status:"ok",pluginConnected:this.lastPollAt!==null?Q-this.lastPollAt<=H0.HEALTH_TTL_MS:!1,pendingRequests:this.pendingRequests.size,queuedRequests:this.requestQueue.length,lastPollAt:this.lastPollAt,lastResponseAt:this.lastResponseAt,lastRequestAt:this.lastRequestAt}}async readJsonBody(Q,X){return new Promise((Y)=>{let W="",J=0,G=H0.MAX_BODY_BYTES;Q.on("data",(H)=>{if(J+=H.length,J>G){X.writeHead(413),X.end(JSON.stringify({error:"Payload too large"})),Q.destroy(),Y(null);return}W+=H}),Q.on("end",()=>{try{let H=JSON.parse(W);Y(H)}catch{X.writeHead(400),X.end(JSON.stringify({error:"Invalid JSON body"})),Y(null)}}),Q.on("error",()=>{X.writeHead(400),X.end(JSON.stringify({error:"Invalid request body"})),Y(null)})})}}var YM=[{name:"figma_status",description:"Check connection status to Figma plugin. Call this first to verify the plugin is running.",inputSchema:{type:"object",properties:{},required:[]}},{name:"figma_list_components",description:"List all available components in the Figma file. Use this to discover reusable components before creating instances.",inputSchema:{type:"object",properties:{filter:{type:"string",description:"Optional filter to search components by name (case-insensitive)"}},required:[]}},{name:"figma_create",description:"Create a new element in Figma. Supports frames, text, rectangles, ellipses, and semantic types like card, button, nav.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["frame","text","rect","ellipse","line","card","button","form","nav","input"],description:"Element type to create"},name:{type:"string",description:"Name for the element"},width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},x:{type:"number",description:"X position"},y:{type:"number",description:"Y position"},parent:{type:"string",description:"Parent element (ID, 'selection', or 'name:ElementName')"},fill:{type:"string",description:"Fill color (hex, e.g., '#FF0000')"},stroke:{type:"string",description:"Stroke color (hex)"},strokeWidth:{type:"number",description:"Stroke width"},strokeAlign:{type:"string",enum:["INSIDE","OUTSIDE","CENTER"],description:"Stroke alignment"},strokeCap:{type:"string",enum:["NONE","ROUND","SQUARE","ARROW_LINES","ARROW_EQUILATERAL"],description:"Stroke cap style"},strokeJoin:{type:"string",enum:["MITER","BEVEL","ROUND"],description:"Stroke join style"},dashPattern:{type:"array",items:{type:"number"},description:"Dash pattern, e.g., [5, 5] for dashed line"},cornerRadius:{type:"number",description:"Uniform corner radius"},topLeftRadius:{type:"number",description:"Top-left corner radius"},topRightRadius:{type:"number",description:"Top-right corner radius"},bottomLeftRadius:{type:"number",description:"Bottom-left corner radius"},bottomRightRadius:{type:"number",description:"Bottom-right corner radius"},content:{type:"string",description:"Text content (for text elements)"},fontSize:{type:"number",description:"Font size (for text elements)"},fontWeight:{type:"number",description:"Font weight 100-900 (for text elements)"},fontFamily:{type:"string",description:"Font family name (e.g., 'Inter', 'Roboto', 'Noto Sans SC')"},textColor:{type:"string",description:"Text color (hex). Preferred over 'fill' for text elements."},textAlign:{type:"string",enum:["LEFT","CENTER","RIGHT","JUSTIFIED"],description:"Text alignment"},textAutoResize:{type:"string",enum:["WIDTH_AND_HEIGHT","HEIGHT","TRUNCATE","NONE"],description:"Text auto-resize mode"},maxWidth:{type:"number",description:"Max width for text wrapping"},lineHeight:{type:"number",description:"Line height in pixels"},letterSpacing:{type:"number",description:"Letter spacing in pixels"},textDecoration:{type:"string",enum:["NONE","UNDERLINE","STRIKETHROUGH"],description:"Text decoration"},textCase:{type:"string",enum:["ORIGINAL","UPPER","LOWER","TITLE"],description:"Text case transformation"},layout:{type:"object",description:"Auto-layout configuration",properties:{direction:{type:"string",enum:["row","column"]},gap:{type:"number"},padding:{type:"number",description:"Uniform padding, or use object for individual sides"},alignItems:{type:"string",enum:["start","center","end","baseline"]},justifyContent:{type:"string",enum:["start","center","end","space-between","space-around"]},wrap:{type:"boolean",description:"Enable wrapping for multi-row/column layouts"}}},layoutSizingHorizontal:{type:"string",enum:["FIXED","HUG","FILL"],description:"Horizontal sizing in auto-layout"},layoutSizingVertical:{type:"string",enum:["FIXED","HUG","FILL"],description:"Vertical sizing in auto-layout"},layoutPositioning:{type:"string",enum:["AUTO","ABSOLUTE"],description:"Positioning mode within auto-layout"},effects:{type:"array",description:"Visual effects (shadows, blur)",items:{type:"object",properties:{type:{type:"string",enum:["DROP_SHADOW","INNER_SHADOW","LAYER_BLUR","BACKGROUND_BLUR"]},color:{type:"string",description:"Effect color (hex with alpha, e.g., '#00000040')"},offset:{type:"object",properties:{x:{type:"number"},y:{type:"number"}}},radius:{type:"number"},spread:{type:"number"}}}},gradient:{type:"object",description:"Gradient fill (replaces solid fill)",properties:{type:{type:"string",enum:["LINEAR","RADIAL","ANGULAR","DIAMOND"]},angle:{type:"number",description:"Angle in degrees (for LINEAR gradient)"},stops:{type:"array",items:{type:"object",properties:{position:{type:"number",description:"Position 0-1"},color:{type:"string",description:"Hex color"}}}}}},rotation:{type:"number",description:"Rotation angle in degrees"},blendMode:{type:"string",enum:["PASS_THROUGH","NORMAL","DARKEN","MULTIPLY","COLOR_BURN","LIGHTEN","SCREEN","COLOR_DODGE","OVERLAY","SOFT_LIGHT","HARD_LIGHT","DIFFERENCE","EXCLUSION"],description:"Blend mode"},clipsContent:{type:"boolean",description:"Clip content to frame bounds"},constraints:{type:"object",description:"Responsive constraints",properties:{horizontal:{type:"string",enum:["MIN","CENTER","MAX","STRETCH","SCALE"]},vertical:{type:"string",enum:["MIN","CENTER","MAX","STRETCH","SCALE"]}}},minWidth:{type:"number",description:"Minimum width"},minHeight:{type:"number",description:"Minimum height"},maxHeight:{type:"number",description:"Maximum height"},children:{type:"array",description:"Nested child elements to create",items:{type:"object"}}},required:["type"]}},{name:"figma_modify",description:"Modify existing elements in Figma. Target by ID, name, or selection.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to modify (ID, 'selection', or 'name:ElementName')"},name:{type:"string",description:"New name"},width:{type:"number",description:"New width"},height:{type:"number",description:"New height"},x:{type:"number",description:"New X position"},y:{type:"number",description:"New Y position"},fill:{type:"string",description:"New fill color (hex)"},stroke:{type:"string",description:"New stroke color (hex)"},strokeWidth:{type:"number",description:"Stroke width"},cornerRadius:{type:"number",description:"New corner radius"},opacity:{type:"number",description:"Opacity (0-1)"},visible:{type:"boolean",description:"Visibility"},locked:{type:"boolean",description:"Lock/unlock element"},content:{type:"string",description:"New text content"},fontSize:{type:"number",description:"New font size"},fontFamily:{type:"string",description:"Font family name (for text elements)"},fontWeight:{type:"number",description:"Font weight (for text elements)"},textColor:{type:"string",description:"Text color (hex, for text elements)"},layout:{type:"object",description:"Layout updates",properties:{direction:{type:"string",enum:["row","column"]},gap:{type:"number"},padding:{type:"number"},alignItems:{type:"string",enum:["start","center","end","baseline"]},justifyContent:{type:"string",enum:["start","center","end","space-between","space-around"]}}}},required:["target"]}},{name:"figma_delete",description:"Delete elements from Figma.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to delete (ID, 'selection', or 'name:ElementName')"}},required:["target"]}},{name:"figma_append",description:"Move element(s) into a container frame.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to move (ID, 'selection', or 'name:ElementName')"},parent:{type:"string",description:"Container to move into (ID, 'selection', or 'name:ContainerName')"}},required:["target","parent"]}},{name:"figma_instantiate",description:"Create an instance of a component. Use list_components first to discover available components.",inputSchema:{type:"object",properties:{component:{type:"string",description:"Component ID or 'name:ComponentName'"},x:{type:"number",description:"X position"},y:{type:"number",description:"Y position"},parent:{type:"string",description:"Parent element to add instance to"}},required:["component"]}},{name:"figma_query",description:"Get detailed information about elements. Use target 'selection' to query currently selected elements (returns multiple nodes).",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to query (ID, 'selection', or 'name:ElementName'). Use 'selection' to get all selected elements."}},required:["target"]}},{name:"figma_to_component",description:"Convert an element to a reusable component.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to convert (ID, 'selection', or 'name:ElementName')"},name:{type:"string",description:"Component name (e.g., 'Button/Primary')"}},required:["target"]}},{name:"figma_create_variants",description:"Create component variants with different property values.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Component to create variants from"},property:{type:"string",description:"Variant property name (e.g., 'state', 'size')"},values:{type:"array",items:{type:"string"},description:"Variant values (e.g., ['default', 'hover', 'pressed'])"}},required:["target","property","values"]}},{name:"figma_accessibility",description:"Check accessibility issues and optionally fix them. Performs WCAG compliance checking for contrast ratios and touch targets.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to check (ID, 'selection', 'page', or 'name:ElementName')"},level:{type:"string",enum:["AA","AAA"],description:"WCAG conformance level (default: AA)"},autoFix:{type:"boolean",description:"Automatically fix issues where possible (default: false)"},output:{type:"string",enum:["json","text"],description:"Output format (default: json)"}},required:["target"]}},{name:"figma_bind_token",description:"Bind a design token to a node property.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to bind token to (ID, 'selection', or 'name:ElementName')"},property:{type:"string",enum:["fill","stroke","fontSize","fontFamily","fontWeight","cornerRadius","gap","padding"],description:"Property to bind"},token:{type:"string",description:"Token name or ID"}},required:["target","property","token"]}},{name:"figma_create_token",description:"Create a new design token.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Token collection name"},name:{type:"string",description:"Token name"},type:{type:"string",enum:["COLOR","NUMBER","STRING","BOOLEAN"],description:"Token type"},value:{description:"Token value",anyOf:[{type:"string"},{type:"number"},{type:"boolean"}]}},required:["collection","name","type","value"]}},{name:"figma_sync_tokens",description:"Import or export design tokens to/from JSON files.",inputSchema:{type:"object",properties:{from:{type:"string",description:"Import from JSON file path"},to:{type:"string",description:"Export to JSON file path"}},required:[]}},{name:"figma_export",description:"Export elements as images (PNG, SVG, PDF). Use after finishing a request to review a PNG.",inputSchema:{type:"object",properties:{target:{type:"string",description:"Element to export"},format:{type:"string",enum:["png","svg","pdf","jpg"],description:"Export format"},scale:{type:"number",description:"Scale factor (default: 1)"}},required:["target","format"]}}],WM={figma_status:"status",figma_list_components:"list-components",figma_create:"create",figma_modify:"modify",figma_delete:"delete",figma_append:"append",figma_instantiate:"instantiate",figma_query:"query",figma_to_component:"to-component",figma_create_variants:"create-variants",figma_accessibility:"accessibility",figma_bind_token:"bind-token",figma_create_token:"create-token",figma_sync_tokens:"sync-tokens",figma_export:"export"};async function JM(){let Q=new M3;await Q.start();let X=new ZX({name:"figma-pilot",version:"0.1.0"},{capabilities:{tools:{}}});X.setRequestHandler(J8,async()=>({tools:YM})),X.setRequestHandler(J9,async(W)=>{let{name:J,arguments:G}=W.params;if(!await Q.checkHealth())return{content:[{type:"text",text:JSON.stringify({error:"Figma plugin not connected. Please open Figma Desktop and run the figma-pilot plugin."})}],isError:!0};let $=WM[J];if(!$)return{content:[{type:"text",text:JSON.stringify({error:`Unknown tool: ${J}`})}],isError:!0};try{let K=G||{},z=await Q.sendRequest($,K);return{content:[{type:"text",text:JSON.stringify(z,null,2)}]}}catch(K){return{content:[{type:"text",text:JSON.stringify({error:K instanceof Error?K.message:"Unknown error"})}],isError:!0}}}),process.on("SIGINT",async()=>{await Q.stop(),process.exit(0)}),process.on("SIGTERM",async()=>{await Q.stop(),process.exit(0)});let Y=new OX;await X.connect(Y),console.error("figma-pilot MCP server running (bridge included)")}JM().catch(console.error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@youware-labs/figma-pilot-mcp",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "MCP server for AI agents to create and modify Figma designs via natural language",
5
5
  "type": "module",
6
6
  "bin": {