@atomixstudio/mcp 1.0.17 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ isAllowedMethod,
4
+ normalizeBridgeMethod
5
+ } from "./chunk-FFAGTYRZ.js";
2
6
 
3
7
  // src/index.ts
4
8
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -12,13 +16,12 @@ import {
12
16
  GetPromptRequestSchema
13
17
  } from "@modelcontextprotocol/sdk/types.js";
14
18
 
15
- // node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/dist/index.js
19
+ // ../atomix-sync-core/dist/index.js
16
20
  import * as fs from "fs";
17
21
  import * as path from "path";
18
22
  import * as path3 from "path";
19
23
  function generateETag(meta) {
20
- const ts = meta.updatedAt ?? meta.exportedAt ?? "";
21
- const hash = `${meta.version}-${ts}`;
24
+ const hash = `${meta.version}-${meta.updatedAt}`;
22
25
  return `"v${hash}"`;
23
26
  }
24
27
  function compareDesignSystems(cached, fresh) {
@@ -221,7 +224,7 @@ function detectGovernanceChangesByFoundation(cached, fresh) {
221
224
  return changes;
222
225
  }
223
226
  async function fetchDesignSystem(options) {
224
- const { dsId: dsId2, apiKey: apiKey2, apiBase: apiBase2 = "https://atomixstudio.eu", etag, forceRefresh = false } = options;
227
+ const { dsId: dsId2, apiKey: apiKey2, accessToken: accessToken2, apiBase: apiBase2 = "https://atomixstudio.eu", etag, forceRefresh = false } = options;
225
228
  if (!dsId2) {
226
229
  throw new Error("Missing dsId. Usage: fetchDesignSystem({ dsId: '...' })");
227
230
  }
@@ -229,7 +232,9 @@ async function fetchDesignSystem(options) {
229
232
  const headers = {
230
233
  "Content-Type": "application/json"
231
234
  };
232
- if (apiKey2) {
235
+ if (accessToken2) {
236
+ headers["Authorization"] = `Bearer ${accessToken2}`;
237
+ } else if (apiKey2) {
233
238
  headers["x-api-key"] = apiKey2;
234
239
  }
235
240
  if (etag) {
@@ -249,7 +254,7 @@ async function fetchDesignSystem(options) {
249
254
  }
250
255
  const data = await response.json();
251
256
  const responseETag = response.headers.get("etag");
252
- const finalETag = responseETag || generateETag(data.meta);
257
+ const finalETag = responseETag || generateETag({ version: data.meta.version, updatedAt: data.meta.exportedAt });
253
258
  const designSystemData = {
254
259
  tokens: data.tokens,
255
260
  cssVariables: data.cssVariables,
@@ -1286,10 +1291,495 @@ function getTokenStats(data) {
1286
1291
  // src/index.ts
1287
1292
  import * as path2 from "path";
1288
1293
  import * as fs2 from "fs";
1294
+ import { execSync } from "child_process";
1295
+ import { platform } from "os";
1296
+ import WebSocket, { WebSocketServer } from "ws";
1297
+ var FIGMA_BRIDGE_PORT = Number(process.env.FIGMA_BRIDGE_PORT) || 8765;
1298
+ var FIGMA_BRIDGE_HOST = process.env.FIGMA_BRIDGE_HOST || "127.0.0.1";
1299
+ var FIGMA_BRIDGE_TIMEOUT_MS = 15e3;
1300
+ var FIGMA_BRIDGE_TOKEN = process.env.FIGMA_BRIDGE_TOKEN || null;
1301
+ var FIGMA_CONNECTION_INSTRUCTIONS = {
1302
+ installAndRun: "In Figma: Open Plugins and run the Atomix plugin (Atomix Token Extractor). If it's not installed yet, install it from the Figma Community or your team's plugin library, then run it.",
1303
+ connect: 'In the plugin UI, tap **Connect to Cursor** and wait until the status shows "Connected".',
1304
+ startBridge: "The Figma bridge runs with this MCP server. Ensure Cursor has started this MCP server (e.g. in Cursor settings), then in Figma run the Atomix plugin and click Connect to Cursor."
1305
+ };
1306
+ var bridgeWss = null;
1307
+ var pluginWs = null;
1308
+ var pendingBridgeRequests = /* @__PURE__ */ new Map();
1309
+ function ensureFigmaBridgePortFree(port) {
1310
+ const portStr = String(port);
1311
+ const ourPid = String(process.pid);
1312
+ try {
1313
+ if (platform() === "win32") {
1314
+ const out = execSync(`netstat -ano`, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
1315
+ const pids = /* @__PURE__ */ new Set();
1316
+ for (const line of out.split(/\r?\n/)) {
1317
+ if (line.includes(`:${portStr}`) && line.includes("LISTENING")) {
1318
+ const parts = line.trim().split(/\s+/);
1319
+ const pid = parts[parts.length - 1];
1320
+ if (/^\d+$/.test(pid) && pid !== ourPid) pids.add(pid);
1321
+ }
1322
+ }
1323
+ for (const pid of pids) {
1324
+ try {
1325
+ execSync(`taskkill /PID ${pid} /F`, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
1326
+ console.error(`[atomix-mcp] Freed Figma bridge port ${port} (killed PID ${pid})`);
1327
+ } catch (_) {
1328
+ }
1329
+ }
1330
+ } else {
1331
+ const out = execSync(`lsof -ti :${portStr}`, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1332
+ if (!out) return;
1333
+ const pids = out.split(/\s+/).filter((p) => p && p !== ourPid);
1334
+ for (const pid of pids) {
1335
+ try {
1336
+ execSync(`kill -9 ${pid}`, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
1337
+ console.error(`[atomix-mcp] Freed Figma bridge port ${port} (killed PID ${pid})`);
1338
+ } catch (_) {
1339
+ }
1340
+ }
1341
+ }
1342
+ } catch {
1343
+ }
1344
+ }
1345
+ function startFigmaBridge() {
1346
+ if (bridgeWss) return;
1347
+ try {
1348
+ ensureFigmaBridgePortFree(FIGMA_BRIDGE_PORT);
1349
+ bridgeWss = new WebSocketServer({
1350
+ host: FIGMA_BRIDGE_HOST,
1351
+ port: FIGMA_BRIDGE_PORT,
1352
+ clientTracking: true
1353
+ });
1354
+ bridgeWss.on("connection", (ws, req) => {
1355
+ const url = req.url || "";
1356
+ const params = new URLSearchParams(url.startsWith("/") ? url.slice(1) : url);
1357
+ const token = params.get("token");
1358
+ const role = params.get("role");
1359
+ if (FIGMA_BRIDGE_TOKEN && token !== FIGMA_BRIDGE_TOKEN) {
1360
+ ws.close(4003, "Invalid or missing bridge token");
1361
+ return;
1362
+ }
1363
+ if (role !== "plugin") {
1364
+ ws.close(4002, "Only role=plugin is accepted (bridge runs in MCP server)");
1365
+ return;
1366
+ }
1367
+ if (pluginWs) {
1368
+ try {
1369
+ pluginWs.close();
1370
+ } catch (_) {
1371
+ }
1372
+ pluginWs = null;
1373
+ }
1374
+ pluginWs = ws;
1375
+ ws.on("message", (raw) => {
1376
+ const text = typeof raw === "string" ? raw : raw.toString("utf8");
1377
+ let msg;
1378
+ try {
1379
+ msg = JSON.parse(text);
1380
+ } catch {
1381
+ return;
1382
+ }
1383
+ const parsed = msg;
1384
+ if (parsed?.type === "ping" && typeof parsed.id === "string") {
1385
+ try {
1386
+ ws.send(JSON.stringify({ type: "pong", id: parsed.id }));
1387
+ } catch (_) {
1388
+ }
1389
+ return;
1390
+ }
1391
+ if (typeof parsed.id === "string" && ("result" in parsed || "error" in parsed)) {
1392
+ const pending = pendingBridgeRequests.get(parsed.id);
1393
+ if (pending) {
1394
+ clearTimeout(pending.timeout);
1395
+ pendingBridgeRequests.delete(parsed.id);
1396
+ if (parsed.error) pending.reject(new Error(parsed.error));
1397
+ else pending.resolve(parsed.result);
1398
+ }
1399
+ }
1400
+ });
1401
+ ws.on("close", () => {
1402
+ if (pluginWs === ws) pluginWs = null;
1403
+ });
1404
+ ws.on("error", () => {
1405
+ if (pluginWs === ws) pluginWs = null;
1406
+ });
1407
+ });
1408
+ bridgeWss.on("listening", () => {
1409
+ console.error(`[atomix-mcp] Figma bridge listening on ws://${FIGMA_BRIDGE_HOST}:${FIGMA_BRIDGE_PORT} (local only)`);
1410
+ if (FIGMA_BRIDGE_TOKEN) {
1411
+ console.error("[atomix-mcp] Figma bridge token required (FIGMA_BRIDGE_TOKEN)");
1412
+ }
1413
+ });
1414
+ bridgeWss.on("error", (err) => {
1415
+ console.error("[atomix-mcp] Figma bridge server error:", err);
1416
+ });
1417
+ } catch (err) {
1418
+ console.error("[atomix-mcp] Failed to start Figma bridge:", err);
1419
+ }
1420
+ }
1421
+ function closeFigmaBridge() {
1422
+ if (pluginWs) {
1423
+ try {
1424
+ pluginWs.close();
1425
+ } catch (_) {
1426
+ }
1427
+ pluginWs = null;
1428
+ }
1429
+ if (bridgeWss) {
1430
+ try {
1431
+ bridgeWss.close();
1432
+ } catch (_) {
1433
+ }
1434
+ bridgeWss = null;
1435
+ }
1436
+ }
1437
+ function isBridgeReachable() {
1438
+ return Promise.resolve(!!(pluginWs && pluginWs.readyState === WebSocket.OPEN));
1439
+ }
1440
+ function sendBridgeRequest(method, params, timeoutMs = FIGMA_BRIDGE_TIMEOUT_MS) {
1441
+ const normalized = normalizeBridgeMethod(method);
1442
+ if (!isAllowedMethod(normalized)) {
1443
+ return Promise.reject(new Error(`Bridge method not allowed: ${method}`));
1444
+ }
1445
+ const ws = pluginWs;
1446
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
1447
+ return Promise.reject(
1448
+ new Error("Figma plugin not connected. Open Figma, run Atomix plugin, and click Connect to Cursor.")
1449
+ );
1450
+ }
1451
+ const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
1452
+ return new Promise((resolve4, reject) => {
1453
+ const timeout = setTimeout(() => {
1454
+ if (pendingBridgeRequests.delete(id)) {
1455
+ reject(new Error("Figma bridge timeout. " + FIGMA_CONNECTION_INSTRUCTIONS.startBridge + " Then " + FIGMA_CONNECTION_INSTRUCTIONS.connect));
1456
+ }
1457
+ }, timeoutMs);
1458
+ pendingBridgeRequests.set(id, { resolve: resolve4, reject, timeout });
1459
+ try {
1460
+ ws.send(JSON.stringify({ id, method: normalized, params }));
1461
+ } catch (e) {
1462
+ pendingBridgeRequests.delete(id);
1463
+ clearTimeout(timeout);
1464
+ reject(e instanceof Error ? e : new Error(String(e)));
1465
+ }
1466
+ });
1467
+ }
1468
+ function figmaColorNameWithGroup(key) {
1469
+ if (key.includes("/")) {
1470
+ const [group2, ...rest] = key.split("/");
1471
+ const name2 = rest.join("/").trim();
1472
+ if (!name2) return key;
1473
+ const groupDisplay2 = group2.charAt(0).toUpperCase() + group2.slice(1).toLowerCase();
1474
+ return `${groupDisplay2} / ${name2}`;
1475
+ }
1476
+ const firstDash = key.indexOf("-");
1477
+ if (firstDash <= 0) return key;
1478
+ const group = key.slice(0, firstDash);
1479
+ const name = key.slice(firstDash + 1);
1480
+ const groupDisplay = group.charAt(0).toUpperCase() + group.slice(1).toLowerCase();
1481
+ return `${groupDisplay} / ${name}`;
1482
+ }
1483
+ function tokenValueToNumber(s) {
1484
+ if (typeof s !== "string" || !s.trim()) return 0;
1485
+ const t = s.trim();
1486
+ if (t.endsWith("rem")) {
1487
+ const n2 = parseFloat(t.replace(/rem$/, ""));
1488
+ return Number.isFinite(n2) ? Math.round(n2 * 16) : 0;
1489
+ }
1490
+ if (t.endsWith("px")) {
1491
+ const n2 = parseFloat(t.replace(/px$/, ""));
1492
+ return Number.isFinite(n2) ? Math.round(n2) : 0;
1493
+ }
1494
+ const n = parseFloat(t);
1495
+ return Number.isFinite(n) ? n : 0;
1496
+ }
1497
+ function parseBoxShadowToFigmaEffect(shadowStr) {
1498
+ const s = shadowStr.trim();
1499
+ if (!s || s.toLowerCase() === "none") return null;
1500
+ const parsePx = (x) => typeof x === "string" ? parseFloat(x.replace(/px$/i, "")) : NaN;
1501
+ const colorMatch = s.match(/(rgba?\s*\([^)]+\)|#[0-9A-Fa-f]{3,8})\s*$/i);
1502
+ const colorStr = colorMatch ? colorMatch[1].trim() : void 0;
1503
+ const rest = (colorMatch ? s.slice(0, colorMatch.index) : s).trim();
1504
+ const parts = rest ? rest.split(/\s+/) : [];
1505
+ if (parts.length < 3) return null;
1506
+ const offsetX = parsePx(parts[0]);
1507
+ const offsetY = parsePx(parts[1]);
1508
+ const blur = parsePx(parts[2]);
1509
+ let spread = 0;
1510
+ if (parts.length >= 4) spread = parsePx(parts[3]);
1511
+ let r = 0, g = 0, b = 0, a = 0.1;
1512
+ if (colorStr) {
1513
+ const rgbaMatch = colorStr.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)/i);
1514
+ if (rgbaMatch) {
1515
+ r = Number(rgbaMatch[1]) / 255;
1516
+ g = Number(rgbaMatch[2]) / 255;
1517
+ b = Number(rgbaMatch[3]) / 255;
1518
+ a = rgbaMatch[4] != null ? parseFloat(rgbaMatch[4]) : 1;
1519
+ } else {
1520
+ const hexMatch = colorStr.match(/^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/);
1521
+ if (hexMatch) {
1522
+ r = parseInt(hexMatch[1].slice(0, 2), 16) / 255;
1523
+ g = parseInt(hexMatch[1].slice(2, 4), 16) / 255;
1524
+ b = parseInt(hexMatch[1].slice(4, 6), 16) / 255;
1525
+ a = hexMatch[2] ? parseInt(hexMatch[2], 16) / 255 : 0.1;
1526
+ }
1527
+ }
1528
+ }
1529
+ if (!Number.isFinite(offsetX) || !Number.isFinite(offsetY) || !Number.isFinite(blur)) return null;
1530
+ return {
1531
+ type: "DROP_SHADOW",
1532
+ offset: { x: offsetX, y: offsetY },
1533
+ radius: Math.max(0, blur),
1534
+ spread: Number.isFinite(spread) ? spread : 0,
1535
+ color: { r, g, b, a },
1536
+ visible: true,
1537
+ blendMode: "NORMAL"
1538
+ };
1539
+ }
1540
+ function parseBoxShadowToFigmaEffects(shadowStr) {
1541
+ const s = (shadowStr || "").trim();
1542
+ if (!s || s.toLowerCase() === "none") return [];
1543
+ const out = [];
1544
+ const segments = s.split(/\s*,\s*/);
1545
+ for (const seg of segments) {
1546
+ const effect = parseBoxShadowToFigmaEffect(seg.trim());
1547
+ if (effect) out.push(effect);
1548
+ }
1549
+ return out;
1550
+ }
1551
+ function buildFigmaPayloadsFromDS(data) {
1552
+ const tokens = data.tokens;
1553
+ const colors = tokens?.colors;
1554
+ const typography = tokens?.typography;
1555
+ const modes = [];
1556
+ const variables = [];
1557
+ const paintStyles = [];
1558
+ const hexRe = /^#?[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/;
1559
+ const addedNames = /* @__PURE__ */ new Set();
1560
+ if (colors?.modes) {
1561
+ const light = colors.modes.light ?? {};
1562
+ const dark = colors.modes.dark ?? {};
1563
+ if (Object.keys(light).length > 0) modes.push("Light");
1564
+ if (Object.keys(dark).length > 0 && !modes.includes("Dark")) modes.push("Dark");
1565
+ if (modes.length === 0) modes.push("Light");
1566
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(light), ...Object.keys(dark)]);
1567
+ for (const key of allKeys) {
1568
+ const lightHex = light[key];
1569
+ const darkHex = dark[key];
1570
+ if (typeof lightHex === "string" && hexRe.test(lightHex)) {
1571
+ const figmaName = figmaColorNameWithGroup(key);
1572
+ if (addedNames.has(figmaName)) continue;
1573
+ addedNames.add(figmaName);
1574
+ const values = {};
1575
+ if (modes.includes("Light")) values.Light = lightHex;
1576
+ if (modes.includes("Dark")) values.Dark = typeof darkHex === "string" && hexRe.test(darkHex) ? darkHex : lightHex;
1577
+ variables.push({ name: figmaName, values });
1578
+ paintStyles.push({ name: figmaName, color: lightHex });
1579
+ }
1580
+ }
1581
+ }
1582
+ if (colors?.static?.brand && typeof colors.static.brand === "object") {
1583
+ for (const [key, hex] of Object.entries(colors.static.brand)) {
1584
+ if (typeof hex !== "string" || !hexRe.test(hex)) continue;
1585
+ const figmaName = figmaColorNameWithGroup(`brand/${key}`);
1586
+ if (addedNames.has(figmaName)) continue;
1587
+ addedNames.add(figmaName);
1588
+ paintStyles.push({ name: figmaName, color: hex });
1589
+ if (modes.length === 0) modes.push("Light");
1590
+ const values = {};
1591
+ for (const m of modes) values[m] = hex;
1592
+ variables.push({ name: figmaName, values });
1593
+ }
1594
+ }
1595
+ if (variables.length === 0 && modes.length === 0) modes.push("Light");
1596
+ const collectionName = data.meta?.name ? `${data.meta.name} Colors` : "Atomix Colors";
1597
+ const textStyles = [];
1598
+ const sizeToPx = (val, basePx = 16) => {
1599
+ if (typeof val === "number") return Math.round(val);
1600
+ const s = String(val).trim();
1601
+ const pxMatch = s.match(/^([\d.]+)\s*px$/i);
1602
+ if (pxMatch) return Math.round(parseFloat(pxMatch[1]));
1603
+ const remMatch = s.match(/^([\d.]+)\s*rem$/i);
1604
+ if (remMatch) return Math.round(parseFloat(remMatch[1]) * basePx);
1605
+ const n = parseFloat(s);
1606
+ if (Number.isFinite(n)) return n <= 0 ? basePx : n < 50 ? Math.round(n * basePx) : Math.round(n);
1607
+ return basePx;
1608
+ };
1609
+ const letterSpacingToPx = (val, fontSizePx) => {
1610
+ if (val === void 0 || val === null) return void 0;
1611
+ if (typeof val === "number") return Math.round(val);
1612
+ const s = String(val).trim();
1613
+ const pxMatch = s.match(/^([-\d.]+)\s*px$/i);
1614
+ if (pxMatch) return Math.round(parseFloat(pxMatch[1]));
1615
+ const emMatch = s.match(/^([-\d.]+)\s*em$/i);
1616
+ if (emMatch) return Math.round(parseFloat(emMatch[1]) * fontSizePx);
1617
+ const n = parseFloat(s);
1618
+ return Number.isFinite(n) ? Math.round(n) : void 0;
1619
+ };
1620
+ const firstFont = (obj) => {
1621
+ if (typeof obj === "string") {
1622
+ const match = obj.match(/['"]?([^'",\s]+)['"]?/);
1623
+ return match ? match[1] : "Inter";
1624
+ }
1625
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) {
1626
+ const v = obj.body ?? obj.heading ?? obj.display ?? Object.values(obj)[0];
1627
+ return firstFont(v);
1628
+ }
1629
+ return "Inter";
1630
+ };
1631
+ const fontFamily = typography ? firstFont(typography.fontFamily ?? "Inter") : "Inter";
1632
+ const fontSizeMap = typography?.fontSize;
1633
+ const fontWeightMap = typography?.fontWeight;
1634
+ const lineHeightMap = typography?.lineHeight;
1635
+ const letterSpacingMap = typography?.letterSpacing;
1636
+ const textTransformMap = typography?.textTransform;
1637
+ const textDecorationMap = typography?.textDecoration;
1638
+ if (fontSizeMap && typeof fontSizeMap === "object" && Object.keys(fontSizeMap).length > 0) {
1639
+ for (const [key, sizeVal] of Object.entries(fontSizeMap)) {
1640
+ const fontSize = sizeToPx(sizeVal);
1641
+ if (fontSize <= 0) continue;
1642
+ const lh = lineHeightMap && typeof lineHeightMap === "object" ? lineHeightMap[key] : void 0;
1643
+ const weight = fontWeightMap && typeof fontWeightMap === "object" ? fontWeightMap[key] : void 0;
1644
+ const fontWeight = weight != null ? String(weight) : "400";
1645
+ const letterSpacingPx = letterSpacingToPx(
1646
+ letterSpacingMap && typeof letterSpacingMap === "object" ? letterSpacingMap[key] : void 0,
1647
+ fontSize
1648
+ );
1649
+ const textTransform = textTransformMap && typeof textTransformMap === "object" ? textTransformMap[key] : void 0;
1650
+ const textDecoration = textDecorationMap && typeof textDecorationMap === "object" ? textDecorationMap[key] : void 0;
1651
+ const namePart = key.replace(/-/g, " / ");
1652
+ const style = {
1653
+ name: namePart.startsWith("Typography") ? namePart : `Typography / ${namePart}`,
1654
+ fontFamily,
1655
+ fontWeight,
1656
+ fontSize,
1657
+ lineHeightUnit: "PERCENT",
1658
+ letterSpacingUnit: "PIXELS",
1659
+ ...letterSpacingPx !== void 0 && letterSpacingPx !== 0 ? { letterSpacingValue: letterSpacingPx } : {}
1660
+ };
1661
+ if (lh != null && typeof lh === "number" && lh > 0) {
1662
+ style.lineHeightValue = lh >= 10 ? Math.round(lh / fontSize * 100) : Math.round(lh * 100);
1663
+ } else {
1664
+ style.lineHeightValue = 150;
1665
+ }
1666
+ if (textTransform === "uppercase") style.textCase = "UPPER";
1667
+ else if (textTransform === "lowercase") style.textCase = "LOWER";
1668
+ else if (textTransform === "capitalize") style.textCase = "TITLE";
1669
+ else style.textCase = "ORIGINAL";
1670
+ if (textDecoration === "underline") style.textDecoration = "UNDERLINE";
1671
+ else style.textDecoration = "NONE";
1672
+ textStyles.push(style);
1673
+ }
1674
+ }
1675
+ const textStylesMap = typography?.textStyles;
1676
+ if (textStyles.length === 0 && textStylesMap && typeof textStylesMap === "object") {
1677
+ for (const [styleName, style] of Object.entries(textStylesMap)) {
1678
+ if (!style || typeof style !== "object") continue;
1679
+ const fontSize = sizeToPx(style.fontSize ?? "1rem");
1680
+ const lhStr = style.lineHeight;
1681
+ const lineHeightUnitless = lhStr != null ? lhStr.endsWith("%") ? parseFloat(lhStr) / 100 : sizeToPx(lhStr) / fontSize : 1.5;
1682
+ const payload = {
1683
+ name: styleName.startsWith("Typography") ? styleName : `Typography / ${styleName.replace(/\//g, " / ")}`,
1684
+ fontFamily,
1685
+ fontWeight: String(style.fontWeight ?? "400"),
1686
+ fontSize,
1687
+ lineHeightUnit: "PERCENT",
1688
+ lineHeightValue: Math.round((Number.isFinite(lineHeightUnitless) ? lineHeightUnitless : 1.5) * 100),
1689
+ letterSpacingUnit: "PIXELS",
1690
+ textCase: "ORIGINAL",
1691
+ textDecoration: "NONE"
1692
+ };
1693
+ textStyles.push(payload);
1694
+ }
1695
+ }
1696
+ const numberVariables = [];
1697
+ const dsName = data.meta?.name ?? "Atomix";
1698
+ const primitivesCollectionName = `${dsName} Primitives`;
1699
+ const spacing = tokens?.spacing;
1700
+ if (spacing?.scale && typeof spacing.scale === "object") {
1701
+ for (const [key, val] of Object.entries(spacing.scale)) {
1702
+ const n = tokenValueToNumber(val);
1703
+ if (n >= 0) numberVariables.push({ name: `Spacing / ${key}`, value: n });
1704
+ }
1705
+ }
1706
+ const radius = tokens?.radius;
1707
+ if (radius?.scale && typeof radius.scale === "object") {
1708
+ for (const [key, val] of Object.entries(radius.scale)) {
1709
+ const n = tokenValueToNumber(val);
1710
+ if (n >= 0) numberVariables.push({ name: `Radius / ${key}`, value: n });
1711
+ }
1712
+ }
1713
+ const borders = tokens?.borders;
1714
+ if (borders?.width && typeof borders.width === "object") {
1715
+ for (const [key, val] of Object.entries(borders.width)) {
1716
+ const n = tokenValueToNumber(val);
1717
+ if (n >= 0) numberVariables.push({ name: `Borders / ${key}`, value: n });
1718
+ }
1719
+ }
1720
+ const sizing = tokens?.sizing;
1721
+ if (sizing?.height && typeof sizing.height === "object") {
1722
+ for (const [key, val] of Object.entries(sizing.height)) {
1723
+ const n = tokenValueToNumber(val);
1724
+ if (n >= 0) numberVariables.push({ name: `Height / ${key}`, value: n });
1725
+ }
1726
+ }
1727
+ if (sizing?.icon && typeof sizing.icon === "object") {
1728
+ for (const [key, val] of Object.entries(sizing.icon)) {
1729
+ const n = tokenValueToNumber(val);
1730
+ if (n >= 0) numberVariables.push({ name: `Icon / ${key}`, value: n });
1731
+ }
1732
+ }
1733
+ const layout = tokens?.layout;
1734
+ if (layout?.breakpoint && typeof layout.breakpoint === "object") {
1735
+ for (const [key, val] of Object.entries(layout.breakpoint)) {
1736
+ const n = tokenValueToNumber(val);
1737
+ if (n >= 0) numberVariables.push({ name: `Breakpoint / ${key}`, value: n });
1738
+ }
1739
+ }
1740
+ const effectStyles = [];
1741
+ const shadows = tokens?.shadows;
1742
+ if (shadows?.elevation && typeof shadows.elevation === "object") {
1743
+ for (const [key, val] of Object.entries(shadows.elevation)) {
1744
+ if (typeof val !== "string") continue;
1745
+ const effects = parseBoxShadowToFigmaEffects(val);
1746
+ if (effects.length > 0) {
1747
+ effectStyles.push({
1748
+ name: `Shadow / ${key}`,
1749
+ effects
1750
+ });
1751
+ }
1752
+ }
1753
+ }
1754
+ if (shadows?.focus && typeof shadows.focus === "string") {
1755
+ const effects = parseBoxShadowToFigmaEffects(shadows.focus);
1756
+ if (effects.length > 0) {
1757
+ effectStyles.push({ name: "Shadow / focus", effects });
1758
+ }
1759
+ }
1760
+ return {
1761
+ colorVariables: { collectionName, modes, variables },
1762
+ paintStyles,
1763
+ textStyles,
1764
+ numberVariables: { collectionName: primitivesCollectionName, variables: numberVariables },
1765
+ effectStyles
1766
+ };
1767
+ }
1768
+ function getExpectedFigmaNamesFromDS(data) {
1769
+ const payloads = buildFigmaPayloadsFromDS(data);
1770
+ return {
1771
+ colorVariableNames: payloads.colorVariables.variables.map((v) => v.name),
1772
+ paintStyleNames: payloads.paintStyles.map((s) => s.name),
1773
+ textStyleNames: payloads.textStyles.map((s) => s.name),
1774
+ effectStyleNames: payloads.effectStyles.map((s) => s.name),
1775
+ numberVariableNames: payloads.numberVariables.variables.map((v) => v.name)
1776
+ };
1777
+ }
1289
1778
  function parseArgs() {
1290
1779
  const args = process.argv.slice(2);
1291
1780
  let dsId2 = null;
1292
1781
  let apiKey2 = null;
1782
+ let accessToken2 = null;
1293
1783
  let apiBase2 = null;
1294
1784
  for (let i = 0; i < args.length; i++) {
1295
1785
  if (args[i] === "--ds-id" && args[i + 1]) {
@@ -1298,19 +1788,42 @@ function parseArgs() {
1298
1788
  } else if (args[i] === "--api-key" && args[i + 1]) {
1299
1789
  apiKey2 = args[i + 1];
1300
1790
  i++;
1791
+ } else if (args[i] === "--atomix-token" && args[i + 1]) {
1792
+ accessToken2 = args[i + 1];
1793
+ i++;
1301
1794
  } else if (args[i] === "--api-base" && args[i + 1]) {
1302
1795
  apiBase2 = args[i + 1];
1303
1796
  i++;
1304
1797
  }
1305
1798
  }
1306
- return { dsId: dsId2, apiKey: apiKey2, apiBase: apiBase2 };
1799
+ return { dsId: dsId2, apiKey: apiKey2, accessToken: accessToken2, apiBase: apiBase2 };
1307
1800
  }
1308
1801
  var cliArgs = parseArgs();
1309
- var { dsId, apiKey } = cliArgs;
1802
+ var { dsId, apiKey, accessToken } = cliArgs;
1310
1803
  var apiBase = cliArgs.apiBase || "https://atomixstudio.eu";
1311
1804
  var cachedData = null;
1312
1805
  var cachedETag = null;
1806
+ var cachedMcpTier = null;
1807
+ var authFailedNoTools = false;
1808
+ function hasValidAuthConfig() {
1809
+ return !!(dsId && accessToken);
1810
+ }
1811
+ var AUTH_REQUIRED_MESSAGE = "Atomix MCP requires authentication. Add both --ds-id and --atomix-token to your MCP config (Settings \u2192 MCP), then restart Cursor. Get your token from Atomix Studio: Export modal or Settings \u2192 Regenerate Atomix access token.";
1313
1812
  var lastChangeSummary = null;
1813
+ var FIGMA_TOOL_NAMES = /* @__PURE__ */ new Set([
1814
+ "syncToFigma",
1815
+ "getFigmaVariablesAndStyles",
1816
+ "createDesignPlaceholder",
1817
+ "resolveFigmaIdsForTokens",
1818
+ "designCreateFrame",
1819
+ "designCreateText",
1820
+ "designCreateRectangle",
1821
+ "designSetAutoLayout",
1822
+ "designSetLayoutConstraints",
1823
+ "designAppendChild",
1824
+ "getDesignScreenshot",
1825
+ "finalizeDesignFrame"
1826
+ ]);
1314
1827
  var lastSyncAffectedTokens = null;
1315
1828
  function getLastChangeSummary() {
1316
1829
  return lastChangeSummary;
@@ -1326,10 +1839,11 @@ ${changes.summary}`);
1326
1839
  }
1327
1840
  }
1328
1841
  async function fetchDesignSystemForMCP(forceRefresh = false) {
1329
- if (!dsId) throw new Error("Missing --ds-id. Usage: npx @atomixstudio/mcp --ds-id <id>");
1842
+ if (!dsId) throw new Error("Missing --ds-id. Usage: npx @atomixstudio/mcp --ds-id <id> --atomix-token <token>");
1843
+ if (!accessToken) throw new Error("Missing --atomix-token. Get your token from the Export modal or Settings.");
1330
1844
  const result = await fetchDesignSystem({
1331
1845
  dsId,
1332
- apiKey: apiKey ?? void 0,
1846
+ accessToken,
1333
1847
  apiBase: apiBase ?? void 0,
1334
1848
  etag: forceRefresh ? void 0 : cachedETag ?? void 0,
1335
1849
  forceRefresh
@@ -1338,6 +1852,7 @@ async function fetchDesignSystemForMCP(forceRefresh = false) {
1338
1852
  if (result.status === 304 || !result.data) throw new Error("No design system data (304 or null)");
1339
1853
  cachedData = result.data;
1340
1854
  cachedETag = result.etag;
1855
+ cachedMcpTier = result.data.meta.mcpTier ?? null;
1341
1856
  await updateChangeSummary(result.data);
1342
1857
  return result.data;
1343
1858
  }
@@ -1345,7 +1860,7 @@ var TOKEN_CATEGORIES = ["colors", "typography", "spacing", "sizing", "shadows",
1345
1860
  var server = new Server(
1346
1861
  {
1347
1862
  name: "atomix-mcp-user",
1348
- version: "1.0.17"
1863
+ version: "1.0.19"
1349
1864
  },
1350
1865
  {
1351
1866
  capabilities: {
@@ -1356,165 +1871,494 @@ var server = new Server(
1356
1871
  }
1357
1872
  );
1358
1873
  server.setRequestHandler(ListToolsRequestSchema, async () => {
1359
- return {
1360
- tools: [
1361
- {
1362
- name: "getToken",
1363
- description: "Get a specific design token by its path. Returns the value and CSS variable name.",
1364
- inputSchema: {
1365
- type: "object",
1366
- properties: {
1367
- path: {
1368
- type: "string",
1369
- description: "Token path in dot notation (e.g., 'colors.brand.primary', 'spacing.scale.md')"
1370
- }
1371
- },
1372
- required: ["path"]
1373
- }
1374
- },
1375
- {
1376
- name: "listTokens",
1377
- description: "List all tokens in a category (colors, typography, spacing, sizing, shadows, radius, borders, motion, zIndex).",
1378
- inputSchema: {
1379
- type: "object",
1380
- properties: {
1381
- category: {
1382
- type: "string",
1383
- enum: TOKEN_CATEGORIES,
1384
- description: "Token category to list"
1385
- },
1386
- subcategory: {
1387
- type: "string",
1388
- description: "Optional subcategory (e.g., 'brand' for colors, 'scale' for spacing)"
1389
- }
1390
- },
1391
- required: ["category"]
1392
- }
1393
- },
1394
- {
1395
- name: "searchTokens",
1396
- description: "Search for tokens by name or value.",
1397
- inputSchema: {
1398
- type: "object",
1399
- properties: {
1400
- query: {
1401
- type: "string",
1402
- description: "Search query (matches token paths or values)"
1403
- }
1404
- },
1405
- required: ["query"]
1406
- }
1407
- },
1408
- {
1409
- name: "validateUsage",
1410
- description: "Check if a CSS value follows the design system. Detects hardcoded values that should use tokens.",
1411
- inputSchema: {
1412
- type: "object",
1413
- properties: {
1414
- value: {
1415
- type: "string",
1416
- description: "CSS value to validate (e.g., '#ff0000', '16px', 'rgb(0,112,97)')"
1417
- },
1418
- context: {
1419
- type: "string",
1420
- enum: ["color", "spacing", "radius", "shadow", "typography", "any"],
1421
- description: "Context of the value to help find the right token"
1422
- }
1423
- },
1424
- required: ["value"]
1425
- }
1426
- },
1427
- {
1428
- name: "getAIToolRules",
1429
- description: "Generate design system rules for AI coding tools (Cursor, Copilot, Windsurf, etc.).",
1430
- inputSchema: {
1431
- type: "object",
1432
- properties: {
1433
- tool: {
1434
- type: "string",
1435
- enum: ["cursor", "copilot", "windsurf", "cline", "continue", "zed", "generic", "all"],
1436
- description: "AI tool to generate rules for. Use 'all' to get rules for all tools."
1437
- }
1874
+ if (!hasValidAuthConfig()) {
1875
+ authFailedNoTools = true;
1876
+ console.error("[Atomix MCP] Missing --ds-id or --atomix-token. Add both to your MCP config.");
1877
+ throw new Error(AUTH_REQUIRED_MESSAGE);
1878
+ }
1879
+ if (cachedMcpTier === null) {
1880
+ try {
1881
+ await fetchDesignSystemForMCP(true);
1882
+ if (cachedMcpTier === "pro") {
1883
+ console.error("[Atomix MCP] Resolved tier = pro. Figma sync/design tools are available.");
1884
+ } else if (cachedMcpTier === "free") {
1885
+ console.error(
1886
+ "[Atomix MCP] Resolved tier = free. Figma sync/design tools are hidden. Pro tools appear when the DS owner has Pro and the pro_figma_export flag is enabled."
1887
+ );
1888
+ }
1889
+ } catch (err) {
1890
+ const msg = err instanceof Error ? err.message : String(err);
1891
+ authFailedNoTools = true;
1892
+ console.error(
1893
+ "[Atomix MCP] Design system not loaded: ds-id or token invalid or API error. No tools will be shown.",
1894
+ msg.includes("401") ? " Token invalid or expired. Regenerate in Atomix Studio (Settings \u2192 Regenerate Atomix access token), update your MCP config, then restart Cursor." : msg.includes("403") ? " You do not have access to this design system (owner or invited guest)." : msg.includes("404") ? " Design system not found (invalid ds-id)." : msg
1895
+ );
1896
+ }
1897
+ }
1898
+ if (authFailedNoTools) {
1899
+ throw new Error(AUTH_REQUIRED_MESSAGE);
1900
+ }
1901
+ const toolsList = [
1902
+ {
1903
+ name: "getToken",
1904
+ description: "Get a specific design token by its path. Returns the value and CSS variable name.",
1905
+ inputSchema: {
1906
+ type: "object",
1907
+ properties: {
1908
+ path: {
1909
+ type: "string",
1910
+ description: "Token path in dot notation (e.g., 'colors.brand.primary', 'spacing.scale.md')"
1911
+ }
1912
+ },
1913
+ required: ["path"]
1914
+ }
1915
+ },
1916
+ {
1917
+ name: "listTokens",
1918
+ description: "List all tokens in a category (colors, typography, spacing, sizing, shadows, radius, borders, motion, zIndex).",
1919
+ inputSchema: {
1920
+ type: "object",
1921
+ properties: {
1922
+ category: {
1923
+ type: "string",
1924
+ enum: TOKEN_CATEGORIES,
1925
+ description: "Token category to list"
1438
1926
  },
1439
- required: ["tool"]
1440
- }
1441
- },
1442
- {
1443
- name: "exportMCPConfig",
1444
- description: "Generate MCP configuration file for AI tools.",
1445
- inputSchema: {
1446
- type: "object",
1447
- properties: {
1448
- tool: {
1449
- type: "string",
1450
- enum: ["cursor", "claude-desktop", "windsurf", "continue", "vscode", "all"],
1451
- description: "AI tool to generate MCP config for."
1452
- }
1927
+ subcategory: {
1928
+ type: "string",
1929
+ description: "Optional subcategory (e.g., 'brand' for colors, 'scale' for spacing)"
1930
+ }
1931
+ },
1932
+ required: ["category"]
1933
+ }
1934
+ },
1935
+ {
1936
+ name: "searchTokens",
1937
+ description: "Search for tokens by name or value.",
1938
+ inputSchema: {
1939
+ type: "object",
1940
+ properties: {
1941
+ query: {
1942
+ type: "string",
1943
+ description: "Search query (matches token paths or values)"
1944
+ }
1945
+ },
1946
+ required: ["query"]
1947
+ }
1948
+ },
1949
+ {
1950
+ name: "validateUsage",
1951
+ description: "Check if a CSS value follows the design system. Detects hardcoded values that should use tokens.",
1952
+ inputSchema: {
1953
+ type: "object",
1954
+ properties: {
1955
+ value: {
1956
+ type: "string",
1957
+ description: "CSS value to validate (e.g., '#ff0000', '16px', 'rgb(0,112,97)')"
1453
1958
  },
1454
- required: ["tool"]
1455
- }
1456
- },
1457
- {
1458
- name: "getSetupInstructions",
1459
- description: "Get detailed setup instructions for a specific AI tool.",
1460
- inputSchema: {
1461
- type: "object",
1462
- properties: {
1463
- tool: {
1464
- type: "string",
1465
- enum: ["cursor", "copilot", "windsurf", "cline", "continue", "zed", "claude-desktop", "generic"],
1466
- description: "AI tool to get setup instructions for."
1467
- }
1959
+ context: {
1960
+ type: "string",
1961
+ enum: ["color", "spacing", "radius", "shadow", "typography", "any"],
1962
+ description: "Context of the value to help find the right token"
1963
+ }
1964
+ },
1965
+ required: ["value"]
1966
+ }
1967
+ },
1968
+ {
1969
+ name: "getAIToolRules",
1970
+ description: "Generate design system rules for AI coding tools (Cursor, Copilot, Windsurf, etc.).",
1971
+ inputSchema: {
1972
+ type: "object",
1973
+ properties: {
1974
+ tool: {
1975
+ type: "string",
1976
+ enum: ["cursor", "copilot", "windsurf", "cline", "continue", "zed", "generic", "all"],
1977
+ description: "AI tool to generate rules for. Use 'all' to get rules for all tools."
1978
+ }
1979
+ },
1980
+ required: ["tool"]
1981
+ }
1982
+ },
1983
+ {
1984
+ name: "exportMCPConfig",
1985
+ description: "Generate MCP configuration file for AI tools.",
1986
+ inputSchema: {
1987
+ type: "object",
1988
+ properties: {
1989
+ tool: {
1990
+ type: "string",
1991
+ enum: ["cursor", "claude-desktop", "windsurf", "continue", "vscode", "all"],
1992
+ description: "AI tool to generate MCP config for."
1993
+ }
1994
+ },
1995
+ required: ["tool"]
1996
+ }
1997
+ },
1998
+ {
1999
+ name: "getSetupInstructions",
2000
+ description: "Get detailed setup instructions for a specific AI tool.",
2001
+ inputSchema: {
2002
+ type: "object",
2003
+ properties: {
2004
+ tool: {
2005
+ type: "string",
2006
+ enum: ["cursor", "copilot", "windsurf", "cline", "continue", "zed", "claude-desktop", "generic"],
2007
+ description: "AI tool to get setup instructions for."
2008
+ }
2009
+ },
2010
+ required: ["tool"]
2011
+ }
2012
+ },
2013
+ {
2014
+ name: "syncAll",
2015
+ description: "Sync tokens, AI rules, skills files (SKILL.md, design-in-figma.md), and atomix-dependencies.json. One tool for full project sync. Use /--sync prompt or call when the user wants to sync. Optional: output (default ./tokens.css), format (default css), skipTokens (if true, only writes skills and manifest).",
2016
+ inputSchema: {
2017
+ type: "object",
2018
+ properties: {
2019
+ output: {
2020
+ type: "string",
2021
+ description: "Token file path (e.g. ./tokens.css). Default: ./tokens.css. Ignored if skipTokens is true."
1468
2022
  },
1469
- required: ["tool"]
1470
- }
1471
- },
1472
- {
1473
- name: "syncTokens",
1474
- description: "Sync design tokens to a local file. Safe, never breaks UI - adds new tokens, updates existing values, marks deprecated tokens. Use /refactor to migrate deprecated tokens. WARNING: The output file is completely rewritten - only CSS custom properties (variables) are preserved. Custom CSS rules will be lost. Keep custom CSS in a separate file.",
1475
- inputSchema: {
1476
- type: "object",
1477
- properties: {
1478
- output: {
1479
- type: "string",
1480
- description: "Output file path relative to project root (e.g., './src/tokens.css', './DesignTokens.swift')"
1481
- },
1482
- format: {
1483
- type: "string",
1484
- enum: ["css", "scss", "less", "json", "ts", "js", "swift", "kotlin", "dart"],
1485
- description: "Output format. WEB: css, scss, less, json, ts, js. NATIVE: swift (iOS), kotlin (Android), dart (Flutter). Default: css"
1486
- }
2023
+ format: {
2024
+ type: "string",
2025
+ enum: ["css", "scss", "less", "json", "ts", "js", "swift", "kotlin", "dart"],
2026
+ description: "Token output format. Default: css. Ignored if skipTokens is true."
1487
2027
  },
1488
- required: ["output"]
1489
- }
1490
- },
1491
- {
1492
- name: "getDependencies",
1493
- description: "Get suggested dependencies for this design system (icon package, fonts, SKILL.md, token files). Use with /--getstarted prompt. Optional platform and stack for tailored suggestions.",
1494
- inputSchema: {
1495
- type: "object",
1496
- properties: {
1497
- platform: {
1498
- type: "string",
1499
- enum: ["web", "ios", "android"],
1500
- description: "Target platform (web, ios, android). Optional."
1501
- },
1502
- stack: {
1503
- type: "string",
1504
- description: "Stack or framework (e.g. react, vue, next, swift, kotlin). Optional."
1505
- }
2028
+ skipTokens: {
2029
+ type: "boolean",
2030
+ description: "If true, skip token file and rules sync; only write skills and dependencies manifest. Default: false."
2031
+ }
2032
+ },
2033
+ required: []
2034
+ }
2035
+ },
2036
+ {
2037
+ name: "getDependencies",
2038
+ description: "Get suggested dependencies for this design system (icon package, fonts, SKILL.md, token files). Use with /--get-started prompt. Optional platform and stack for tailored suggestions.",
2039
+ inputSchema: {
2040
+ type: "object",
2041
+ properties: {
2042
+ platform: {
2043
+ type: "string",
2044
+ enum: ["web", "ios", "android"],
2045
+ description: "Target platform (web, ios, android). Optional."
1506
2046
  },
1507
- required: []
2047
+ stack: {
2048
+ type: "string",
2049
+ description: "Stack or framework (e.g. react, vue, next, swift, kotlin). Optional."
2050
+ }
2051
+ },
2052
+ required: []
2053
+ }
2054
+ },
2055
+ {
2056
+ name: "syncToFigma",
2057
+ description: "Push the owner's design system to Figma: creates color variable collection (Light/Dark), color and paint styles, number variables (spacing, radius, borders, sizing, breakpoints), text styles, and shadow effect styles. Uses local WebSocket bridge and Atomix Figma plugin (no Figma REST API). No arguments. If the bridge is not running, the response includes agentInstruction to start it; only if that fails should the user start the bridge and connect the plugin. Call this when the user asks to 'sync to Figma' or 'push DS to Figma'.",
2058
+ inputSchema: {
2059
+ type: "object",
2060
+ properties: {},
2061
+ required: []
2062
+ }
2063
+ },
2064
+ {
2065
+ name: "getFigmaVariablesAndStyles",
2066
+ description: "Get all local variable collections (with variable names and ids) and local paint, text, and effect styles from the open Figma file. Call after syncToFigma when designing in Figma; use with resolveFigmaIdsForTokens to get ids for granular design commands. Requires Atomix Figma plugin connected.",
2067
+ inputSchema: {
2068
+ type: "object",
2069
+ properties: {},
2070
+ required: []
2071
+ }
2072
+ },
2073
+ {
2074
+ name: "createDesignPlaceholder",
2075
+ description: "Create a placeholder frame in Figma with name 'Atomix: Preparing the design..', temporary background, and 'Design in progress...' text. Call this first when designing in Figma so the user sees the placeholder. Returns frameId; use that as parentId for designCreateFrame and other design commands. Optional width and height (default 400); use dimensions inferred from the request (e.g. mobile 390x844, card 400x300).",
2076
+ inputSchema: {
2077
+ type: "object",
2078
+ properties: {
2079
+ width: { type: "number", description: "Frame width in px (optional, default 400)" },
2080
+ height: { type: "number", description: "Frame height in px (optional, default 400)" }
1508
2081
  }
1509
2082
  }
1510
- ]
1511
- };
2083
+ },
2084
+ {
2085
+ name: "resolveFigmaIdsForTokens",
2086
+ description: "Resolve design system token names to Figma variable and style ids in the open file. Call after syncToFigma and getFigmaVariablesAndStyles. Returns a map keyed by Figma name (e.g. 'Spacing / lg', 'Background / surface') to { variableId?, paintStyleId?, textStyleId?, effectStyleId? }. Use these ids in designCreateFrame, designCreateText, designSetAutoLayout, etc. No arguments.",
2087
+ inputSchema: {
2088
+ type: "object",
2089
+ properties: {},
2090
+ required: []
2091
+ }
2092
+ },
2093
+ {
2094
+ name: "designCreateFrame",
2095
+ description: "Create a frame in Figma under the given parent. Use fillVariableId or fillPaintStyleId from resolveFigmaIdsForTokens for background. Returns nodeId.",
2096
+ inputSchema: {
2097
+ type: "object",
2098
+ properties: {
2099
+ parentId: { type: "string", description: "Parent frame/node id (e.g. from createDesignPlaceholder)" },
2100
+ name: { type: "string", description: "Layer name" },
2101
+ width: { type: "number", description: "Width in px (optional)" },
2102
+ height: { type: "number", description: "Height in px (optional)" },
2103
+ fillVariableId: { type: "string", description: "Color variable id from resolveFigmaIdsForTokens" },
2104
+ fillPaintStyleId: { type: "string", description: "Paint style id from resolveFigmaIdsForTokens" }
2105
+ },
2106
+ required: ["parentId", "name"]
2107
+ }
2108
+ },
2109
+ {
2110
+ name: "designCreateText",
2111
+ description: "Create a text node in Figma. Bind to a text style via textStyleId from resolveFigmaIdsForTokens.",
2112
+ inputSchema: {
2113
+ type: "object",
2114
+ properties: {
2115
+ parentId: { type: "string", description: "Parent frame id" },
2116
+ characters: { type: "string", description: "Text content" },
2117
+ textStyleId: { type: "string", description: "Text style id from resolveFigmaIdsForTokens (required)" },
2118
+ name: { type: "string", description: "Layer name (optional)" }
2119
+ },
2120
+ required: ["parentId", "characters", "textStyleId"]
2121
+ }
2122
+ },
2123
+ {
2124
+ name: "designCreateRectangle",
2125
+ description: "Create a rectangle in Figma. Use fillVariableId or fillPaintStyleId from resolveFigmaIdsForTokens.",
2126
+ inputSchema: {
2127
+ type: "object",
2128
+ properties: {
2129
+ parentId: { type: "string", description: "Parent frame id" },
2130
+ width: { type: "number", description: "Width in px" },
2131
+ height: { type: "number", description: "Height in px" },
2132
+ fillVariableId: { type: "string", description: "Color variable id" },
2133
+ fillPaintStyleId: { type: "string", description: "Paint style id" },
2134
+ name: { type: "string", description: "Layer name (optional)" }
2135
+ },
2136
+ required: ["parentId", "width", "height"]
2137
+ }
2138
+ },
2139
+ {
2140
+ name: "designSetAutoLayout",
2141
+ description: "Set auto-layout on a frame. Use variable ids from resolveFigmaIdsForTokens for padding and itemSpacing (e.g. Spacing / lg).",
2142
+ inputSchema: {
2143
+ type: "object",
2144
+ properties: {
2145
+ nodeId: { type: "string", description: "Frame node id" },
2146
+ direction: { type: "string", description: "HORIZONTAL or VERTICAL" },
2147
+ paddingVariableId: { type: "string", description: "Number variable id for all padding" },
2148
+ paddingTopVariableId: { type: "string" },
2149
+ paddingRightVariableId: { type: "string" },
2150
+ paddingBottomVariableId: { type: "string" },
2151
+ paddingLeftVariableId: { type: "string" },
2152
+ itemSpacingVariableId: { type: "string", description: "Number variable id for gap between children" },
2153
+ primaryAxisAlignItems: { type: "string", description: "MIN, CENTER, MAX, SPACE_BETWEEN" },
2154
+ counterAxisAlignItems: { type: "string", description: "MIN, CENTER, MAX, BASELINE" },
2155
+ layoutSizingHorizontal: { type: "string", description: "HUG or FILL" },
2156
+ layoutSizingVertical: { type: "string", description: "HUG or FILL" }
2157
+ },
2158
+ required: ["nodeId", "direction"]
2159
+ }
2160
+ },
2161
+ {
2162
+ name: "designSetLayoutConstraints",
2163
+ description: "Set min/max width and height on a frame (e.g. breakpoint variables). Use number variable ids from resolveFigmaIdsForTokens.",
2164
+ inputSchema: {
2165
+ type: "object",
2166
+ properties: {
2167
+ nodeId: { type: "string", description: "Frame node id" },
2168
+ minWidthVariableId: { type: "string" },
2169
+ maxWidthVariableId: { type: "string" },
2170
+ minHeightVariableId: { type: "string" },
2171
+ maxHeightVariableId: { type: "string" }
2172
+ },
2173
+ required: ["nodeId"]
2174
+ }
2175
+ },
2176
+ {
2177
+ name: "designAppendChild",
2178
+ description: "Move a node under a new parent (reparent). Use to reorder or nest nodes.",
2179
+ inputSchema: {
2180
+ type: "object",
2181
+ properties: {
2182
+ parentId: { type: "string", description: "New parent frame id" },
2183
+ childId: { type: "string", description: "Node id to move" }
2184
+ },
2185
+ required: ["parentId", "childId"]
2186
+ }
2187
+ },
2188
+ {
2189
+ name: "getDesignScreenshot",
2190
+ description: "Export a frame as PNG and return it as base64 so you can verify layout, content fill, and hug. Call after each design pass to check your work against the user's intent. Use the returned image to decide if another pass is needed.",
2191
+ inputSchema: {
2192
+ type: "object",
2193
+ properties: {
2194
+ frameId: { type: "string", description: "Frame node id (e.g. from createDesignPlaceholder)" },
2195
+ scale: { type: "number", description: "Export scale 1\u20134 (optional, default 1)" }
2196
+ },
2197
+ required: ["frameId"]
2198
+ }
2199
+ },
2200
+ {
2201
+ name: "finalizeDesignFrame",
2202
+ description: "Rename the design frame and remove the placeholder background. Call after the final design pass. Set name to a short description of the design plus ' \u2705'. Use fillVariableId or fillPaintStyleId from resolveFigmaIdsForTokens (e.g. Background / surface) so the gray placeholder is replaced.",
2203
+ inputSchema: {
2204
+ type: "object",
2205
+ properties: {
2206
+ frameId: { type: "string", description: "Frame node id to finalize" },
2207
+ name: { type: "string", description: "New frame name (e.g. 'Login card \u2705')" },
2208
+ fillVariableId: { type: "string", description: "Variable id for frame fill (removes placeholder bg)" },
2209
+ fillPaintStyleId: { type: "string", description: "Paint style id for frame fill" }
2210
+ },
2211
+ required: ["frameId", "name"]
2212
+ }
2213
+ }
2214
+ ];
2215
+ const tools = cachedMcpTier === "pro" ? toolsList : toolsList.filter((t) => !FIGMA_TOOL_NAMES.has(t.name));
2216
+ return { tools };
1512
2217
  });
1513
2218
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
1514
2219
  const { name, arguments: args } = request.params;
2220
+ if (!hasValidAuthConfig() || authFailedNoTools) {
2221
+ return {
2222
+ content: [{
2223
+ type: "text",
2224
+ text: "MCP access requires valid --ds-id and --atomix-token. Add both to your MCP config and restart Cursor. No tools are available until then."
2225
+ }],
2226
+ isError: true
2227
+ };
2228
+ }
1515
2229
  try {
1516
- const shouldForceRefresh = name === "syncTokens";
2230
+ const shouldForceRefresh = name === "syncAll";
1517
2231
  const data = await fetchDesignSystemForMCP(shouldForceRefresh);
2232
+ if (FIGMA_TOOL_NAMES.has(name) && cachedMcpTier !== "pro") {
2233
+ return {
2234
+ content: [
2235
+ {
2236
+ type: "text",
2237
+ text: "This design system does not have Pro Figma access. Figma sync and design tools are available when the design system owner has a Pro subscription."
2238
+ }
2239
+ ],
2240
+ isError: true
2241
+ };
2242
+ }
2243
+ async function performTokenSyncAndRules(designSystemData, tokenOutput, tokenFormat) {
2244
+ const output = tokenOutput;
2245
+ const format = tokenFormat;
2246
+ const outputPath = path2.resolve(process.cwd(), output);
2247
+ const fileExists = fs2.existsSync(outputPath);
2248
+ const deprecatedTokens = /* @__PURE__ */ new Map();
2249
+ const existingTokens = /* @__PURE__ */ new Map();
2250
+ if (fileExists && ["css", "scss", "less"].includes(format)) {
2251
+ const oldContent = fs2.readFileSync(outputPath, "utf-8");
2252
+ const oldVarPattern = /(?:^|\n)\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*)?(--[a-zA-Z0-9-]+):\s*([^;]+);/gm;
2253
+ let match;
2254
+ while ((match = oldVarPattern.exec(oldContent)) !== null) {
2255
+ const varName = match[1];
2256
+ const varValue = match[2].trim();
2257
+ existingTokens.set(varName, varValue);
2258
+ if (!(varName in designSystemData.cssVariables)) deprecatedTokens.set(varName, varValue);
2259
+ }
2260
+ }
2261
+ const mergedCssVariables = { ...designSystemData.cssVariables };
2262
+ const darkModeColors = designSystemData.tokens?.colors?.modes;
2263
+ let newContent;
2264
+ switch (format) {
2265
+ case "css":
2266
+ newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2267
+ break;
2268
+ case "scss":
2269
+ newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2270
+ break;
2271
+ case "less":
2272
+ newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2273
+ break;
2274
+ case "json":
2275
+ newContent = generateJSONOutput(designSystemData.tokens);
2276
+ break;
2277
+ case "js":
2278
+ newContent = generateJSOutput(designSystemData.tokens);
2279
+ break;
2280
+ case "ts":
2281
+ newContent = generateTSOutput(designSystemData.tokens);
2282
+ break;
2283
+ case "swift":
2284
+ newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2285
+ break;
2286
+ case "kotlin":
2287
+ newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2288
+ break;
2289
+ case "dart":
2290
+ newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2291
+ break;
2292
+ default:
2293
+ newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
2294
+ }
2295
+ const tokenCount = Object.keys(mergedCssVariables).length;
2296
+ const dsTokenCount = Object.keys(designSystemData.cssVariables).length;
2297
+ const deprecatedCount = deprecatedTokens.size;
2298
+ let changes = [];
2299
+ let diff;
2300
+ if (fileExists && ["css", "scss", "less"].includes(format)) {
2301
+ const oldContent = fs2.readFileSync(outputPath, "utf-8");
2302
+ diff = diffTokens(oldContent, mergedCssVariables, format, darkModeColors?.dark);
2303
+ const lightChanges = diff.added.length + diff.modified.length;
2304
+ const darkChanges = diff.addedDark.length + diff.modifiedDark.length;
2305
+ const totalChanges = lightChanges + darkChanges + deprecatedCount;
2306
+ if (totalChanges === 0) {
2307
+ const lastUpdated = designSystemData.meta.exportedAt ? new Date(designSystemData.meta.exportedAt).toLocaleString() : "N/A";
2308
+ return {
2309
+ responseText: `\u2713 Already up to date!
2310
+
2311
+ File: ${output}
2312
+ Tokens: ${tokenCount}
2313
+ Version: ${designSystemData.meta.version}
2314
+ Last updated: ${lastUpdated}`,
2315
+ rulesResults: []
2316
+ };
2317
+ }
2318
+ changes = [...diff.modified, ...diff.modifiedDark];
2319
+ const removedTokensWithValues = [];
2320
+ for (const [token, value] of deprecatedTokens.entries()) removedTokensWithValues.push({ token, lastValue: value });
2321
+ lastSyncAffectedTokens = {
2322
+ modified: [...diff.modified, ...diff.modifiedDark].map((m) => ({ token: m.key, oldValue: m.old, newValue: m.new })),
2323
+ removed: removedTokensWithValues,
2324
+ added: [...diff.added, ...diff.addedDark],
2325
+ format,
2326
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2327
+ };
2328
+ }
2329
+ const outputDir = path2.dirname(outputPath);
2330
+ if (!fs2.existsSync(outputDir)) fs2.mkdirSync(outputDir, { recursive: true });
2331
+ fs2.writeFileSync(outputPath, newContent);
2332
+ let rulesResults = [];
2333
+ try {
2334
+ rulesResults = await syncRulesFiles({
2335
+ dsId,
2336
+ apiKey: apiKey ?? void 0,
2337
+ apiBase: apiBase ?? void 0,
2338
+ rulesDir: process.cwd()
2339
+ });
2340
+ } catch (error) {
2341
+ console.error(`[syncAll] Failed to sync rules: ${error}`);
2342
+ }
2343
+ const governanceChanges = cachedData ? detectGovernanceChangesByFoundation(cachedData, designSystemData) : [];
2344
+ const response = formatSyncResponse({
2345
+ data: designSystemData,
2346
+ output,
2347
+ format,
2348
+ dsTokenCount,
2349
+ deprecatedCount,
2350
+ deprecatedTokens,
2351
+ diff,
2352
+ changes,
2353
+ fileExists,
2354
+ rulesResults,
2355
+ governanceChanges,
2356
+ changeSummary: getLastChangeSummary(),
2357
+ hasRefactorRecommendation: !!lastSyncAffectedTokens?.removed.length,
2358
+ deprecatedTokenCount: lastSyncAffectedTokens?.removed.length || 0
2359
+ });
2360
+ return { responseText: response, rulesResults };
2361
+ }
1518
2362
  switch (name) {
1519
2363
  case "getToken": {
1520
2364
  const path4 = args?.path;
@@ -1688,7 +2532,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1688
2532
  const serverName = data.meta.name.toLowerCase().replace(/[^a-z0-9]/g, "-");
1689
2533
  const npxArgs = ["@atomixstudio/mcp@latest"];
1690
2534
  if (dsId) npxArgs.push("--ds-id", dsId);
1691
- if (apiKey) npxArgs.push("--api-key", apiKey);
2535
+ if (accessToken) npxArgs.push("--atomix-token", accessToken);
1692
2536
  const config = {
1693
2537
  mcpServers: {
1694
2538
  [serverName]: {
@@ -1879,157 +2723,78 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1879
2723
  }]
1880
2724
  };
1881
2725
  }
1882
- case "syncTokens": {
1883
- const output = args?.output;
2726
+ case "syncAll": {
2727
+ const skipTokens = args?.skipTokens === true;
2728
+ const output = args?.output || "./tokens.css";
1884
2729
  const format = args?.format || "css";
1885
- if (!output) {
1886
- return {
1887
- content: [{
1888
- type: "text",
1889
- text: JSON.stringify({ error: "Missing required parameter: output" }, null, 2)
1890
- }]
1891
- };
1892
- }
1893
- const outputPath = path2.resolve(process.cwd(), output);
1894
- const fileExists = fs2.existsSync(outputPath);
1895
- const deprecatedTokens = /* @__PURE__ */ new Map();
1896
- const existingTokens = /* @__PURE__ */ new Map();
1897
- if (fileExists && ["css", "scss", "less"].includes(format)) {
1898
- const oldContent = fs2.readFileSync(outputPath, "utf-8");
1899
- const oldVarPattern = /(?:^|\n)\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*)?(--[a-zA-Z0-9-]+):\s*([^;]+);/gm;
1900
- let match;
1901
- while ((match = oldVarPattern.exec(oldContent)) !== null) {
1902
- const varName = match[1];
1903
- const varValue = match[2].trim();
1904
- existingTokens.set(varName, varValue);
1905
- if (!(varName in data.cssVariables)) {
1906
- deprecatedTokens.set(varName, varValue);
1907
- }
2730
+ const parts = ["\u2713 syncAll complete."];
2731
+ let tokenResponseText = "";
2732
+ if (!skipTokens) {
2733
+ const { responseText, rulesResults } = await performTokenSyncAndRules(data, output, format);
2734
+ tokenResponseText = responseText;
2735
+ parts.push(`Tokens: ${output} (${format})`);
2736
+ if (rulesResults.length > 0) {
2737
+ parts.push(`Rules: ${rulesResults.map((r) => r.path).join(", ")}`);
1908
2738
  }
1909
2739
  }
1910
- const mergedCssVariables = { ...data.cssVariables };
1911
- const darkModeColors = data.tokens?.colors?.modes;
1912
- let newContent;
1913
- switch (format) {
1914
- case "css":
1915
- newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1916
- break;
1917
- case "scss":
1918
- newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1919
- break;
1920
- case "less":
1921
- newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1922
- break;
1923
- case "json":
1924
- newContent = generateJSONOutput(data.tokens);
1925
- break;
1926
- case "js":
1927
- newContent = generateJSOutput(data.tokens);
1928
- break;
1929
- case "ts":
1930
- newContent = generateTSOutput(data.tokens);
1931
- break;
1932
- case "swift":
1933
- newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1934
- break;
1935
- case "kotlin":
1936
- newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1937
- break;
1938
- case "dart":
1939
- newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1940
- break;
1941
- default:
1942
- newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);
1943
- }
1944
- const tokenCount = Object.keys(mergedCssVariables).length;
1945
- const dsTokenCount = Object.keys(data.cssVariables).length;
1946
- const deprecatedCount = deprecatedTokens.size;
1947
- let diffSummary = "";
1948
- let changes = [];
1949
- let diff;
1950
- if (fileExists && ["css", "scss", "less"].includes(format)) {
1951
- const oldContent = fs2.readFileSync(outputPath, "utf-8");
1952
- diff = diffTokens(oldContent, mergedCssVariables, format, darkModeColors?.dark);
1953
- const lightChanges = diff.added.length + diff.modified.length;
1954
- const darkChanges = diff.addedDark.length + diff.modifiedDark.length;
1955
- const totalChanges = lightChanges + darkChanges + deprecatedCount;
1956
- if (totalChanges === 0) {
1957
- const lastUpdated = data.meta.exportedAt ? new Date(data.meta.exportedAt).toLocaleString() : "N/A";
1958
- return {
1959
- content: [{
1960
- type: "text",
1961
- text: `\u2713 Already up to date!
1962
-
1963
- File: ${output}
1964
- Tokens: ${tokenCount}
1965
- Version: ${data.meta.version}
1966
- Last updated: ${lastUpdated}`
1967
- }]
1968
- };
1969
- }
1970
- changes = [...diff.modified, ...diff.modifiedDark];
1971
- const lightSummary = lightChanges > 0 ? `Light: ${diff.modified.length} modified, ${diff.added.length} added` : "";
1972
- const darkSummary = darkChanges > 0 ? `Dark: ${diff.modifiedDark.length} modified, ${diff.addedDark.length} added` : "";
1973
- const deprecatedSummary = deprecatedCount > 0 ? `${deprecatedCount} deprecated (use /refactor)` : "";
1974
- diffSummary = [lightSummary, darkSummary, deprecatedSummary].filter(Boolean).join(" | ");
1975
- const removedTokensWithValues = [];
1976
- for (const [token, value] of deprecatedTokens.entries()) {
1977
- removedTokensWithValues.push({ token, lastValue: value });
2740
+ const skillsDir = path2.resolve(process.cwd(), ".cursor/skills/atomix-ds");
2741
+ if (!fs2.existsSync(skillsDir)) fs2.mkdirSync(skillsDir, { recursive: true });
2742
+ const dsVersion = String(data.meta.version ?? "1.0.0");
2743
+ const dsExportedAt = data.meta.exportedAt;
2744
+ const genericWithVersion = injectSkillVersion(GENERIC_SKILL_MD, dsVersion, dsExportedAt);
2745
+ const figmaWithVersion = injectSkillVersion(FIGMA_DESIGN_SKILL_MD, dsVersion, dsExportedAt);
2746
+ fs2.writeFileSync(path2.join(skillsDir, "SKILL.md"), genericWithVersion);
2747
+ fs2.writeFileSync(path2.join(skillsDir, "design-in-figma.md"), figmaWithVersion);
2748
+ parts.push("Skills: .cursor/skills/atomix-ds/SKILL.md, .cursor/skills/atomix-ds/design-in-figma.md (synced at DS v" + dsVersion + ")");
2749
+ const tokens = data.tokens;
2750
+ const typography = tokens?.typography;
2751
+ const fontFamily = typography?.fontFamily;
2752
+ const fontNames = [];
2753
+ if (fontFamily) {
2754
+ for (const key of ["display", "heading", "body"]) {
2755
+ const v = fontFamily[key];
2756
+ if (typeof v === "string" && v && !fontNames.includes(v)) fontNames.push(v);
1978
2757
  }
1979
- lastSyncAffectedTokens = {
1980
- modified: [...diff.modified, ...diff.modifiedDark].map((m) => ({
1981
- token: m.key,
1982
- oldValue: m.old,
1983
- newValue: m.new
1984
- })),
1985
- removed: removedTokensWithValues,
1986
- added: [...diff.added, ...diff.addedDark],
1987
- format,
1988
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1989
- };
1990
- }
1991
- const outputDir = path2.dirname(outputPath);
1992
- if (!fs2.existsSync(outputDir)) {
1993
- fs2.mkdirSync(outputDir, { recursive: true });
1994
2758
  }
1995
- fs2.writeFileSync(outputPath, newContent);
1996
- let rulesResults = [];
1997
- try {
1998
- rulesResults = await syncRulesFiles({
1999
- dsId,
2000
- apiKey: apiKey ?? void 0,
2001
- apiBase: apiBase ?? void 0,
2002
- rulesDir: process.cwd()
2003
- });
2004
- } catch (error) {
2005
- console.error(`[syncTokens] Failed to sync rules: ${error}`);
2006
- }
2007
- const governanceChanges = cachedData ? detectGovernanceChangesByFoundation(cachedData, data) : [];
2008
- const response = formatSyncResponse({
2009
- data,
2010
- output,
2011
- format,
2012
- dsTokenCount,
2013
- deprecatedCount,
2014
- deprecatedTokens,
2015
- diff,
2016
- changes,
2017
- fileExists,
2018
- rulesResults,
2019
- governanceChanges,
2020
- changeSummary: getLastChangeSummary(),
2021
- hasRefactorRecommendation: !!lastSyncAffectedTokens?.removed.length,
2022
- deprecatedTokenCount: lastSyncAffectedTokens?.removed.length || 0
2023
- });
2759
+ const icons = tokens?.icons;
2760
+ const ICON_PACKAGES = {
2761
+ lucide: { web: "lucide-react", native: "lucide-react-native" },
2762
+ heroicons: { web: "@heroicons/react", native: "heroicons-react-native" },
2763
+ phosphor: { web: "phosphor-react", native: "phosphor-react-native" }
2764
+ };
2765
+ const lib = icons?.library || "lucide";
2766
+ const iconPkgs = ICON_PACKAGES[lib] || ICON_PACKAGES.lucide;
2767
+ const manifest = {
2768
+ designSystem: { name: data.meta.name, version: data.meta.version },
2769
+ tokenFile: skipTokens ? void 0 : output,
2770
+ iconLibrary: {
2771
+ package: iconPkgs.web,
2772
+ nativePackage: iconPkgs.native,
2773
+ strokeWidthToken: icons?.strokeWidth != null ? "icons.strokeWidth" : void 0,
2774
+ strokeWidthValue: icons?.strokeWidth
2775
+ },
2776
+ fonts: { families: fontNames },
2777
+ skills: {
2778
+ skill: ".cursor/skills/atomix-ds/SKILL.md",
2779
+ skillFigmaDesign: ".cursor/skills/atomix-ds/design-in-figma.md",
2780
+ syncedAtVersion: data.meta.version ?? "1.0.0"
2781
+ }
2782
+ };
2783
+ const manifestPath = path2.resolve(process.cwd(), "atomix-dependencies.json");
2784
+ fs2.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
2785
+ parts.push("Manifest: atomix-dependencies.json (icons, fonts, skill paths)");
2786
+ const summary = parts.join("\n");
2787
+ const fullText = tokenResponseText ? `${summary}
2788
+
2789
+ ---
2790
+
2791
+ ${tokenResponseText}` : summary;
2024
2792
  return {
2025
- content: [{
2026
- type: "text",
2027
- text: response
2028
- }]
2793
+ content: [{ type: "text", text: fullText }]
2029
2794
  };
2030
2795
  }
2031
2796
  case "getDependencies": {
2032
- const platform = args?.platform;
2797
+ const platform2 = args?.platform;
2033
2798
  const stack = args?.stack;
2034
2799
  const tokens = data.tokens;
2035
2800
  const typography = tokens?.typography;
@@ -2065,16 +2830,26 @@ Last updated: ${lastUpdated}`
2065
2830
  path: ".cursor/skills/atomix-ds/SKILL.md",
2066
2831
  content: GENERIC_SKILL_MD
2067
2832
  },
2833
+ skillFigmaDesign: {
2834
+ path: ".cursor/skills/atomix-ds/design-in-figma.md",
2835
+ content: FIGMA_DESIGN_SKILL_MD
2836
+ },
2068
2837
  tokenFiles: {
2069
2838
  files: ["tokens.css", "tokens.json"],
2070
- copyInstructions: "Call the syncTokens MCP tool to create the token file; do not only suggest the user run sync later."
2839
+ copyInstructions: "Call the syncAll MCP tool to create the token file, skills, and atomix-dependencies.json; do not only suggest the user run sync later."
2071
2840
  },
2072
- showcase: platform === "web" || !platform ? {
2841
+ showcase: platform2 === "web" || !platform2 ? {
2073
2842
  path: "atomix-setup-showcase.html",
2074
2843
  template: SHOWCASE_HTML_TEMPLATE,
2075
- substitutionInstructions: "Replace placeholders with values from the synced token file. MCP/sync/export use the --atmx- prefix. {{TOKENS_CSS_PATH}} = path to the synced token file (e.g. ./tokens.css, same as syncTokens output). {{DS_NAME}} = design system name. {{BRAND_PRIMARY_VAR}} = var(--atmx-color-brand-primary). {{BRAND_PRIMARY_FOREGROUND_VAR}} = var(--atmx-color-brand-primary-foreground). {{HEADING_FONT_VAR}} = var(--atmx-typography-font-family-heading) or var(--atmx-typography-font-family-display). {{FONT_FAMILY_VAR}} = var(--atmx-typography-font-family-body). {{FONT_LINK_TAG}} = Google Fonts <link> for the font, or empty string. Do not invent CSS variable names; use only vars that exist in the export."
2844
+ substitutionInstructions: "Replace placeholders with values from the synced token file. MCP/sync/export use the --atmx- prefix. {{TOKENS_CSS_PATH}} = path to the synced token file (e.g. ./tokens.css, same as syncAll output). {{DS_NAME}} = design system name. {{BRAND_PRIMARY_VAR}} = var(--atmx-color-brand-primary). {{BRAND_PRIMARY_FOREGROUND_VAR}} = var(--atmx-color-brand-primary-foreground). {{HEADING_FONT_VAR}} = var(--atmx-typography-font-family-heading) or var(--atmx-typography-font-family-display). {{FONT_FAMILY_VAR}} = var(--atmx-typography-font-family-body). {{FONT_LINK_TAG}} = Google Fonts <link> for the font, or empty string. Do not invent CSS variable names; use only vars that exist in the export."
2076
2845
  } : void 0,
2077
- meta: { dsName: data.meta.name, platform: platform ?? void 0, stack: stack ?? void 0 }
2846
+ meta: {
2847
+ dsName: data.meta.name,
2848
+ platform: platform2 ?? void 0,
2849
+ stack: stack ?? void 0,
2850
+ designSystemVersion: data.meta.version ?? "1.0.0",
2851
+ designSystemExportedAt: data.meta.exportedAt
2852
+ }
2078
2853
  };
2079
2854
  return {
2080
2855
  content: [{
@@ -2083,13 +2858,363 @@ Last updated: ${lastUpdated}`
2083
2858
  }]
2084
2859
  };
2085
2860
  }
2861
+ case "syncToFigma": {
2862
+ const payloads = buildFigmaPayloadsFromDS(data);
2863
+ const out = {};
2864
+ const agentStartBridge = `The Figma bridge runs with this MCP server. Ensure Cursor has this MCP configured and running, then in Figma run the Atomix plugin and click Connect to Cursor. Then call **syncToFigma** again.`;
2865
+ const userSteps = [
2866
+ FIGMA_CONNECTION_INSTRUCTIONS.startBridge,
2867
+ FIGMA_CONNECTION_INSTRUCTIONS.installAndRun,
2868
+ FIGMA_CONNECTION_INSTRUCTIONS.connect,
2869
+ "Then run Sync to Figma again."
2870
+ ].join(" ");
2871
+ try {
2872
+ const reachable = await isBridgeReachable();
2873
+ if (!reachable) {
2874
+ out.bridgeNotRunning = true;
2875
+ out.agentInstruction = agentStartBridge;
2876
+ out.userInstruction = `If the bridge still does not connect: ${userSteps}`;
2877
+ out.figmaPayload = {
2878
+ collectionName: payloads.colorVariables.collectionName,
2879
+ modes: payloads.colorVariables.modes,
2880
+ variables: payloads.colorVariables.variables,
2881
+ paintStyles: payloads.paintStyles,
2882
+ textStyles: payloads.textStyles,
2883
+ numberVariables: payloads.numberVariables,
2884
+ effectStyles: payloads.effectStyles
2885
+ };
2886
+ return {
2887
+ content: [{ type: "text", text: JSON.stringify(out, null, 2) }]
2888
+ };
2889
+ }
2890
+ if (payloads.colorVariables.variables.length > 0) {
2891
+ out.colorVariables = await sendBridgeRequest("create_color_variables", {
2892
+ collectionName: payloads.colorVariables.collectionName,
2893
+ modes: payloads.colorVariables.modes,
2894
+ variables: payloads.colorVariables.variables
2895
+ });
2896
+ }
2897
+ if (payloads.paintStyles.length > 0) {
2898
+ out.paintStyles = await sendBridgeRequest("create_paint_styles", { styles: payloads.paintStyles });
2899
+ }
2900
+ if (payloads.numberVariables.variables.length > 0) {
2901
+ try {
2902
+ out.numberVariables = await sendBridgeRequest("create_number_variables", {
2903
+ collectionName: payloads.numberVariables.collectionName,
2904
+ variables: payloads.numberVariables.variables
2905
+ });
2906
+ } catch (e) {
2907
+ const msg = e instanceof Error ? e.message : String(e);
2908
+ out.numberVariables = { error: msg };
2909
+ if (msg.includes("Method not allowed") && msg.includes("create_number_variables")) {
2910
+ out.numberVariablesHint = "Number variables require the latest Atomix Figma plugin and bridge. Rebuild the plugin and bridge, reload the plugin in Figma, restart the bridge, then sync again.";
2911
+ }
2912
+ }
2913
+ }
2914
+ if (payloads.textStyles.length > 0) {
2915
+ out.textStyles = await sendBridgeRequest("create_text_styles", { styles: payloads.textStyles });
2916
+ }
2917
+ if (payloads.effectStyles.length > 0) {
2918
+ out.effectStyles = await sendBridgeRequest("create_effect_styles", { styles: payloads.effectStyles });
2919
+ }
2920
+ out.figmaPayload = {
2921
+ collectionName: payloads.colorVariables.collectionName,
2922
+ modes: payloads.colorVariables.modes,
2923
+ variables: payloads.colorVariables.variables,
2924
+ paintStyles: payloads.paintStyles,
2925
+ textStyles: payloads.textStyles,
2926
+ numberVariables: payloads.numberVariables,
2927
+ effectStyles: payloads.effectStyles
2928
+ };
2929
+ } catch (e) {
2930
+ out.error = e instanceof Error ? e.message : String(e);
2931
+ out.figmaPayload = {
2932
+ collectionName: payloads.colorVariables.collectionName,
2933
+ modes: payloads.colorVariables.modes,
2934
+ variables: payloads.colorVariables.variables,
2935
+ paintStyles: payloads.paintStyles,
2936
+ textStyles: payloads.textStyles,
2937
+ numberVariables: payloads.numberVariables,
2938
+ effectStyles: payloads.effectStyles
2939
+ };
2940
+ const errMsg = out.error.toLowerCase();
2941
+ const connectionFailure = errMsg.includes("econnrefused") || errMsg.includes("bridge timeout") || errMsg.includes("websocket") || errMsg.includes("network");
2942
+ if (connectionFailure) {
2943
+ out.bridgeNotRunning = true;
2944
+ out.agentInstruction = agentStartBridge;
2945
+ out.userInstruction = `If the bridge still does not connect: ${userSteps}`;
2946
+ } else if (errMsg.includes("plugin not connected") || errMsg.includes("figma plugin")) {
2947
+ out.userInstruction = `${FIGMA_CONNECTION_INSTRUCTIONS.installAndRun} ${FIGMA_CONNECTION_INSTRUCTIONS.connect}`;
2948
+ }
2949
+ }
2950
+ const textStylesResult = out.textStyles;
2951
+ if (textStylesResult?.failed && textStylesResult.failures?.length) {
2952
+ const firstReason = textStylesResult.failures[0].reason;
2953
+ out.summary = `Text styles: ${textStylesResult.failed} could not be created. ${firstReason}`;
2954
+ }
2955
+ if (out.numberVariablesHint) {
2956
+ out.summary = [out.summary, out.numberVariablesHint].filter(Boolean).join(" ");
2957
+ }
2958
+ out.motionEasingNote = "Motion easing tokens are not synced as Figma styles; Figma has no reusable easing style. Easing is only used in prototype transitions (e.g. smart animate). Duration/easing remain available as number variables (duration) or in export JSON.";
2959
+ return {
2960
+ content: [{
2961
+ type: "text",
2962
+ text: JSON.stringify(out, null, 2)
2963
+ }],
2964
+ ...out.error ? { isError: true } : {}
2965
+ };
2966
+ }
2967
+ case "getFigmaVariablesAndStyles": {
2968
+ try {
2969
+ const reachable = await isBridgeReachable();
2970
+ if (!reachable) {
2971
+ return {
2972
+ content: [{
2973
+ type: "text",
2974
+ text: JSON.stringify({
2975
+ error: "Figma bridge not reachable.",
2976
+ bridgeNotRunning: true,
2977
+ agentInstruction: "The Figma bridge runs with this MCP server. Ensure Cursor has this MCP running, then in Figma run the Atomix plugin and click Connect to Cursor. Then call getFigmaVariablesAndStyles again."
2978
+ }, null, 2)
2979
+ }],
2980
+ isError: true
2981
+ };
2982
+ }
2983
+ const result = await sendBridgeRequest("get_figma_variables_and_styles");
2984
+ return {
2985
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2986
+ };
2987
+ } catch (e) {
2988
+ const message = e instanceof Error ? e.message : String(e);
2989
+ return {
2990
+ content: [{
2991
+ type: "text",
2992
+ text: JSON.stringify({ error: message, hint: "Ensure the bridge is running and the Atomix plugin is connected." }, null, 2)
2993
+ }],
2994
+ isError: true
2995
+ };
2996
+ }
2997
+ }
2998
+ case "createDesignPlaceholder": {
2999
+ try {
3000
+ const reachable = await isBridgeReachable();
3001
+ if (!reachable) {
3002
+ return {
3003
+ content: [{
3004
+ type: "text",
3005
+ text: JSON.stringify({
3006
+ error: "Figma bridge not reachable.",
3007
+ hint: "The bridge runs with this MCP server. Ensure Cursor has this MCP running, then run the Atomix plugin and click Connect to Cursor."
3008
+ }, null, 2)
3009
+ }],
3010
+ isError: true
3011
+ };
3012
+ }
3013
+ const w = args?.width;
3014
+ const h = args?.height;
3015
+ const placeholderParams = {};
3016
+ if (typeof w === "number" && w > 0) placeholderParams.width = Math.round(w);
3017
+ if (typeof h === "number" && h > 0) placeholderParams.height = Math.round(h);
3018
+ const result = await sendBridgeRequest("create_design_placeholder", placeholderParams);
3019
+ return {
3020
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
3021
+ };
3022
+ } catch (e) {
3023
+ const message = e instanceof Error ? e.message : String(e);
3024
+ return {
3025
+ content: [{
3026
+ type: "text",
3027
+ text: JSON.stringify({ error: message }, null, 2)
3028
+ }],
3029
+ isError: true
3030
+ };
3031
+ }
3032
+ }
3033
+ case "resolveFigmaIdsForTokens": {
3034
+ try {
3035
+ const reachable = await isBridgeReachable();
3036
+ if (!reachable) {
3037
+ return {
3038
+ content: [{
3039
+ type: "text",
3040
+ text: JSON.stringify({
3041
+ error: "Figma bridge not reachable.",
3042
+ hint: "Run syncToFigma first, then ensure the plugin is connected. Then call resolveFigmaIdsForTokens again."
3043
+ }, null, 2)
3044
+ }],
3045
+ isError: true
3046
+ };
3047
+ }
3048
+ const raw = await sendBridgeRequest("get_figma_variables_and_styles");
3049
+ const response = raw;
3050
+ const variableByName = /* @__PURE__ */ new Map();
3051
+ if (response.variableCollections) {
3052
+ for (const coll of response.variableCollections) {
3053
+ for (const v of coll.variables || []) {
3054
+ variableByName.set(v.name, v.id);
3055
+ }
3056
+ }
3057
+ }
3058
+ const paintByName = /* @__PURE__ */ new Map();
3059
+ for (const s of response.paintStyles || []) {
3060
+ paintByName.set(s.name, s.id);
3061
+ }
3062
+ const textByName = /* @__PURE__ */ new Map();
3063
+ for (const s of response.textStyles || []) {
3064
+ textByName.set(s.name, s.id);
3065
+ }
3066
+ const effectByName = /* @__PURE__ */ new Map();
3067
+ for (const s of response.effectStyles || []) {
3068
+ effectByName.set(s.name, s.id);
3069
+ }
3070
+ const expected = getExpectedFigmaNamesFromDS(data);
3071
+ const resolved = {};
3072
+ const allNames = /* @__PURE__ */ new Set([
3073
+ ...expected.colorVariableNames,
3074
+ ...expected.paintStyleNames,
3075
+ ...expected.textStyleNames,
3076
+ ...expected.effectStyleNames,
3077
+ ...expected.numberVariableNames
3078
+ ]);
3079
+ for (const name2 of allNames) {
3080
+ const entry = {};
3081
+ const vId = variableByName.get(name2);
3082
+ if (vId) entry.variableId = vId;
3083
+ const pId = paintByName.get(name2);
3084
+ if (pId) entry.paintStyleId = pId;
3085
+ const tId = textByName.get(name2);
3086
+ if (tId) entry.textStyleId = tId;
3087
+ const eId = effectByName.get(name2);
3088
+ if (eId) entry.effectStyleId = eId;
3089
+ if (vId || pId || tId || eId) resolved[name2] = entry;
3090
+ }
3091
+ return {
3092
+ content: [{ type: "text", text: JSON.stringify({ resolved }, null, 2) }]
3093
+ };
3094
+ } catch (e) {
3095
+ const message = e instanceof Error ? e.message : String(e);
3096
+ return {
3097
+ content: [{
3098
+ type: "text",
3099
+ text: JSON.stringify({ error: message }, null, 2)
3100
+ }],
3101
+ isError: true
3102
+ };
3103
+ }
3104
+ }
3105
+ case "getDesignScreenshot": {
3106
+ try {
3107
+ const reachable = await isBridgeReachable();
3108
+ if (!reachable) {
3109
+ return {
3110
+ content: [{
3111
+ type: "text",
3112
+ text: JSON.stringify({
3113
+ error: "Figma bridge not reachable.",
3114
+ hint: "Run the Atomix plugin in Figma and click Connect to Cursor, then retry."
3115
+ }, null, 2)
3116
+ }],
3117
+ isError: true
3118
+ };
3119
+ }
3120
+ const frameId = args?.frameId;
3121
+ const scale = args?.scale;
3122
+ const params = { frameId };
3123
+ if (typeof scale === "number" && scale >= 1 && scale <= 4) params.scale = scale;
3124
+ const result = await sendBridgeRequest("get_design_screenshot", params);
3125
+ if (result.error) {
3126
+ return {
3127
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
3128
+ isError: true
3129
+ };
3130
+ }
3131
+ const content = [
3132
+ { type: "text", text: `Screenshot captured (format: ${result.format ?? "PNG"}, scale: ${result.scale ?? 1}). Use the image below to verify layout, fill, and content hug.` }
3133
+ ];
3134
+ if (result.imageBase64) {
3135
+ content.push({ type: "image", data: result.imageBase64, mimeType: "image/png" });
3136
+ }
3137
+ return { content };
3138
+ } catch (e) {
3139
+ const message = e instanceof Error ? e.message : String(e);
3140
+ return {
3141
+ content: [{ type: "text", text: JSON.stringify({ error: message }, null, 2) }],
3142
+ isError: true
3143
+ };
3144
+ }
3145
+ }
3146
+ case "finalizeDesignFrame": {
3147
+ try {
3148
+ const reachable = await isBridgeReachable();
3149
+ if (!reachable) {
3150
+ return {
3151
+ content: [{
3152
+ type: "text",
3153
+ text: JSON.stringify({
3154
+ error: "Figma bridge not reachable.",
3155
+ hint: "Run the Atomix plugin in Figma and click Connect to Cursor, then retry."
3156
+ }, null, 2)
3157
+ }],
3158
+ isError: true
3159
+ };
3160
+ }
3161
+ const params = args && typeof args === "object" ? args : {};
3162
+ const result = await sendBridgeRequest("finalize_design_frame", params);
3163
+ return {
3164
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
3165
+ };
3166
+ } catch (e) {
3167
+ const message = e instanceof Error ? e.message : String(e);
3168
+ return {
3169
+ content: [{ type: "text", text: JSON.stringify({ error: message }, null, 2) }],
3170
+ isError: true
3171
+ };
3172
+ }
3173
+ }
3174
+ case "designCreateFrame":
3175
+ case "designCreateText":
3176
+ case "designCreateRectangle":
3177
+ case "designSetAutoLayout":
3178
+ case "designSetLayoutConstraints":
3179
+ case "designAppendChild": {
3180
+ try {
3181
+ const reachable = await isBridgeReachable();
3182
+ if (!reachable) {
3183
+ return {
3184
+ content: [{
3185
+ type: "text",
3186
+ text: JSON.stringify({
3187
+ error: "Figma bridge not reachable.",
3188
+ hint: "Run the Atomix plugin in Figma and click Connect to Cursor, then retry."
3189
+ }, null, 2)
3190
+ }],
3191
+ isError: true
3192
+ };
3193
+ }
3194
+ const method = normalizeBridgeMethod(name);
3195
+ const params = args && typeof args === "object" ? args : {};
3196
+ const result = await sendBridgeRequest(method, params);
3197
+ return {
3198
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
3199
+ };
3200
+ } catch (e) {
3201
+ const message = e instanceof Error ? e.message : String(e);
3202
+ return {
3203
+ content: [{
3204
+ type: "text",
3205
+ text: JSON.stringify({ error: message }, null, 2)
3206
+ }],
3207
+ isError: true
3208
+ };
3209
+ }
3210
+ }
2086
3211
  default:
2087
3212
  return {
2088
3213
  content: [{
2089
3214
  type: "text",
2090
3215
  text: JSON.stringify({
2091
3216
  error: `Unknown tool: ${name}`,
2092
- availableTools: ["getToken", "listTokens", "searchTokens", "validateUsage", "getAIToolRules", "exportMCPConfig", "getSetupInstructions", "syncTokens", "getDependencies"]
3217
+ availableTools: ["getToken", "listTokens", "searchTokens", "validateUsage", "getAIToolRules", "exportMCPConfig", "getSetupInstructions", "syncAll", "getDependencies", "syncToFigma", "getFigmaVariablesAndStyles", "createDesignPlaceholder", "resolveFigmaIdsForTokens", "designCreateFrame", "designCreateText", "designCreateRectangle", "designSetAutoLayout", "designSetLayoutConstraints", "designAppendChild", "getDesignScreenshot", "finalizeDesignFrame"]
2093
3218
  }, null, 2)
2094
3219
  }]
2095
3220
  };
@@ -2106,7 +3231,7 @@ Last updated: ${lastUpdated}`
2106
3231
  if (status === "404") {
2107
3232
  suggestion = `Design system ID "${dsId}" not found. Verify the ID is correct or the design system has been published.`;
2108
3233
  } else if (status === "401" || status === "403") {
2109
- suggestion = "Design system is private. Add --api-key <your-key> to your MCP server configuration.";
3234
+ suggestion = "Add --atomix-token <your-token> from the Export modal or Settings \u2192 Regenerate.";
2110
3235
  } else {
2111
3236
  suggestion = `API request failed (${status}). Check your network connection and API base URL (${apiBase}).`;
2112
3237
  }
@@ -2131,6 +3256,16 @@ Last updated: ${lastUpdated}`
2131
3256
  };
2132
3257
  }
2133
3258
  });
3259
+ function injectSkillVersion(content, version, exportedAt) {
3260
+ const endOfFrontmatter = content.indexOf("\n---\n", 3);
3261
+ if (endOfFrontmatter === -1) return content;
3262
+ const before = content.slice(0, endOfFrontmatter);
3263
+ const after = content.slice(endOfFrontmatter);
3264
+ const versionLines = `atomixDsVersion: "${version}"
3265
+ atomixDsExportedAt: "${exportedAt ?? ""}"
3266
+ `;
3267
+ return before + "\n" + versionLines + after;
3268
+ }
2134
3269
  var GENERIC_SKILL_MD = `---
2135
3270
  name: atomix-ds
2136
3271
  description: Use the Atomix design system for UI, tokens, and styles. Fetch rules and tokens via MCP tools; never hardcode design values.
@@ -2167,7 +3302,7 @@ Alternatively use the **/--rules** prompt or the resource \`atomix://rules/<tool
2167
3302
  - **validateUsage(value, context)** \u2014 Check if a CSS/value should use a token instead (e.g. \`validateUsage("#007061", "color")\`).
2168
3303
 
2169
3304
  **4. Syncing tokens to a file**
2170
- - **syncTokens({ output, format })** \u2014 Writes the current design system tokens to a file (e.g. \`./tokens.css\`). Use when the user wants a local token file.
3305
+ - **syncAll({ output?, format?, skipTokens? })** \u2014 Syncs tokens to a file, AI rules, skills (.cursor/skills/atomix-ds/*), and atomix-dependencies.json. Default output \`./tokens.css\`, format \`css\`. Use \`skipTokens: true\` to only write skills and manifest.
2171
3306
 
2172
3307
  Use the returned rules and token paths/values when generating or editing code. Prefer CSS variables (e.g. \`var(--atmx-*)\`) or the exact token references from the tools.
2173
3308
 
@@ -2177,6 +3312,50 @@ Use the returned rules and token paths/values when generating or editing code. P
2177
3312
  - **Icons:** Apply the design system's icon tokens when rendering icons: sizing via \`getToken("sizing.icon.sm")\` or \`listTokens("sizing")\`, and stroke width via \`getToken("icons.strokeWidth")\` when the DS defines it; do not use hardcoded sizes or stroke widths.
2178
3313
  - **Typography:** Use typography tokens (fontFamily, fontSize, fontWeight, lineHeight, letterSpacing) from the DS for any text; build typesets (Display, Heading, body) from those tokens when creating global styles.
2179
3314
  - **No guessing:** If a value is not in the rules or token list, use searchTokens or listTokens to find the closest match rather than inventing a value.
3315
+ - **Version check:** If this skill file has frontmatter \`atomixDsVersion\`, compare it to the design system version from **getDependencies** (\`meta.designSystemVersion\`). If the design system is newer, suggest the user run **syncAll** to update skills and tokens.
3316
+ `;
3317
+ var FIGMA_DESIGN_SKILL_MD = `---
3318
+ name: atomix-design-in-figma
3319
+ description: Design in Figma using granular MCP commands. Three passes: wireframe, then tokens/rules, then audit. Use getDesignScreenshot to verify; finalizeDesignFrame to rename and remove placeholder.
3320
+ ---
3321
+
3322
+ # Design in Figma (principal product designer)
3323
+
3324
+ Use this skill when the user asks to **design in Figma** (e.g. /--design-in-figma). Design by calling a **sequence of MCP tools**\u2014no script generation. All values come from the owner's Figma variables and styles (via **syncToFigma** and **resolveFigmaIdsForTokens**).
3325
+
3326
+ ## Mandatory: no hardcoding
3327
+
3328
+ - **Only variable and style ids.** Use **resolveFigmaIdsForTokens** to get \`variableId\`, \`paintStyleId\`, \`textStyleId\`, \`effectStyleId\` keyed by Figma name (e.g. "Spacing / lg", "Background / surface"). Pass these ids into designCreateFrame, designCreateText, designSetAutoLayout, designSetLayoutConstraints. Never pass raw px, hex, or font sizes.
3329
+
3330
+ ## Mandatory: user AI rules (colors, typography, buttons)
3331
+
3332
+ - **Colors:** Only variable/paint style ids from resolveFigmaIdsForTokens and getAIToolRules; no hex or raw values.
3333
+ - **Typography:** Only text style ids from resolved + rules; no raw font size/weight/family.
3334
+ - **Buttons:** Use token-based sizing and hierarchy from getAIToolRules; primary/secondary/ghost from resolved styles.
3335
+
3336
+ ## Mandatory: set up variables first
3337
+
3338
+ - **Call syncToFigma first.** Then getAIToolRules, listTokens, and resolveFigmaIdsForTokens. Use the \`resolved\` map for every fill, text style, and spacing.
3339
+
3340
+ ## Mandatory: auto-layout and breakpoints
3341
+
3342
+ - **Every frame with children:** Call **designSetAutoLayout** with \`nodeId\`, \`direction\`, \`paddingVariableId\`, \`itemSpacingVariableId\` from resolved. Use \`layoutSizingHorizontal\` / \`layoutSizingVertical\` (HUG or FILL) so content hugs or fills as intended.
3343
+ - **Breakpoints (non-mobile):** Use **designSetLayoutConstraints** with \`maxWidthVariableId\` from resolved for container frames.
3344
+
3345
+ ## Three-pass flow (strict order)
3346
+
3347
+ **Setup (once):** syncToFigma \u2192 createDesignPlaceholder (save \`frameId\`) \u2192 getAIToolRules + listTokens \u2192 resolveFigmaIdsForTokens. Keep \`resolved\` and \`frameId\` for all passes.
3348
+
3349
+ **Pass 1 \u2014 Layout and contents (wireframe)**
3350
+ Build structure only: frames, text nodes, rectangles, auto-layout, layout constraints. Focus on hierarchy, spacing, and content placement; temporary or neutral fills are acceptable. Then call **getDesignScreenshot** with \`frameId\`. Check the image: layout correct? Content and frames hugging/filling as intended? If not, fix with design commands and take another screenshot until satisfied.
3351
+
3352
+ **Pass 2 \u2014 Apply design tokens and AI rules**
3353
+ Apply the owner's design system: set all fills to variable/paint ids from \`resolved\` (e.g. Background / surface, Brand / primary). Set all text to text style ids from \`resolved\`. Apply button and component tokens from getAIToolRules (colors, typography, buttons). Then call **getDesignScreenshot**. Check: do colors, typography, and buttons match the design system and rules? If not, fix and re-check.
3354
+
3355
+ **Pass 3 \u2014 Confirm no hardcoded values and follow AI rules**
3356
+ Audit: ensure no raw px, hex, or font values were introduced. Verify every fill, text style, and spacing uses an id from \`resolved\`. Check getAIToolRules again for colors, typography, buttons. Then call **getDesignScreenshot** one last time. If all good: call **finalizeDesignFrame** with \`frameId\`, \`name\` = short description of the design + " \u2705", and \`fillVariableId\` (or \`fillPaintStyleId\`) for the surface/background so the placeholder gray is removed. Then **summarise** what was built and any fixes made across passes.
3357
+
3358
+ Do not generate or run any JavaScript code. Use only the MCP tools listed above.
2180
3359
  `;
2181
3360
  var SHOWCASE_HTML_TEMPLATE = `<!DOCTYPE html>
2182
3361
  <html lang="en">
@@ -2239,20 +3418,15 @@ var SHOWCASE_HTML_TEMPLATE = `<!DOCTYPE html>
2239
3418
  `;
2240
3419
  var AI_TOOLS = ["cursor", "copilot", "windsurf", "cline", "continue", "zed", "generic"];
2241
3420
  server.setRequestHandler(ListResourcesRequestSchema, async () => {
3421
+ if (!hasValidAuthConfig() || authFailedNoTools) {
3422
+ throw new Error(AUTH_REQUIRED_MESSAGE);
3423
+ }
2242
3424
  try {
2243
3425
  await fetchDesignSystemForMCP();
2244
3426
  return { resources: [] };
2245
3427
  } catch {
2246
- return {
2247
- resources: [
2248
- {
2249
- uri: "atomix://setup",
2250
- name: "Configure MCP",
2251
- description: "Add --ds-id to your MCP config to load design system resources",
2252
- mimeType: "text/markdown"
2253
- }
2254
- ]
2255
- };
3428
+ authFailedNoTools = true;
3429
+ throw new Error(AUTH_REQUIRED_MESSAGE);
2256
3430
  }
2257
3431
  });
2258
3432
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
@@ -2264,7 +3438,7 @@ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
2264
3438
  mimeType: "text/markdown",
2265
3439
  text: `# Configure Atomix MCP
2266
3440
 
2267
- Add \`--ds-id <your-design-system-id>\` to your MCP server config.
3441
+ Add \`--ds-id\` and \`--atomix-token\` to your MCP server config (both required).
2268
3442
 
2269
3443
  Example (\`.cursor/mcp.json\`):
2270
3444
  \`\`\`json
@@ -2272,16 +3446,19 @@ Example (\`.cursor/mcp.json\`):
2272
3446
  "mcpServers": {
2273
3447
  "atomix": {
2274
3448
  "command": "npx",
2275
- "args": ["@atomixstudio/mcp@latest", "--ds-id", "<your-ds-id>"]
3449
+ "args": ["@atomixstudio/mcp@latest", "--ds-id", "<your-ds-id>", "--atomix-token", "<your-token>"]
2276
3450
  }
2277
3451
  }
2278
3452
  }
2279
3453
  \`\`\`
2280
3454
 
2281
- Get your DS ID from: https://atomixstudio.eu/ds/[your-ds-id]`
3455
+ Get your DS ID and token from the Export modal or Settings \u2192 Regenerate Atomix access token.`
2282
3456
  }]
2283
3457
  };
2284
3458
  }
3459
+ if (!hasValidAuthConfig() || authFailedNoTools) {
3460
+ throw new Error("MCP access requires valid --ds-id and --atomix-token. Add both to your MCP config and restart Cursor. See atomix://setup for instructions.");
3461
+ }
2285
3462
  const data = await fetchDesignSystemForMCP();
2286
3463
  const stats = getTokenStats(data);
2287
3464
  if (uri === "atomix://hello") {
@@ -2318,19 +3495,49 @@ Get your DS ID from: https://atomixstudio.eu/ds/[your-ds-id]`
2318
3495
  }
2319
3496
  throw new Error(`Unknown resource: ${uri}`);
2320
3497
  });
3498
+ var FIGMA_PROMPT_NAMES = /* @__PURE__ */ new Set(["--sync-to-figma", "--design-in-figma"]);
2321
3499
  server.setRequestHandler(ListPromptsRequestSchema, async () => {
2322
- const prompts = [
3500
+ if (!hasValidAuthConfig()) {
3501
+ authFailedNoTools = true;
3502
+ throw new Error(AUTH_REQUIRED_MESSAGE);
3503
+ }
3504
+ if (cachedMcpTier === null && !authFailedNoTools) {
3505
+ try {
3506
+ await fetchDesignSystemForMCP(true);
3507
+ } catch {
3508
+ authFailedNoTools = true;
3509
+ }
3510
+ }
3511
+ if (authFailedNoTools) {
3512
+ throw new Error(AUTH_REQUIRED_MESSAGE);
3513
+ }
3514
+ const allPrompts = [
2323
3515
  { name: "--hello", description: "Get started with this design system - overview, tokens, and tools. Run this first!" },
2324
- { name: "--getstarted", description: "Get started with design system in project. Three phases: scan, report and ask, then create only after you approve." },
3516
+ { name: "--get-started", description: "Get started with design system in project. Three phases: scan, report and ask, then create only after you approve." },
2325
3517
  { name: "--rules", description: "Get the design system governance rules for your AI coding tool (default: cursor)." },
2326
- { name: "--sync", description: "Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. Use /--refactor to migrate." },
2327
- { name: "--refactor", description: "Migrate deprecated tokens in codebase. Run after /--sync." }
3518
+ { name: "--sync", description: "Sync tokens, AI rules, skills files, and dependencies manifest (icons, fonts). Use /--refactor to migrate deprecated tokens." },
3519
+ { name: "--refactor", description: "Migrate deprecated tokens in codebase. Run after /--sync." },
3520
+ { name: "--sync-to-figma", description: "Push this design system to Figma (variables, color + typography styles). Uses local bridge + plugin; no Figma token." },
3521
+ { name: "--design-in-figma", description: "Design UI in Figma: 3 passes (wireframe \u2192 tokens/rules \u2192 audit), getDesignScreenshot after each pass, then finalizeDesignFrame (rename + \u2705, remove placeholder) and summarise." }
2328
3522
  ];
3523
+ const prompts = cachedMcpTier === "pro" ? allPrompts : allPrompts.filter((p) => !FIGMA_PROMPT_NAMES.has(p.name));
2329
3524
  return { prompts };
2330
3525
  });
2331
3526
  server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2332
3527
  const { name, arguments: args } = request.params;
2333
- const canonicalName = name === "--hello" ? "hello" : name === "--getstarted" ? "atomix-setup" : name === "--rules" ? "design-system-rules" : name === "--sync" ? "sync" : name === "--refactor" ? "refactor" : name;
3528
+ if (!hasValidAuthConfig() || authFailedNoTools) {
3529
+ return {
3530
+ description: "MCP Server Configuration Required",
3531
+ messages: [{
3532
+ role: "user",
3533
+ content: {
3534
+ type: "text",
3535
+ text: "MCP access requires valid --ds-id and --atomix-token. Add both to your MCP config and restart Cursor. No tools or prompts are available until then."
3536
+ }
3537
+ }]
3538
+ };
3539
+ }
3540
+ const canonicalName = name === "--hello" ? "hello" : name === "--get-started" ? "atomix-setup" : name === "--rules" ? "design-system-rules" : name === "--sync" ? "sync" : name === "--refactor" ? "refactor" : name === "--sync-to-figma" || name === "syncToFigma" ? "sync-to-figma" : name === "--design-in-figma" ? "design-in-figma" : name;
2334
3541
  const shouldForceRefresh = canonicalName === "sync";
2335
3542
  let data = null;
2336
3543
  let stats = null;
@@ -2348,12 +3555,10 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2348
3555
  content: {
2349
3556
  type: "text",
2350
3557
  text: `The MCP server isn't configured. To use design system prompts, you need to configure the server with:
2351
- - \`--ds-id\`: Your design system ID (required - get it from https://atomixstudio.eu/ds/[your-ds-id])
2352
- - \`--api-key\`: Your API key (optional - only needed for private design systems)
3558
+ - \`--ds-id\`: Your design system ID (get it from https://atomixstudio.eu/ds/[your-ds-id])
3559
+ - \`--atomix-token\`: Your access token (get it from the Export modal or Settings \u2192 Regenerate Atomix access token)
2353
3560
 
2354
- **Note:** Most design systems are public and don't require an API key. Only add \`--api-key\` if your design system is private.
2355
-
2356
- Configure the MCP server in your Cursor settings, then restart Cursor.`
3561
+ Both are required. Configure the MCP server in your Cursor settings, then restart Cursor.`
2357
3562
  }
2358
3563
  }
2359
3564
  ]
@@ -2384,12 +3589,12 @@ Configure the MCP server in your Cursor settings, then restart Cursor.`
2384
3589
  } else if (status === "401" || status === "403") {
2385
3590
  helpText += `**Possible causes:**
2386
3591
  `;
2387
- helpText += `- Design system is private and requires an API key
3592
+ helpText += `- Missing or invalid access token
2388
3593
  `;
2389
- helpText += `- API key is invalid or expired
3594
+ helpText += `- You don't have access to this design system (owner or invited guest only)
2390
3595
 
2391
3596
  `;
2392
- helpText += `**Solution:** Add \`--api-key <your-key>\` to your MCP server configuration.`;
3597
+ helpText += `**Solution:** Add \`--atomix-token <your-token>\` from the Export modal or Settings \u2192 Regenerate.`;
2393
3598
  } else {
2394
3599
  helpText += `**Possible causes:**
2395
3600
  `;
@@ -2417,6 +3622,20 @@ Configure the MCP server in your Cursor settings, then restart Cursor.`
2417
3622
  }
2418
3623
  throw error;
2419
3624
  }
3625
+ if (FIGMA_PROMPT_NAMES.has(name) && cachedMcpTier !== "pro") {
3626
+ return {
3627
+ description: "Pro Figma required",
3628
+ messages: [
3629
+ {
3630
+ role: "user",
3631
+ content: {
3632
+ type: "text",
3633
+ text: "This design system does not have Pro Figma access. Figma sync and design prompts are available when the design system owner has a Pro subscription."
3634
+ }
3635
+ }
3636
+ ]
3637
+ };
3638
+ }
2420
3639
  const buildCategoryPrompt = (category, instructions) => {
2421
3640
  const lines = [];
2422
3641
  lines.push(`## Design System Information`);
@@ -2636,19 +3855,61 @@ Format the response as a markdown table with columns: Token Name | Value | CSS V
2636
3855
  case "sync": {
2637
3856
  const output = args?.output || "./tokens.css";
2638
3857
  const format = args?.format || "css";
2639
- const response = {
2640
- description: `Sync design tokens to ${output}`,
3858
+ return {
3859
+ description: "Sync tokens, rules, skills, and dependencies manifest",
2641
3860
  messages: [
2642
3861
  {
2643
3862
  role: "user",
2644
3863
  content: {
2645
3864
  type: "text",
2646
- text: `Call the syncTokens tool now. Use output="${output}" and format="${format}". Execute immediately - do not search or ask questions.`
3865
+ text: `Call the syncAll tool now. Use output="${output}" and format="${format}". This syncs tokens, AI rules, skills (.cursor/skills/atomix-ds/*), and atomix-dependencies.json. Execute immediately - do not search or ask questions.`
3866
+ }
3867
+ }
3868
+ ]
3869
+ };
3870
+ }
3871
+ case "sync-to-figma": {
3872
+ return {
3873
+ description: "Push design system to Figma via MCP tool",
3874
+ messages: [
3875
+ {
3876
+ role: "user",
3877
+ content: {
3878
+ type: "text",
3879
+ text: `Call the MCP tool **syncToFigma** now (no arguments). It pushes the design system into the open Figma file via the built-in bridge and Atomix plugin. Do not use the Figma REST API or external scripts. If the response includes \`bridgeNotRunning\` and \`agentInstruction\`, ensure Cursor has this MCP server running, then in Figma run the Atomix plugin and click Connect to Cursor, then call syncToFigma again. Only if that fails, tell the user: (1) Ensure Cursor has this MCP configured and running. (2) In Figma, open and run the Atomix plugin, then tap **Connect to Cursor**. (3) Run Sync to Figma again.`
3880
+ }
3881
+ }
3882
+ ]
3883
+ };
3884
+ }
3885
+ case "design-in-figma": {
3886
+ return {
3887
+ description: "Design in Figma using granular MCP commands: 3 passes (wireframe \u2192 tokens \u2192 audit), screenshot checks, then finalize and summarise",
3888
+ messages: [
3889
+ {
3890
+ role: "user",
3891
+ content: {
3892
+ type: "text",
3893
+ text: `You must **design in Figma** by calling a **sequence of MCP tools**\u2014do not generate or run any JavaScript code. Follow the design-in-Figma skill if present; otherwise follow this **three-pass flow**.
3894
+
3895
+ Prerequisites: Figma bridge runs inside this MCP server. In Figma, run the Atomix plugin and click "Connect to Cursor"; leave the plugin open.
3896
+
3897
+ **Setup (once):** syncToFigma \u2192 createDesignPlaceholder (save \`frameId\`) \u2192 getAIToolRules + listTokens \u2192 resolveFigmaIdsForTokens. Use the returned \`resolved\` map and \`frameId\` for all passes.
3898
+
3899
+ **Pass 1 \u2014 Layout and contents (wireframe)**
3900
+ Build the structure: designCreateFrame, designCreateText, designCreateRectangle, designSetAutoLayout (use paddingVariableId, itemSpacingVariableId, and layoutSizingHorizontal/layoutSizingVertical HUG or FILL from resolved), designSetLayoutConstraints, designAppendChild. Focus on hierarchy, spacing, and content placement. Then call **getDesignScreenshot** with \`frameId\`. Check the returned image: is layout correct? Do elements hug or fill as intended? If not, fix and take another screenshot until satisfied.
3901
+
3902
+ **Pass 2 \u2014 Apply design tokens and AI rules**
3903
+ Apply the owner's design system: set all fills and text styles using only ids from \`resolved\` (no raw px/hex). Strictly follow getAIToolRules for **colors, typography, and buttons**. Then call **getDesignScreenshot**. Check: do colors, typography, and buttons match the design system? If not, fix and re-check.
3904
+
3905
+ **Pass 3 \u2014 Confirm no hardcoded values**
3906
+ Audit: ensure no raw px, hex, or font values remain; every fill and text style must use an id from \`resolved\`. Call **getDesignScreenshot** once more. If everything is correct: call **finalizeDesignFrame** with \`frameId\`, \`name\` = a short description of the design + " \u2705", and \`fillVariableId\` (or \`fillPaintStyleId\`) from resolved for the surface/background so the placeholder gray is removed. Then **summarise** what was built and any fixes made across the three passes.
3907
+
3908
+ If the bridge is not reachable: tell the user to run the Atomix plugin in Figma and click Connect to Cursor, then retry.`
2647
3909
  }
2648
3910
  }
2649
3911
  ]
2650
3912
  };
2651
- return response;
2652
3913
  }
2653
3914
  case "refactor": {
2654
3915
  if (!lastSyncAffectedTokens) {
@@ -2762,7 +4023,7 @@ Use \`/color\`, \`/spacing\`, \`/radius\`, \`/typography\`, \`/shadow\`, \`/bord
2762
4023
  };
2763
4024
  }
2764
4025
  case "atomix-setup": {
2765
- const setupInstructions = `You are running **/--getstarted** (get started with design system). Three phases only.
4026
+ const setupInstructions = `You are running **/--get-started** (get started with design system). Three phases only.
2766
4027
 
2767
4028
  **Rule:** Do not create, write, or modify any file until Phase 3 and only after the user has explicitly approved (e.g. "Yes", "Yes for all", "Go ahead").
2768
4029
 
@@ -2774,8 +4035,8 @@ Use \`/color\`, \`/spacing\`, \`/radius\`, \`/typography\`, \`/shadow\`, \`/bord
2774
4035
 
2775
4036
  - Resolve platform/stack: infer from the project (e.g. package.json, build.gradle, Xcode) or ask once: "Which platform? (e.g. web, Android, iOS)" and if relevant "Which stack? (e.g. React, Vue, Next, Swift, Kotlin)." Do not assume a default.
2776
4037
  - Call **getDependencies** with \`platform\` and optional \`stack\`. If it fails, tell the user the design system could not be reached and stop.
2777
- - Scan the repo for: .cursor/skills/atomix-ds/SKILL.md, a tokens file (e.g. tokens.css or src/tokens.css), icon package from getDependencies, font links. **Web:** note any existing CSS (globals.css, main.css, Tailwind, etc.). **Native:** note any theme/style files (SwiftUI, Android themes, Compose).
2778
- - Build two lists: **Suggested** (from getDependencies minus what exists) and **Already present**. Include: icon package, font links, skill (.cursor/skills/atomix-ds/SKILL.md), token files; for web, also include the **showcase page** (atomix-setup-showcase.html) if getDependencies returned a \`showcase\` object.
4038
+ - Scan the repo for: .cursor/skills/atomix-ds/SKILL.md, .cursor/skills/atomix-ds/design-in-figma.md, a tokens file (e.g. tokens.css or src/tokens.css), icon package from getDependencies, font links. **Web:** note any existing CSS (globals.css, main.css, Tailwind, etc.). **Native:** note any theme/style files (SwiftUI, Android themes, Compose).
4039
+ - Build two lists: **Suggested** (from getDependencies minus what exists) and **Already present**. Include: icon package, font links, skill (.cursor/skills/atomix-ds/SKILL.md), **Figma design skill** (.cursor/skills/atomix-ds/design-in-figma.md), token files; for web, also include the **showcase page** (atomix-setup-showcase.html) if getDependencies returned a \`showcase\` object.
2779
4040
  - Do not write, create, or add anything in Phase 1.
2780
4041
 
2781
4042
  ## Phase 2 \u2013 Report and ask
@@ -2788,19 +4049,20 @@ Use \`/color\`, \`/spacing\`, \`/radius\`, \`/typography\`, \`/shadow\`, \`/bord
2788
4049
 
2789
4050
  - Run only when the user has said yes (all or specific items).
2790
4051
  - For each approved item:
2791
- - **Skill:** Write the skill content from getDependencies to .cursor/skills/atomix-ds/SKILL.md.
2792
- - **Token file:** Call **syncTokens** with \`output\` set to the path (e.g. "./src/tokens.css" or "./tokens.css"). You must call syncTokens; do not only suggest the user run it later.
4052
+ - **Skill:** Write the skill content from getDependencies \`skill.content\` to \`skill.path\` (.cursor/skills/atomix-ds/SKILL.md).
4053
+ - **Figma design skill:** Write the skill content from getDependencies \`skillFigmaDesign.content\` to \`skillFigmaDesign.path\` (.cursor/skills/atomix-ds/design-in-figma.md). Use this when designing in Figma so the agent follows principal-product-designer rules and prefers existing Figma variables.
4054
+ - **Token file:** Call **syncAll** with \`output\` set to the path (e.g. "./src/tokens.css" or "./tokens.css"). syncAll also writes skills and atomix-dependencies.json. You must call syncAll; do not only suggest the user run it later.
2793
4055
  - **Icon package:** Install per getDependencies. When rendering icons, apply the design system's icon tokens: use getToken(\`sizing.icon.*\`) or listTokens(\`sizing\`) for size, and getToken(\`icons.strokeWidth\`) for stroke width when the DS defines it; do not use hardcoded sizes or stroke widths.
2794
4056
  - **Fonts and typeset:** Add font links (e.g. \`<link>\` or \`@import\` from Google Fonts). Then build a **typeset** in CSS: use **getToken** / **listTokens** (category \`typography\`) to get fontFamily, fontSize, fontWeight, lineHeight, letterSpacing for display, heading, and body, and write CSS rules (e.g. \`.typeset-display\`, \`.typeset-heading\`, \`.typeset-body\`, or \`h1\`/\`h2\`/\`p\`) that set those properties to \`var(--atmx-typography-*)\`. The typeset file (or section) must define the full type scale\u2014not only a font import. Do not create a CSS file that contains only a font import.
2795
4057
  - **Showcase page (web only):** If platform is web and getDependencies returned a \`showcase\` object, create the file at \`showcase.path\` using \`showcase.template\`. Replace every placeholder per \`showcase.substitutionInstructions\`: TOKENS_CSS_PATH, DS_NAME, BRAND_PRIMARY_VAR (page background), BRAND_PRIMARY_FOREGROUND_VAR (text on brand), HEADING_FONT_VAR (h1), FONT_FAMILY_VAR (body), FONT_LINK_TAG. Use only CSS variable names that exist in the synced token file. Do not change the HTML structure. After creating the file, launch it in the default browser (e.g. \`open atomix-setup-showcase.html\` on macOS, \`xdg-open atomix-setup-showcase.html\` on Linux, or the equivalent on Windows).
2796
- - Report only what you actually created or updated. Do not claim the token file was added if you did not call syncTokens.
4058
+ - Report only what you actually created or updated. Do not claim the token file was added if you did not call syncAll.
2797
4059
  - **After reporting \u2013 styles/theme:**
2798
4060
  - **Web:** If the project already has at least one CSS file: recommend how to integrate Atomix (e.g. import the synced tokens file, use \`var(--atmx-*)\`). Do not suggest a new global CSS. Only if there is **no** CSS file at all, ask once: "There are no CSS files yet. Do you want me to build a global typeset from the design system?" If yes, create a CSS file that includes: (1) font \`@import\` or document that a font link is needed, and (2) **typeset rules**\u2014CSS classes or element rules that set font-family, font-size, font-weight, line-height, letter-spacing using \`var(--atmx-typography-*)\` from the token file (e.g. \`.typeset-display\`, \`.typeset-heading\`, \`.typeset-body\`). You must call getToken/listTokens to get the exact typography token paths and write the corresponding var() references. The output must not be only a font import; it must define the full typeset (Display, Heading, body) with every style detail from the design system.
2799
4061
  - **iOS/Android:** If the project already has theme/style files: recommend how to integrate Atomix tokens. Do not suggest a new global theme. Only if there is **no** theme/style at all, ask once: "There's no theme/style setup yet. Do you want a minimal token-based theme?" and add only if the user says yes.
2800
4062
 
2801
4063
  Create your todo list first, then Phase 1 (resolve platform/stack, call getDependencies, scan, build lists), then Phase 2 (report and ask). Do not perform Phase 3 until the user replies.`;
2802
4064
  return {
2803
- description: "Get started with design system in project (/--getstarted). Create todo list; Phase 1 scan, Phase 2 report and ask, Phase 3 create only after user approval.",
4065
+ description: "Get started with design system in project (/--get-started). Create todo list; Phase 1 scan, Phase 2 report and ask, Phase 3 create only after user approval.",
2804
4066
  messages: [
2805
4067
  {
2806
4068
  role: "user",
@@ -2871,12 +4133,12 @@ ${tokenSummary}
2871
4133
  | Command | What to expect |
2872
4134
  |---------|----------------|
2873
4135
  | **/--hello** | Get started - overview, tokens, and tools. Run this first! |
2874
- | **/--getstarted** | Get started with design system in project. Three phases; creates files only after you approve. |
4136
+ | **/--get-started** | Get started with design system in project. Three phases; creates files only after you approve. |
2875
4137
  | **/--rules** | Governance rules for your AI tool (Cursor, Copilot, Windsurf, etc.). |
2876
- | **/--sync** | Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. |
4138
+ | **/--sync** | Sync tokens, rules, skills, and dependencies manifest (icons, fonts). Safe: adds new, updates existing, marks deprecated. |
2877
4139
  | **/--refactor** | Migrate deprecated tokens in codebase. Run after /--sync. |
2878
4140
 
2879
- **Suggested next step:** Run **/--getstarted** to set up global styles, icons, fonts, and token files; the AI will list options and ask before adding anything.
4141
+ **Suggested next step:** Run **/--get-started** to set up global styles, icons, fonts, and token files; the AI will list options and ask before adding anything.
2880
4142
 
2881
4143
  ---
2882
4144
 
@@ -2886,17 +4148,32 @@ ${tokenSummary}
2886
4148
  async function startServer() {
2887
4149
  if (!dsId) {
2888
4150
  console.error("Error: Missing --ds-id argument");
2889
- console.error("Usage: npx atomix --ds-id <id> [--api-key <key>]");
2890
- console.error("Note: --api-key is optional (only needed for private design systems)");
4151
+ console.error("Usage: npx @atomixstudio/mcp@latest --ds-id <id> --atomix-token <token>");
4152
+ console.error("Get your DS ID and Atomix access token from account settings.");
4153
+ console.error("");
4154
+ process.exit(1);
4155
+ }
4156
+ if (!accessToken) {
4157
+ console.error("Error: Missing --atomix-token argument");
4158
+ console.error("Usage: npx @atomixstudio/mcp@latest --ds-id <id> --atomix-token <token>");
4159
+ console.error("Get your DS ID and Atomix access token from account settings.");
2891
4160
  console.error("");
2892
- console.error("For sync command: npx atomix sync --help");
2893
- console.error("Get your DS ID from https://atomixstudio.eu/ds/[your-ds-id]");
2894
4161
  process.exit(1);
2895
4162
  }
4163
+ startFigmaBridge();
2896
4164
  const transport = new StdioServerTransport();
2897
4165
  await server.connect(transport);
2898
4166
  console.error(`Atomix MCP Server started for design system: ${dsId}`);
4167
+ console.error(`Atomix MCP API base: ${apiBase}`);
4168
+ console.error(
4169
+ "If you switched MCP config (e.g. free vs pro DS), restart Cursor so this process uses the new --ds-id and --atomix-token."
4170
+ );
4171
+ }
4172
+ function onShutdown() {
4173
+ closeFigmaBridge();
2899
4174
  }
4175
+ process.on("SIGINT", onShutdown);
4176
+ process.on("SIGTERM", onShutdown);
2900
4177
  async function main() {
2901
4178
  await startServer();
2902
4179
  }