@tempad-dev/mcp 0.7.1 → 0.8.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,11 +20,14 @@ For agent-specific setup, open TemPad Dev's **Preferences → Agent integration
20
20
  Supported tools/resources:
21
21
 
22
22
  - `get_code`: Tailwind-first JSX/Vue markup plus assets and token references.
23
+ - `get_design_system`: Query-ranked Figma components and variables from the active page/file.
24
+ - `apply_canvas`: One declarative create/update result, reconciled locally against the live canvas.
23
25
  - `get_structure`: Hierarchy/geometry outline for the selection.
24
26
 
25
27
  Notes:
26
28
 
27
29
  - Tool responses use a shared `64 KiB` inline budget measured on the `CallToolResult` body. When a selection is too large for the `get_code` budget, TemPad Dev may return a shell response instead of failing. The shell keeps the current node wrapper and lists omitted direct child ids in an inline code comment so agents can request them one by one. The accompanying warning stays lightweight and only points agents to that comment.
30
+ - `apply_canvas` is disabled by default. Enable **Canvas writes** in Agent integration only when you want the connected agent to modify the active Figma file.
28
31
  - Assets are ephemeral and tool-linked; image/SVG bytes are downloaded via the capability-bearing HTTP `asset.url` from tool results. Treat the full URL as a temporary secret and do not persist it in logs.
29
32
  - Asset resources are not exposed via MCP `resources/list`/`resources/read`.
30
33
  - The HTTP fallback URL uses `/{capability}/assets/{hash}` and may include an image extension (for example `/{capability}/assets/{hash}.png`). Both filename forms are accepted.
package/README.zh-Hans.md CHANGED
@@ -18,11 +18,14 @@
18
18
  支持的工具和资源:
19
19
 
20
20
  - `get_code`:以 Tailwind 优先的 JSX/Vue 标记输出,并附带资源和变量引用。
21
+ - `get_design_system`:从当前页面/文件中返回按查询排序的 Figma 组件和变量。
22
+ - `apply_canvas`:提交一次声明式创建或更新结果,由扩展与实时画布在本地进行增量协调。
21
23
  - `get_structure`:当前选中节点的层级/几何结构信息。
22
24
 
23
25
  说明:
24
26
 
25
27
  - 工具响应共用 `64 KiB` 的 inline budget,按 `CallToolResult` 整体响应体积计算。若选区过大而超出 `get_code` 的预算,TemPad Dev 可能返回 shell response 而不是直接失败。shell 会保留当前节点的包裹结构,并在内联代码注释中列出被省略的直接子节点 id,方便 agent 逐个继续拉取;配套 warning 只保留最小化的提示信息,用来指向这条注释。
28
+ - `apply_canvas` 默认禁用。只有在希望已连接的 agent 修改当前 Figma 文件时,才在 Agent integration 中启用 **Canvas writes**。
26
29
  - 资源是临时且与工具调用关联的;图片/SVG 请直接使用工具结果中带 capability 的 HTTP `asset.url` 下载。完整 URL 应视作临时密钥,不要持久化到日志中。
27
30
  - MCP 不再暴露 `resources/list` / `resources/read` 用于 asset 内容读取。
28
31
  - HTTP 回退 URL 使用 `/{capability}/assets/{hash}`,也可能带图片扩展名(例如 `/{capability}/assets/{hash}.png`),两种文件名形式都支持。
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as LOCK_PATH, c as SOCK_PATH, d as log, l as ensureDir, o as PACKAGE_VERSION, s as RUNTIME_DIR } from "./shared-Df79xZoB.mjs";
2
+ import { a as LOCK_PATH, c as SOCK_PATH, d as log, l as ensureDir, o as PACKAGE_VERSION, s as RUNTIME_DIR } from "./shared-BM-k8yN9.mjs";
3
3
  import { spawn } from "node:child_process";
4
4
  import { connect } from "node:net";
5
5
  import { join } from "node:path";
package/dist/hub.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-Df79xZoB.mjs";
1
+ import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-BM-k8yN9.mjs";
2
2
  import { connect, createServer } from "node:net";
3
3
  import { join } from "node:path";
4
4
  import { URL as URL$1 } from "node:url";
@@ -32,6 +32,12 @@ const TEMPAD_MCP_ERROR_CODES = {
32
32
  EXTENSION_DISCONNECTED: "EXTENSION_DISCONNECTED",
33
33
  INVALID_SELECTION: "INVALID_SELECTION",
34
34
  NODE_NOT_VISIBLE: "NODE_NOT_VISIBLE",
35
+ CANVAS_WRITE_DISABLED: "CANVAS_WRITE_DISABLED",
36
+ CANVAS_UNSUPPORTED_EDITOR: "CANVAS_UNSUPPORTED_EDITOR",
37
+ CANVAS_BUSY: "CANVAS_BUSY",
38
+ INVALID_CANVAS_SCOPE: "INVALID_CANVAS_SCOPE",
39
+ INVALID_CANVAS_SPEC: "INVALID_CANVAS_SPEC",
40
+ CANVAS_APPLY_FAILED: "CANVAS_APPLY_FAILED",
35
41
  ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
36
42
  TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
37
43
  };
@@ -189,7 +195,7 @@ function buildPluginSetupCommand(prefix) {
189
195
  return [`codex plugin marketplace add ${REPOSITORY} --ref main`, `codex plugin add ${PLUGIN_NAME}@${MARKETPLACE_NAME}`].join(" && ");
190
196
  }
191
197
  function buildPluginSetupDeepLink(prefix) {
192
- const prompt = `Install the TemPad Dev agent plugin by running this command, then confirm that its MCP server and figma-design-to-code skill are available:\n\n${buildPluginSetupCommand(prefix)}`;
198
+ const prompt = `Install the TemPad Dev agent plugin by running this command, then confirm that its MCP server plus figma-design-to-code and figma-canvas-authoring skills are available:\n\n${buildPluginSetupCommand(prefix)}`;
193
199
  return `${prefix === "claude" ? "claude-cli://open?q=" : "codex://new?prompt="}${encodeURIComponent(prompt)}`;
194
200
  }
195
201
  function buildSkillInstallCommand(...agents) {
@@ -440,6 +446,12 @@ function buildGetCodeToolResult(payload) {
440
446
  summary.push("Read structuredContent for the full code string and metadata.");
441
447
  return buildTextToolResult(summary.join("\n"), payload);
442
448
  }
449
+ function buildGetDesignSystemToolResult(payload) {
450
+ return buildTextToolResult(`${`Found ${formatCount(payload.components.length, "component")} and ${formatCount(payload.variables.length, "variable")} on page "${payload.page.name}".`}${payload.warnings?.length ? `\n${payload.warnings.join("\n")}` : ""}\nRead structuredContent for stable component and variable references.`, payload);
451
+ }
452
+ function buildApplyCanvasToolResult(payload) {
453
+ return buildTextToolResult(`${`Applied ${formatCount(payload.mutationCount, "canvas mutation")}: ${formatCount(payload.createdNodeIds.length, "node")} created and ${formatCount(payload.updatedNodeIds.length, "node")} updated.`}${payload.warnings?.length ? `\n${payload.warnings.join("\n")}` : ""}\nRoot node: ${payload.rootNodeId}. Reuse nodeIdsByKey for later updates.`, payload);
454
+ }
443
455
  function buildGetStructureToolResult(payload) {
444
456
  const roots = payload.roots.length;
445
457
  const nodeCount = countOutlineNodes(payload.roots);
@@ -518,6 +530,191 @@ const GetStructureParametersSchema = z.object({
518
530
  nodeId: z.string().describe("Optional node id to outline; defaults to the current single selection. Useful when auto-layout hints are none/inferred or you need explicit geometry for refactors.").optional(),
519
531
  options: z.object({ depth: z.number().int().positive().describe("Limit traversal depth; defaults to full tree (subject to safety caps).").optional() }).optional()
520
532
  });
533
+ const GetDesignSystemParametersSchema = z.object({ query: z.string().trim().min(1).max(500).describe("Optional task or design-system query used to rank matching components and variables.").optional() }).strict();
534
+ const CanvasDesignReferenceSchema = z.object({
535
+ id: z.string().min(1).describe("Live Figma node or variable id.").optional(),
536
+ key: z.string().min(1).describe("Importable Figma library key.").optional()
537
+ }).strict().refine((reference) => reference.id !== void 0 || reference.key !== void 0, { message: "A design-system reference requires id or key." });
538
+ const CanvasNodeTypeSchema = z.enum([
539
+ "ELLIPSE",
540
+ "FRAME",
541
+ "INSTANCE",
542
+ "LINE",
543
+ "RECTANGLE",
544
+ "TEXT"
545
+ ]);
546
+ const CanvasColorSchema = z.string().regex(/^#[\dA-Fa-f]{6}(?:[\dA-Fa-f]{2})?$/, "Use #RRGGBB or #RRGGBBAA.");
547
+ const CanvasFiniteNumberSchema = z.number().finite();
548
+ const CanvasNonnegativeNumberSchema = z.number().nonnegative().finite();
549
+ const CanvasPositiveNumberSchema = z.number().positive().finite();
550
+ const CanvasPositionSchema = z.object({
551
+ x: CanvasFiniteNumberSchema.optional(),
552
+ y: CanvasFiniteNumberSchema.optional()
553
+ }).strict();
554
+ const CanvasSizeSchema = z.object({
555
+ width: CanvasPositiveNumberSchema.optional(),
556
+ height: CanvasPositiveNumberSchema.optional(),
557
+ horizontal: z.enum([
558
+ "FILL",
559
+ "FIXED",
560
+ "HUG"
561
+ ]).optional(),
562
+ vertical: z.enum([
563
+ "FILL",
564
+ "FIXED",
565
+ "HUG"
566
+ ]).optional()
567
+ }).strict();
568
+ const CanvasPaddingSchema = z.object({
569
+ top: CanvasNonnegativeNumberSchema.optional(),
570
+ right: CanvasNonnegativeNumberSchema.optional(),
571
+ bottom: CanvasNonnegativeNumberSchema.optional(),
572
+ left: CanvasNonnegativeNumberSchema.optional()
573
+ }).strict();
574
+ const CanvasLayoutSchema = z.object({
575
+ mode: z.enum([
576
+ "HORIZONTAL",
577
+ "NONE",
578
+ "VERTICAL"
579
+ ]).optional(),
580
+ gap: CanvasFiniteNumberSchema.optional(),
581
+ padding: z.union([CanvasNonnegativeNumberSchema, CanvasPaddingSchema]).optional(),
582
+ primaryAlign: z.enum([
583
+ "CENTER",
584
+ "MAX",
585
+ "MIN",
586
+ "SPACE_BETWEEN"
587
+ ]).optional(),
588
+ counterAlign: z.enum([
589
+ "BASELINE",
590
+ "CENTER",
591
+ "MAX",
592
+ "MIN"
593
+ ]).optional()
594
+ }).strict();
595
+ const CanvasAppearanceSchema = z.object({
596
+ fill: CanvasColorSchema.nullable().optional(),
597
+ stroke: CanvasColorSchema.nullable().optional(),
598
+ strokeWeight: CanvasNonnegativeNumberSchema.optional(),
599
+ cornerRadius: CanvasNonnegativeNumberSchema.optional(),
600
+ opacity: z.number().min(0).max(1).finite().optional()
601
+ }).strict();
602
+ const CanvasTextSchema = z.object({
603
+ characters: z.string().max(1e5).optional(),
604
+ fontFamily: z.string().min(1).max(200).optional(),
605
+ fontStyle: z.string().min(1).max(200).optional(),
606
+ fontSize: CanvasPositiveNumberSchema.optional(),
607
+ lineHeight: CanvasPositiveNumberSchema.optional(),
608
+ letterSpacing: CanvasFiniteNumberSchema.optional(),
609
+ alignHorizontal: z.enum([
610
+ "CENTER",
611
+ "JUSTIFIED",
612
+ "LEFT",
613
+ "RIGHT"
614
+ ]).optional(),
615
+ alignVertical: z.enum([
616
+ "BOTTOM",
617
+ "CENTER",
618
+ "TOP"
619
+ ]).optional()
620
+ }).strict();
621
+ const CanvasVariableBindingsSchema = z.object({
622
+ fill: CanvasDesignReferenceSchema.optional(),
623
+ stroke: CanvasDesignReferenceSchema.optional(),
624
+ width: CanvasDesignReferenceSchema.optional(),
625
+ height: CanvasDesignReferenceSchema.optional(),
626
+ gap: CanvasDesignReferenceSchema.optional(),
627
+ paddingTop: CanvasDesignReferenceSchema.optional(),
628
+ paddingRight: CanvasDesignReferenceSchema.optional(),
629
+ paddingBottom: CanvasDesignReferenceSchema.optional(),
630
+ paddingLeft: CanvasDesignReferenceSchema.optional(),
631
+ cornerRadius: CanvasDesignReferenceSchema.optional(),
632
+ opacity: CanvasDesignReferenceSchema.optional(),
633
+ fontFamily: CanvasDesignReferenceSchema.optional(),
634
+ fontStyle: CanvasDesignReferenceSchema.optional(),
635
+ fontSize: CanvasDesignReferenceSchema.optional(),
636
+ lineHeight: CanvasDesignReferenceSchema.optional(),
637
+ letterSpacing: CanvasDesignReferenceSchema.optional()
638
+ }).strict();
639
+ const MAX_CANVAS_NODES = 100;
640
+ const MAX_CANVAS_DEPTH = 12;
641
+ const CanvasNodeSpecSchema = z.lazy(() => z.object({
642
+ key: z.string().min(1).max(128).regex(/^[\w./:-]+$/, "Use a stable key containing letters, numbers, ., /, :, _, or -.").describe("Agent-stable identity reused across later apply_canvas results."),
643
+ nodeId: z.string().min(1).describe("Optional exact live node identity; update mode only.").optional(),
644
+ type: CanvasNodeTypeSchema.describe("Native Figma node type."),
645
+ name: z.string().max(500).optional(),
646
+ visible: z.boolean().optional(),
647
+ position: CanvasPositionSchema.optional(),
648
+ size: CanvasSizeSchema.optional(),
649
+ layout: CanvasLayoutSchema.optional(),
650
+ appearance: CanvasAppearanceSchema.optional(),
651
+ text: CanvasTextSchema.optional(),
652
+ component: CanvasDesignReferenceSchema.describe("Required design-system component reference for INSTANCE nodes.").optional(),
653
+ componentProperties: z.record(z.string().min(1), z.union([z.string(), z.boolean()])).describe("Exposed component property values for an INSTANCE.").optional(),
654
+ variables: CanvasVariableBindingsSchema.describe("Figma variable bindings. A binding wins over a literal for the same field.").optional(),
655
+ children: z.array(CanvasNodeSpecSchema).max(MAX_CANVAS_NODES).describe("Desired FRAME children in order; omitted live children are preserved.").optional()
656
+ }).strict());
657
+ const ApplyCanvasParametersSchema = z.object({
658
+ mode: z.enum(["create", "update"]).describe("Create one new FRAME tree, or update one explicitly scoped live subtree."),
659
+ targetNodeId: z.string().min(1).describe("Required update-scope root node id; invalid in create mode.").optional(),
660
+ root: CanvasNodeSpecSchema.describe("Declarative desired result. Omitted fields and live children are preserved.")
661
+ }).strict().superRefine((value, context) => {
662
+ function addIssue(message, path) {
663
+ context.addIssue({
664
+ code: "custom",
665
+ message,
666
+ path
667
+ });
668
+ }
669
+ if (value.mode === "create") {
670
+ if (value.targetNodeId !== void 0) addIssue("targetNodeId is only valid in update mode.", ["targetNodeId"]);
671
+ if (value.root.type !== "FRAME") addIssue("Create mode requires a FRAME root.", ["root", "type"]);
672
+ } else {
673
+ if (value.targetNodeId === void 0) addIssue("Update mode requires targetNodeId.", ["targetNodeId"]);
674
+ if (value.root.nodeId !== void 0 && value.root.nodeId !== value.targetNodeId) addIssue("The root nodeId must match targetNodeId in update mode.", ["root", "nodeId"]);
675
+ }
676
+ const keys = /* @__PURE__ */ new Set();
677
+ const nodeIds = /* @__PURE__ */ new Set();
678
+ const stack = [{
679
+ depth: 1,
680
+ node: value.root,
681
+ path: ["root"]
682
+ }];
683
+ let count = 0;
684
+ while (stack.length) {
685
+ const { depth, node, path } = stack.pop();
686
+ count += 1;
687
+ if (count > MAX_CANVAS_NODES) {
688
+ addIssue(`Canvas specs may contain at most ${MAX_CANVAS_NODES} nodes.`, ["root"]);
689
+ break;
690
+ }
691
+ if (depth > MAX_CANVAS_DEPTH) addIssue(`Canvas specs may be at most ${MAX_CANVAS_DEPTH} levels deep.`, path);
692
+ if (keys.has(node.key)) addIssue(`Duplicate canvas key "${node.key}".`, [...path, "key"]);
693
+ keys.add(node.key);
694
+ if (node.nodeId) {
695
+ if (value.mode === "create") addIssue("Create mode cannot reference existing nodeIds.", [...path, "nodeId"]);
696
+ if (nodeIds.has(node.nodeId)) addIssue(`Duplicate nodeId "${node.nodeId}".`, [...path, "nodeId"]);
697
+ nodeIds.add(node.nodeId);
698
+ }
699
+ if (node.type === "INSTANCE" && !node.component) addIssue("INSTANCE nodes require a component reference.", [...path, "component"]);
700
+ if (node.type !== "INSTANCE" && node.component) addIssue("Only INSTANCE nodes accept a component reference.", [...path, "component"]);
701
+ if (node.type !== "INSTANCE" && node.componentProperties) addIssue("Only INSTANCE nodes accept componentProperties.", [...path, "componentProperties"]);
702
+ if (node.type !== "TEXT" && node.text) addIssue("Only TEXT nodes accept text properties.", [...path, "text"]);
703
+ if (node.type !== "FRAME" && node.layout) addIssue("Only FRAME nodes accept layout properties.", [...path, "layout"]);
704
+ if (node.type !== "FRAME" && node.children !== void 0) addIssue("Only FRAME nodes may declare children.", [...path, "children"]);
705
+ node.children?.forEach((child, index) => {
706
+ stack.push({
707
+ depth: depth + 1,
708
+ node: child,
709
+ path: [
710
+ ...path,
711
+ "children",
712
+ index
713
+ ]
714
+ });
715
+ });
716
+ }
717
+ });
521
718
  const GetAssetsParametersSchema = z.object({ hashes: z.array(z.string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.") });
522
719
  const GetAssetsResultSchema = z.object({
523
720
  assets: z.array(AssetDescriptorSchema),
@@ -1320,7 +1517,7 @@ function rawDataToBuffer(raw) {
1320
1517
  }
1321
1518
  //#endregion
1322
1519
  //#region src/instructions.md?raw
1323
- var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
1520
+ var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- For Figma authoring, combine Host design-system guidance with one `get_design_system` call. Prefer\n returned components and semantic variables, use primitives or literals only for gaps, then send\n one declarative `apply_canvas` result; do not emulate individual Figma Plugin API calls.\n- Reuse `nodeIdsByKey` returned by `apply_canvas` when refining existing generated content. Omitted\n fields and children are preserved; deletion is not supported.\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
1324
1521
  //#endregion
1325
1522
  //#region src/request.ts
1326
1523
  const pendingCalls = /* @__PURE__ */ new Map();
@@ -1422,9 +1619,11 @@ const CONNECTIVITY_TROUBLESHOOTING_LINES = [
1422
1619
  "- Keep the Figma tab active/foreground while using the MCP server."
1423
1620
  ];
1424
1621
  const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
1622
+ function isRecord(value) {
1623
+ return !!value && typeof value === "object" && !Array.isArray(value);
1624
+ }
1425
1625
  function getRecordProperty$1(record, key) {
1426
- if (!record || typeof record !== "object") return;
1427
- return Reflect.get(record, key);
1626
+ return isRecord(record) ? record[key] : void 0;
1428
1627
  }
1429
1628
  function extTool(definition) {
1430
1629
  return definition;
@@ -1440,6 +1639,20 @@ const TOOL_DEFS = [
1440
1639
  target: "extension",
1441
1640
  format: createCodeToolResponse
1442
1641
  }),
1642
+ extTool({
1643
+ name: "get_design_system",
1644
+ description: "Return a compact, query-ranked set of Figma components and variables from the current page/file. Reuse returned ids/keys in apply_canvas.",
1645
+ parameters: GetDesignSystemParametersSchema,
1646
+ target: "extension",
1647
+ format: createDesignSystemToolResponse
1648
+ }),
1649
+ extTool({
1650
+ name: "apply_canvas",
1651
+ description: "Apply one declarative canvas tree. Create adds a FRAME tree; update safely reconciles within targetNodeId, preserving omissions and skipping unchanged values. Requires Canvas writes.",
1652
+ parameters: ApplyCanvasParametersSchema,
1653
+ target: "extension",
1654
+ format: createApplyCanvasToolResponse
1655
+ }),
1443
1656
  extTool({
1444
1657
  name: "get_token_defs",
1445
1658
  description: "Resolve canonical token names to literal values (optionally including all modes) for tokens referenced by get_code.",
@@ -1484,9 +1697,8 @@ function isTempadMcpErrorCode(value) {
1484
1697
  function extractToolErrorMessage(error) {
1485
1698
  if (error instanceof Error) return error.message || "Unknown error occurred.";
1486
1699
  if (typeof error === "string") return error;
1487
- if (error && typeof error === "object") {
1488
- const candidate = error;
1489
- if (typeof candidate.message === "string" && candidate.message.trim()) return candidate.message;
1700
+ if (isRecord(error)) {
1701
+ if (typeof error.message === "string" && error.message.trim()) return error.message;
1490
1702
  }
1491
1703
  return "Unknown error occurred.";
1492
1704
  }
@@ -1514,48 +1726,49 @@ function isSelectionToolError(code, message) {
1514
1726
  return (code ? SELECTION_ERROR_CODES.has(code) : false) || /select exactly one visible node/i.test(message) || /no visible node found/i.test(message);
1515
1727
  }
1516
1728
  function createCodeToolResponse(payload) {
1517
- if (!isCodeResult(payload)) throw new Error("Invalid get_code payload received from extension.");
1518
- return toCallToolResult(buildGetCodeToolResult(payload));
1729
+ return formatToolResult("get_code", payload, isCodeResult, buildGetCodeToolResult);
1730
+ }
1731
+ function createDesignSystemToolResponse(payload) {
1732
+ return formatToolResult("get_design_system", payload, isDesignSystemResult, buildGetDesignSystemToolResult);
1733
+ }
1734
+ function createApplyCanvasToolResponse(payload) {
1735
+ return formatToolResult("apply_canvas", payload, isApplyCanvasResult, buildApplyCanvasToolResult);
1519
1736
  }
1520
1737
  function createStructureToolResponse(payload) {
1521
- if (!isStructureResult(payload)) throw new Error("Invalid get_structure payload received from extension.");
1522
- return toCallToolResult(buildGetStructureToolResult(payload));
1738
+ return formatToolResult("get_structure", payload, isStructureResult, buildGetStructureToolResult);
1523
1739
  }
1524
1740
  function createTokenDefsToolResponse(payload) {
1525
- if (!isTokenDefsResult(payload)) throw new Error("Invalid get_token_defs payload received from extension.");
1526
- return toCallToolResult(buildGetTokenDefsToolResult(payload));
1741
+ return formatToolResult("get_token_defs", payload, isTokenDefsResult, buildGetTokenDefsToolResult);
1527
1742
  }
1528
1743
  function createScreenshotToolResponse(payload) {
1529
- if (!isScreenshotResult(payload)) throw new Error("Invalid get_screenshot payload received from extension.");
1530
- return toCallToolResult(buildGetScreenshotToolResult(payload));
1744
+ return formatToolResult("get_screenshot", payload, isScreenshotResult, buildGetScreenshotToolResult);
1745
+ }
1746
+ function formatToolResult(toolName, payload, isValid, build) {
1747
+ if (!isValid(payload)) throw new Error(`Invalid ${toolName} payload received from extension.`);
1748
+ return toCallToolResult(build(payload));
1531
1749
  }
1532
1750
  function isScreenshotResult(payload) {
1533
- if (typeof payload !== "object" || !payload) return false;
1534
- const candidate = payload;
1535
- return typeof candidate.asset === "object" && candidate.asset !== null && typeof candidate.width === "number" && typeof candidate.height === "number" && typeof candidate.scale === "number" && typeof candidate.bytes === "number" && typeof candidate.format === "string";
1751
+ return isRecord(payload) && isRecord(payload.asset) && typeof payload.width === "number" && typeof payload.height === "number" && typeof payload.scale === "number" && typeof payload.bytes === "number" && typeof payload.format === "string";
1752
+ }
1753
+ function isDesignSystemResult(payload) {
1754
+ return isRecord(payload) && isRecord(payload.page) && Array.isArray(payload.components) && Array.isArray(payload.variables);
1755
+ }
1756
+ function isApplyCanvasResult(payload) {
1757
+ return isRecord(payload) && typeof payload.rootNodeId === "string" && isRecord(payload.nodeIdsByKey) && Array.isArray(payload.createdNodeIds) && Array.isArray(payload.updatedNodeIds) && typeof payload.mutationCount === "number";
1536
1758
  }
1537
1759
  function isCodeResult(payload) {
1538
- if (typeof payload !== "object" || !payload) return false;
1539
- const candidate = payload;
1540
- return typeof candidate.code === "string" && typeof candidate.lang === "string" && (candidate.assets === void 0 || Array.isArray(candidate.assets));
1760
+ return isRecord(payload) && typeof payload.code === "string" && typeof payload.lang === "string" && (payload.assets === void 0 || Array.isArray(payload.assets));
1541
1761
  }
1542
1762
  function isStructureResult(payload) {
1543
- if (typeof payload !== "object" || !payload) return false;
1544
- const candidate = payload;
1545
- return Array.isArray(candidate.roots);
1763
+ return isRecord(payload) && Array.isArray(payload.roots);
1546
1764
  }
1547
1765
  function isTokenDefsResult(payload) {
1548
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
1549
- for (const value of Object.values(payload)) {
1550
- if (!value || typeof value !== "object") return false;
1551
- const token = value;
1552
- if (typeof token.kind !== "string") return false;
1553
- if (token.value === void 0) return false;
1554
- }
1766
+ if (!isRecord(payload)) return false;
1767
+ for (const token of Object.values(payload)) if (!isRecord(token) || typeof token.kind !== "string" || token.value === void 0) return false;
1555
1768
  return true;
1556
1769
  }
1557
1770
  function coercePayloadToToolResponse(payload) {
1558
- if (payload && typeof payload === "object" && Array.isArray(payload.content)) return payload;
1771
+ if (isRecord(payload) && Array.isArray(payload.content)) return payload;
1559
1772
  return { content: [{
1560
1773
  type: "text",
1561
1774
  text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2)
@@ -1578,7 +1791,9 @@ function toCallToolResult(result) {
1578
1791
  }
1579
1792
  function getBudgetRetryGuidance(toolName) {
1580
1793
  switch (toolName) {
1794
+ case "apply_canvas": return "Submit a smaller desired subtree and retry.";
1581
1795
  case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
1796
+ case "get_design_system": return "Use a narrower design-system query and retry.";
1582
1797
  case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
1583
1798
  case "get_token_defs": return "Reduce requested names or split them into smaller batches and retry.";
1584
1799
  case "get_screenshot": return "Reduce selection size or scale and retry.";
@@ -1901,7 +2116,8 @@ function registerLocalTool(mcp, tool) {
1901
2116
  if (tool.outputSchema) registrationOptions.outputSchema = tool.outputSchema;
1902
2117
  const registerHandler = async (args) => {
1903
2118
  try {
1904
- return await handler(schema.parse(args));
2119
+ const parsed = schema.parse(args);
2120
+ return await handler(parsed);
1905
2121
  } catch (error) {
1906
2122
  log.error({
1907
2123
  tool: tool.name,