figme-mcp 1.0.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.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +447 -0
  3. package/dist/cache.d.ts +29 -0
  4. package/dist/cache.js +68 -0
  5. package/dist/fig/bytebuffer.d.ts +31 -0
  6. package/dist/fig/bytebuffer.js +98 -0
  7. package/dist/fig/container.d.ts +32 -0
  8. package/dist/fig/container.js +80 -0
  9. package/dist/fig/imagemeta.d.ts +17 -0
  10. package/dist/fig/imagemeta.js +96 -0
  11. package/dist/fig/invariants.d.ts +10 -0
  12. package/dist/fig/invariants.js +63 -0
  13. package/dist/fig/kiwi.d.ts +38 -0
  14. package/dist/fig/kiwi.js +144 -0
  15. package/dist/fig/parse.d.ts +37 -0
  16. package/dist/fig/parse.js +91 -0
  17. package/dist/fig/zip.d.ts +23 -0
  18. package/dist/fig/zip.js +95 -0
  19. package/dist/mcp/create.d.ts +12 -0
  20. package/dist/mcp/create.js +48 -0
  21. package/dist/mcp/respond.d.ts +76 -0
  22. package/dist/mcp/respond.js +124 -0
  23. package/dist/mcp/server.d.ts +3 -0
  24. package/dist/mcp/server.js +22 -0
  25. package/dist/mcp/tools/blob.d.ts +7 -0
  26. package/dist/mcp/tools/blob.js +55 -0
  27. package/dist/mcp/tools/components.d.ts +7 -0
  28. package/dist/mcp/tools/components.js +54 -0
  29. package/dist/mcp/tools/context.d.ts +24 -0
  30. package/dist/mcp/tools/context.js +48 -0
  31. package/dist/mcp/tools/find.d.ts +7 -0
  32. package/dist/mcp/tools/find.js +97 -0
  33. package/dist/mcp/tools/image.d.ts +6 -0
  34. package/dist/mcp/tools/image.js +100 -0
  35. package/dist/mcp/tools/instance.d.ts +7 -0
  36. package/dist/mcp/tools/instance.js +44 -0
  37. package/dist/mcp/tools/node.d.ts +7 -0
  38. package/dist/mcp/tools/node.js +49 -0
  39. package/dist/mcp/tools/overview.d.ts +7 -0
  40. package/dist/mcp/tools/overview.js +45 -0
  41. package/dist/mcp/tools/render.d.ts +6 -0
  42. package/dist/mcp/tools/render.js +128 -0
  43. package/dist/mcp/tools/style.d.ts +7 -0
  44. package/dist/mcp/tools/style.js +38 -0
  45. package/dist/mcp/tools/text.d.ts +7 -0
  46. package/dist/mcp/tools/text.js +89 -0
  47. package/dist/mcp/tools/tree.d.ts +7 -0
  48. package/dist/mcp/tools/tree.js +100 -0
  49. package/dist/mcp/tools/variables.d.ts +7 -0
  50. package/dist/mcp/tools/variables.js +71 -0
  51. package/dist/model/access.d.ts +28 -0
  52. package/dist/model/access.js +106 -0
  53. package/dist/model/components.d.ts +72 -0
  54. package/dist/model/components.js +157 -0
  55. package/dist/model/index.d.ts +73 -0
  56. package/dist/model/index.js +192 -0
  57. package/dist/model/instance.d.ts +87 -0
  58. package/dist/model/instance.js +208 -0
  59. package/dist/model/summarize.d.ts +83 -0
  60. package/dist/model/summarize.js +541 -0
  61. package/dist/model/text.d.ts +29 -0
  62. package/dist/model/text.js +61 -0
  63. package/dist/model/tree.d.ts +47 -0
  64. package/dist/model/tree.js +89 -0
  65. package/dist/model/variables.d.ts +50 -0
  66. package/dist/model/variables.js +141 -0
  67. package/dist/render/bounds.d.ts +64 -0
  68. package/dist/render/bounds.js +173 -0
  69. package/dist/render/color.d.ts +20 -0
  70. package/dist/render/color.js +41 -0
  71. package/dist/render/effects.d.ts +34 -0
  72. package/dist/render/effects.js +196 -0
  73. package/dist/render/export.d.ts +51 -0
  74. package/dist/render/export.js +573 -0
  75. package/dist/render/index.d.ts +42 -0
  76. package/dist/render/index.js +94 -0
  77. package/dist/render/instance.d.ts +12 -0
  78. package/dist/render/instance.js +72 -0
  79. package/dist/render/matrix.d.ts +46 -0
  80. package/dist/render/matrix.js +94 -0
  81. package/dist/render/node.d.ts +41 -0
  82. package/dist/render/node.js +95 -0
  83. package/dist/render/paint.d.ts +27 -0
  84. package/dist/render/paint.js +301 -0
  85. package/dist/render/path.d.ts +42 -0
  86. package/dist/render/path.js +156 -0
  87. package/dist/render/raster.d.ts +31 -0
  88. package/dist/render/raster.js +69 -0
  89. package/dist/render/report.d.ts +72 -0
  90. package/dist/render/report.js +106 -0
  91. package/dist/render/style.d.ts +31 -0
  92. package/dist/render/style.js +67 -0
  93. package/dist/render/svg.d.ts +60 -0
  94. package/dist/render/svg.js +150 -0
  95. package/dist/render/text.d.ts +50 -0
  96. package/dist/render/text.js +90 -0
  97. package/package.json +47 -0
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared plumbing for tool modules: the file cache handle, argument helpers and uniform error
3
+ * reporting. Tool handlers stay small and never touch bytes directly.
4
+ */
5
+ import { z } from 'zod';
6
+ import { errorResult } from '../respond.js';
7
+ export const fileArg = z
8
+ .string()
9
+ .describe('Path to the .fig / .figma file (absolute, or relative to the server CWD).');
10
+ export const cursorArg = z
11
+ .string()
12
+ .optional()
13
+ .describe('Opaque nextCursor from a previous truncated response; resumes where it stopped.');
14
+ export function load(ctx, file) {
15
+ return ctx.cache.get(file);
16
+ }
17
+ export function requireNode(index, guid) {
18
+ const t = index.node(guid);
19
+ if (!t) {
20
+ throw new Error(`no node with guid ${JSON.stringify(guid)} in this file ` +
21
+ '(guids look like "2:1339"; use fig_find or fig_tree to discover them)');
22
+ }
23
+ return t;
24
+ }
25
+ /** Resolve an optional scope argument to a subtree root, defaulting to the DOCUMENT. */
26
+ export function resolveRoot(index, guid) {
27
+ if (guid)
28
+ return requireNode(index, guid);
29
+ const root = index.root;
30
+ if (!root)
31
+ throw new Error('this file has no DOCUMENT node');
32
+ return root;
33
+ }
34
+ /**
35
+ * Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
36
+ * server, and keeps the message actionable (the thrown text is already user-facing).
37
+ */
38
+ export function handler(fn) {
39
+ return async (args) => {
40
+ try {
41
+ return await fn(args);
42
+ }
43
+ catch (err) {
44
+ const message = err instanceof Error ? err.message : String(err);
45
+ return errorResult(message);
46
+ }
47
+ };
48
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_find` — full-text search over layer names and text content. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_find";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=find.d.ts.map
@@ -0,0 +1,97 @@
1
+ import { z } from 'zod';
2
+ import { cursorArg, fileArg, handler, load, requireNode } from './context.js';
3
+ import { Packer, decodeCursor, encodeCursor, jsonResult, measure } from '../respond.js';
4
+ import { summarize } from '../../model/summarize.js';
5
+ import { breadcrumb } from '../../model/tree.js';
6
+ import { obj, str } from '../../model/access.js';
7
+ export const NAME = 'fig_find';
8
+ export const DESCRIPTION = [
9
+ 'Search a file for nodes by name and by text content (case-insensitive substring), optionally',
10
+ 'restricted to node types and/or a subtree. Each hit comes back with the page it lives on, a',
11
+ 'breadcrumb of ancestor names, and which field matched — so you can jump straight to a guid',
12
+ 'and then call fig_node / fig_style. Omit `query` to list every node of the given types.',
13
+ ].join(' ');
14
+ const DEFAULT_LIMIT = 50;
15
+ const TEXT_PREVIEW = 160;
16
+ export function register(server, ctx) {
17
+ server.registerTool(NAME, {
18
+ title: 'Search layers and text',
19
+ description: DESCRIPTION,
20
+ inputSchema: {
21
+ file: fileArg,
22
+ query: z
23
+ .string()
24
+ .optional()
25
+ .describe('Case-insensitive substring matched against layer names AND text content.'),
26
+ types: z.array(z.string()).optional().describe('Restrict to node types, e.g. ["TEXT"].'),
27
+ scope: z.string().optional().describe('Only search inside this guid subtree.'),
28
+ limit: z.number().int().min(1).max(300).optional().describe(`Default ${DEFAULT_LIMIT}.`),
29
+ cursor: cursorArg,
30
+ },
31
+ annotations: { readOnlyHint: true, openWorldHint: false },
32
+ }, handler((args) => {
33
+ const { index } = load(ctx, args.file);
34
+ if (!args.query && !args.types?.length) {
35
+ throw new Error('fig_find needs at least a `query` or a `types` filter');
36
+ }
37
+ const needle = args.query?.toLowerCase();
38
+ const typeFilter = args.types?.length ? new Set(args.types) : undefined;
39
+ const scope = args.scope ? requireNode(index, args.scope) : undefined;
40
+ const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
41
+ const { after } = decodeCursor(args.cursor);
42
+ const packer = new Packer({ limit: args.limit ?? DEFAULT_LIMIT });
43
+ const entries = index.search();
44
+ let skipping = after !== undefined;
45
+ let lastGuid;
46
+ let totalMatches = 0;
47
+ for (let i = range.start; i < range.end; i++) {
48
+ const e = entries[i];
49
+ if (typeFilter && !typeFilter.has(str(e.t.node, 'type') ?? ''))
50
+ continue;
51
+ let matchedOn;
52
+ if (!needle)
53
+ matchedOn = 'type';
54
+ else if (e.nameLower.includes(needle))
55
+ matchedOn = 'name';
56
+ else if (e.textLower?.includes(needle))
57
+ matchedOn = 'text';
58
+ if (!matchedOn)
59
+ continue;
60
+ totalMatches++;
61
+ if (skipping) {
62
+ if (e.t.key === after)
63
+ skipping = false;
64
+ continue;
65
+ }
66
+ // Keep scanning after the packer fills so `totalMatches` stays exact.
67
+ if (packer.full)
68
+ continue;
69
+ const characters = matchedOn === 'text' ? str(obj(e.t.node, 'textData'), 'characters') : undefined;
70
+ const item = {
71
+ ...summarize(e.t),
72
+ matchedOn,
73
+ page: e.t.page ? str(e.t.page.node, 'name') : undefined,
74
+ path: breadcrumb(e.t) || undefined,
75
+ text: characters && characters.length > TEXT_PREVIEW
76
+ ? `${characters.slice(0, TEXT_PREVIEW)}...`
77
+ : characters,
78
+ };
79
+ if (packer.add(item, measure(item)))
80
+ lastGuid = e.t.key;
81
+ }
82
+ const truncated = packer.truncated;
83
+ return jsonResult({
84
+ query: args.query,
85
+ types: args.types,
86
+ scope: scope?.key,
87
+ totalMatches,
88
+ returned: packer.items.length,
89
+ results: packer.items,
90
+ truncated: truncated || undefined,
91
+ nextCursor: truncated && lastGuid ? encodeCursor({ after: lastGuid }) : undefined,
92
+ hint: truncated
93
+ ? 'more matches available: pass nextCursor, or narrow with types/scope'
94
+ : undefined,
95
+ }, { listKey: 'results' });
96
+ }));
97
+ }
@@ -0,0 +1,6 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type ToolContext } from './context.js';
3
+ export declare const NAME = "fig_image";
4
+ export declare const DESCRIPTION: string;
5
+ export declare function register(server: McpServer, ctx: ToolContext): void;
6
+ //# sourceMappingURL=image.d.ts.map
@@ -0,0 +1,100 @@
1
+ /** `fig_image` — the bitmaps embedded in the file (image fills and the document thumbnail). */
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { fileArg, handler, load, requireNode } from './context.js';
6
+ import { jsonResult } from '../respond.js';
7
+ import { sniffImage } from '../../fig/imagemeta.js';
8
+ import { nodeImageHashes } from '../../model/index.js';
9
+ import { str } from '../../model/access.js';
10
+ export const NAME = 'fig_image';
11
+ export const DESCRIPTION = [
12
+ 'Fetch a bitmap stored inside the .fig: pass `hash` (the 40-hex image id reported by',
13
+ 'fig_node / fig_style on an image paint), or `guid` to take the image(s) used by that node, or',
14
+ 'hash:"thumbnail" for the document preview. Small images come back as viewable image content;',
15
+ 'larger ones come back as metadata (mime, byte size, pixel dimensions) — give `savePath` to',
16
+ 'write the exact bytes to disk instead. NOTE: a .fig contains no rendered pictures of frames,',
17
+ 'only the bitmaps placed in image fills plus thumbnail.png, so this cannot screenshot a design.',
18
+ ].join(' ');
19
+ /** Above this, base64 inlining is more harm than help; the caller gets metadata + savePath. */
20
+ const MAX_INLINE_BYTES = 2 * 1024 * 1024;
21
+ export function register(server, ctx) {
22
+ server.registerTool(NAME, {
23
+ title: 'Embedded image',
24
+ description: DESCRIPTION,
25
+ inputSchema: {
26
+ file: fileArg,
27
+ hash: z
28
+ .string()
29
+ .optional()
30
+ .describe('40-hex image hash, or the literal "thumbnail" for thumbnail.png.'),
31
+ guid: z.string().optional().describe('Node guid; uses the image fills on that node.'),
32
+ savePath: z
33
+ .string()
34
+ .optional()
35
+ .describe('Write the bytes to this path (parent directories are created) instead of inlining.'),
36
+ },
37
+ // Not read-only: savePath writes a file. Nothing is ever written back into the .fig.
38
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
39
+ }, handler((args) => {
40
+ const { fig, index } = load(ctx, args.file);
41
+ const zip = fig.zip;
42
+ if (!zip) {
43
+ throw new Error('this .fig is a bare fig-kiwi stream and carries no embedded image entries');
44
+ }
45
+ let hash = args.hash;
46
+ if (!hash && args.guid) {
47
+ const t = requireNode(index, args.guid);
48
+ const hashes = nodeImageHashes(t.node);
49
+ if (hashes.length === 0) {
50
+ throw new Error(`node ${args.guid} (${str(t.node, 'type') ?? '?'}) has no image fills — ` +
51
+ 'fig_node shows an `images` array on nodes that do');
52
+ }
53
+ if (hashes.length > 1) {
54
+ return jsonResult({
55
+ guid: t.key,
56
+ name: str(t.node, 'name'),
57
+ images: hashes,
58
+ hint: 'this node uses several images; call again with one of these `hash` values',
59
+ });
60
+ }
61
+ hash = hashes[0];
62
+ }
63
+ if (!hash)
64
+ throw new Error('fig_image needs either `hash` or `guid`');
65
+ const entry = hash === 'thumbnail' ? 'thumbnail.png' : `images/${hash}`;
66
+ const bytes = zip.read(entry);
67
+ if (!bytes) {
68
+ throw new Error(`no image "${hash}" in this file (${index.imageHashes.size} hashes are referenced by ` +
69
+ 'paints; use fig_node on a node with an image fill to get one, or hash:"thumbnail")');
70
+ }
71
+ const meta = sniffImage(bytes);
72
+ const payload = {
73
+ hash,
74
+ entry,
75
+ mime: meta.mime,
76
+ byteLength: meta.byteLength,
77
+ width: meta.width,
78
+ height: meta.height,
79
+ };
80
+ if (args.savePath) {
81
+ const abs = path.resolve(args.savePath);
82
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
83
+ fs.writeFileSync(abs, bytes);
84
+ return jsonResult({ ...payload, savedTo: abs, bytesWritten: bytes.length });
85
+ }
86
+ if (bytes.length > MAX_INLINE_BYTES) {
87
+ return jsonResult({
88
+ ...payload,
89
+ inlined: false,
90
+ hint: `image is larger than ${MAX_INLINE_BYTES} bytes; call again with savePath to write it to disk`,
91
+ });
92
+ }
93
+ return {
94
+ content: [
95
+ { type: 'image', data: bytes.toString('base64'), mimeType: meta.mime },
96
+ { type: 'text', text: JSON.stringify({ ...payload, inlined: true }) },
97
+ ],
98
+ };
99
+ }));
100
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_instance` — what one INSTANCE changes relative to its component. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_instance";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=instance.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import { fileArg, handler, load, requireNode } from './context.js';
3
+ import { jsonResult } from '../respond.js';
4
+ import { instanceView } from '../../model/components.js';
5
+ import { str } from '../../model/access.js';
6
+ export const NAME = 'fig_instance';
7
+ export const DESCRIPTION = [
8
+ 'Explain one component INSTANCE: which SYMBOL it points at, its component-property',
9
+ 'assignments with the property names resolved, and every override it applies — each with the',
10
+ 'path down into the component, the node that path addresses, and the fields it changes.',
11
+ 'Use it to see how an instance differs from its component without diffing two subtrees.',
12
+ ].join(' ');
13
+ const MAX_OVERRIDES = 60;
14
+ export function register(server, ctx) {
15
+ server.registerTool(NAME, {
16
+ title: 'Instance overrides',
17
+ description: DESCRIPTION,
18
+ inputSchema: {
19
+ file: fileArg,
20
+ guid: z.string().describe('Guid of an INSTANCE node, e.g. "2:1329".'),
21
+ },
22
+ annotations: { readOnlyHint: true, openWorldHint: false },
23
+ }, handler((args) => {
24
+ const { index } = load(ctx, args.file);
25
+ const t = requireNode(index, args.guid);
26
+ const type = str(t.node, 'type');
27
+ if (type !== 'INSTANCE') {
28
+ throw new Error(`node ${args.guid} is a ${type}, not an INSTANCE — ` +
29
+ 'use fig_node for other node types, or fig_components to list SYMBOLs');
30
+ }
31
+ const { overrides = [], ...instance } = instanceView(index, t);
32
+ const truncated = overrides.length > MAX_OVERRIDES;
33
+ return jsonResult({
34
+ instance,
35
+ overrideCount: overrides.length,
36
+ overrides: truncated ? overrides.slice(0, MAX_OVERRIDES) : overrides,
37
+ truncated: truncated || undefined,
38
+ hint: truncated
39
+ ? `showing the first ${MAX_OVERRIDES} of ${overrides.length} overrides; ` +
40
+ 'use fig_node detail:"raw" on this guid for the complete record'
41
+ : undefined,
42
+ }, { listKey: 'overrides' });
43
+ }));
44
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_node` — inspect exactly one node at a chosen detail level. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_node";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ import { fileArg, handler, load, requireNode } from './context.js';
3
+ import { jsonResult } from '../respond.js';
4
+ import { nodeDetail, nodeRaw, summarize } from '../../model/summarize.js';
5
+ export const NAME = 'fig_node';
6
+ export const DESCRIPTION = [
7
+ 'Inspect one node by guid (e.g. "2:1339").',
8
+ 'detail:"full" (default) gives geometry, fills/strokes/effects as hex colours, corner radii,',
9
+ 'auto-layout, text basics, component and variable links, plus child summaries.',
10
+ 'detail:"raw" returns the decoded Figma record verbatim — the escape hatch for fields this',
11
+ 'server does not map yet; it is limited to one node per call and can be large.',
12
+ ].join(' ');
13
+ export function register(server, ctx) {
14
+ server.registerTool(NAME, {
15
+ title: 'Inspect a node',
16
+ description: DESCRIPTION,
17
+ inputSchema: {
18
+ file: fileArg,
19
+ guid: z.string().describe('Node guid, "sessionID:localID", e.g. "2:1339".'),
20
+ detail: z.enum(['summary', 'full', 'raw']).optional().describe('Default "full".'),
21
+ includeChildren: z
22
+ .boolean()
23
+ .optional()
24
+ .describe('Include summaries of direct children (default true).'),
25
+ },
26
+ annotations: { readOnlyHint: true, openWorldHint: false },
27
+ }, handler((args) => {
28
+ const { index } = load(ctx, args.file);
29
+ const t = requireNode(index, args.guid);
30
+ const detail = args.detail ?? 'full';
31
+ const includeChildren = args.includeChildren !== false;
32
+ if (detail === 'summary') {
33
+ return jsonResult({ detail, node: summarize(t, { page: true }) });
34
+ }
35
+ if (detail === 'raw') {
36
+ // §5.2: never more than one raw node per call.
37
+ return jsonResult({
38
+ detail,
39
+ node: nodeRaw(t),
40
+ children: includeChildren ? t.children.map((c) => summarize(c)) : undefined,
41
+ note: 'raw = the decoded NodeChange as stored in the file; bytes are hex, int64 are strings',
42
+ });
43
+ }
44
+ return jsonResult({
45
+ detail,
46
+ node: nodeDetail(index, t, { children: includeChildren }),
47
+ });
48
+ }));
49
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_overview` — parse (or hit the cache) and orient: counts, pages, warnings. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_overview";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=overview.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { fileArg, handler, load } from './context.js';
2
+ import { jsonResult } from '../respond.js';
3
+ import { str } from '../../model/access.js';
4
+ export const NAME = 'fig_overview';
5
+ export const DESCRIPTION = [
6
+ 'Open a local Figma .fig file and summarise it: document name, export date, node counts by',
7
+ 'type, the page list, and how many components / variables / images it holds.',
8
+ 'START HERE. Then fig_tree a page, then fig_node / fig_style on interesting guids;',
9
+ 'fig_find jumps straight to a name or a piece of text. Everything is read-only and offline.',
10
+ ].join(' ');
11
+ export function register(server, ctx) {
12
+ server.registerTool(NAME, {
13
+ title: 'Figma file overview',
14
+ description: DESCRIPTION,
15
+ inputSchema: { file: fileArg },
16
+ annotations: { readOnlyHint: true, openWorldHint: false },
17
+ }, handler(({ file }) => {
18
+ const { fig, index, path } = load(ctx, file);
19
+ const counts = Object.fromEntries(Object.entries(index.typeCounts).sort((a, b) => b[1] - a[1]));
20
+ return jsonResult({
21
+ file: path,
22
+ name: fig.meta?.file_name,
23
+ exportedAt: fig.meta?.exported_at,
24
+ container: fig.container,
25
+ formatVersion: fig.version,
26
+ nodes: index.nodeCount,
27
+ pages: index.pages.map((p) => ({
28
+ guid: p.key,
29
+ name: str(p.node, 'name'),
30
+ children: p.children.length,
31
+ })),
32
+ nodeTypes: counts,
33
+ components: index.symbols.length,
34
+ variables: index.variables.length,
35
+ variableSets: index.variableSets.length,
36
+ images: index.imageHashes.size,
37
+ blobs: fig.blobs.length,
38
+ textNodes: index.textNodeCount,
39
+ orphans: index.tree.orphans.length,
40
+ warnings: fig.warnings.length ? fig.warnings : undefined,
41
+ parseMs: Math.round(fig.parseMs),
42
+ nextSteps: 'fig_tree { root: <page guid>, format: "outline" } to explore a page',
43
+ });
44
+ }));
45
+ }
@@ -0,0 +1,6 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type ToolContext } from './context.js';
3
+ export declare const NAME = "fig_render";
4
+ export declare const DESCRIPTION: string;
5
+ export declare function register(server: McpServer, ctx: ToolContext): void;
6
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1,128 @@
1
+ /** `fig_render` — a picture of any node, rendered entirely from the file's own data. */
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { fileArg, handler, load } from './context.js';
6
+ import { jsonResult, textResult, HARD_CAP } from '../respond.js';
7
+ import { DEFAULT_MAX_SIZE, DEFAULT_SCALE, HARD_MAX_SIZE, renderNode, } from '../../render/index.js';
8
+ import { HARD_MAX_NODES } from '../../render/export.js';
9
+ export const NAME = 'fig_render';
10
+ export const DESCRIPTION = [
11
+ 'Render a node — frame, component, instance, group, shape, text, or a whole page — to a PNG',
12
+ 'the model can look at, or to SVG. Fully offline: geometry, text outlines and images all come',
13
+ 'from the file. Rendering is best-effort: read `approximated` and `unsupported` in the report',
14
+ 'before trusting fine details; exact values remain available from fig_node / fig_style /',
15
+ 'fig_text. Default output is PNG at 2x, capped to 1568 px on the longest edge; use `savePath`',
16
+ 'to write a file instead of inlining it.',
17
+ ].join(' ');
18
+ /** Above this, base64 inlining costs the caller more than it is worth. */
19
+ const MAX_INLINE_PNG = 2 * 1024 * 1024;
20
+ /** An SVG longer than this must go to disk rather than into the conversation. */
21
+ const MAX_INLINE_SVG = 50_000;
22
+ /** Keep the JSON block well inside the response budget. */
23
+ const MAX_FEATURE_ENTRIES = 20;
24
+ /** The report as the tool returns it: capped, and without the tester-only feature list. */
25
+ function toolReport(report, extra = {}) {
26
+ const { featuresPresent: _ignored, ...rest } = report;
27
+ return {
28
+ ...rest,
29
+ unsupported: report.unsupported.slice(0, MAX_FEATURE_ENTRIES),
30
+ approximated: report.approximated.slice(0, MAX_FEATURE_ENTRIES),
31
+ ...extra,
32
+ };
33
+ }
34
+ function write(savePath, data) {
35
+ const abs = path.resolve(savePath);
36
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
37
+ fs.writeFileSync(abs, typeof data === 'string' ? data : Buffer.from(data));
38
+ return abs;
39
+ }
40
+ export function register(server, ctx) {
41
+ server.registerTool(NAME, {
42
+ title: 'Render a node to an image',
43
+ description: DESCRIPTION,
44
+ inputSchema: {
45
+ file: fileArg,
46
+ guid: z
47
+ .string()
48
+ .describe('Node to render, e.g. "2:1339". A page guid renders the whole page, downscaled to fit maxSize.'),
49
+ format: z
50
+ .enum(['png', 'svg'])
51
+ .optional()
52
+ .describe('Default "png". Falls back to SVG text when the optional rasterizer is not installed.'),
53
+ scale: z
54
+ .number()
55
+ .min(0.1)
56
+ .max(4)
57
+ .optional()
58
+ .describe(`Device scale factor. Default ${DEFAULT_SCALE}. Lowered automatically to respect maxSize.`),
59
+ maxSize: z
60
+ .number()
61
+ .int()
62
+ .min(64)
63
+ .max(HARD_MAX_SIZE)
64
+ .optional()
65
+ .describe(`Longest edge in pixels. Default ${DEFAULT_MAX_SIZE}.`),
66
+ background: z
67
+ .enum(['transparent', 'page'])
68
+ .optional()
69
+ .describe('Default "transparent". "page" fills with the page background colour.'),
70
+ savePath: z
71
+ .string()
72
+ .optional()
73
+ .describe('Write the PNG/SVG to this path (directories are created) instead of inlining it. ' +
74
+ `Required when the PNG exceeds ${MAX_INLINE_PNG} bytes or the SVG exceeds ${MAX_INLINE_SVG} characters.`),
75
+ maxNodes: z
76
+ .number()
77
+ .int()
78
+ .min(1)
79
+ .max(HARD_MAX_NODES)
80
+ .optional()
81
+ .describe('Refuse subtrees larger than this. Default 20000.'),
82
+ },
83
+ // Not read-only: savePath writes a file. Nothing is ever written back into the .fig.
84
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
85
+ }, handler(async (args) => {
86
+ const entry = load(ctx, args.file);
87
+ const result = await renderNode(entry, args.guid, {
88
+ scale: args.scale,
89
+ maxSize: args.maxSize,
90
+ background: args.background,
91
+ maxNodes: args.maxNodes,
92
+ format: args.format ?? 'png',
93
+ });
94
+ const wantSvg = args.format === 'svg' || result.rasterizerMissing || !result.png;
95
+ if (wantSvg) {
96
+ if (args.savePath) {
97
+ const savedTo = write(args.savePath, result.svg);
98
+ return jsonResult(toolReport(result.report, { format: 'svg', savedTo, bytesWritten: result.svg.length }));
99
+ }
100
+ if (result.svg.length > Math.min(MAX_INLINE_SVG, HARD_CAP)) {
101
+ return jsonResult(toolReport(result.report, {
102
+ format: 'svg',
103
+ inlined: false,
104
+ hint: `the SVG is ${result.svg.length} characters; call again with savePath to write it to disk`,
105
+ }));
106
+ }
107
+ return textResult(result.svg);
108
+ }
109
+ const png = result.png;
110
+ if (args.savePath) {
111
+ const savedTo = write(args.savePath, png);
112
+ return jsonResult(toolReport(result.report, { format: 'png', savedTo, bytesWritten: png.length }));
113
+ }
114
+ if (png.length > MAX_INLINE_PNG) {
115
+ return jsonResult(toolReport(result.report, {
116
+ format: 'png',
117
+ inlined: false,
118
+ hint: `the PNG is ${png.length} bytes; lower scale or maxSize, or call again with savePath`,
119
+ }));
120
+ }
121
+ return {
122
+ content: [
123
+ { type: 'image', data: Buffer.from(png).toString('base64'), mimeType: 'image/png' },
124
+ { type: 'text', text: JSON.stringify(toolReport(result.report, { format: 'png' })) },
125
+ ],
126
+ };
127
+ }));
128
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_style` — the resolved, code-generation-oriented style of one node. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_style";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=style.d.ts.map
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ import { fileArg, handler, load, requireNode } from './context.js';
3
+ import { jsonResult } from '../respond.js';
4
+ import { styleBlock } from '../../model/summarize.js';
5
+ import { textView } from '../../model/text.js';
6
+ import { str } from '../../model/access.js';
7
+ export const NAME = 'fig_style';
8
+ export const DESCRIPTION = [
9
+ 'The flattened style of one node, shaped for writing code: hex fills / strokes / effects,',
10
+ 'corner radii, typography, and auto-layout translated into CSS flexbox terms',
11
+ '(display, direction, gap, padding, justifyContent, alignItems, sizing) plus how the node',
12
+ 'behaves inside its parent layout (flexGrow, alignSelf, margin).',
13
+ 'Shared styles and variable bindings are named whenever they resolve inside this file.',
14
+ ].join(' ');
15
+ export function register(server, ctx) {
16
+ server.registerTool(NAME, {
17
+ title: 'Resolved style of a node',
18
+ description: DESCRIPTION,
19
+ inputSchema: {
20
+ file: fileArg,
21
+ guid: z.string().describe('Node guid, e.g. "2:1339".'),
22
+ includeRuns: z
23
+ .boolean()
24
+ .optional()
25
+ .describe('For TEXT nodes, also return styled runs (default false).'),
26
+ },
27
+ annotations: { readOnlyHint: true, openWorldHint: false },
28
+ }, handler((args) => {
29
+ const { index } = load(ctx, args.file);
30
+ const t = requireNode(index, args.guid);
31
+ const style = styleBlock(index, t);
32
+ const text = str(t.node, 'type') === 'TEXT' ? textView(index, t, args.includeRuns === true) : undefined;
33
+ return jsonResult({
34
+ style,
35
+ text: text ? { characters: text.characters, runs: text.runs } : undefined,
36
+ });
37
+ }));
38
+ }
@@ -0,0 +1,7 @@
1
+ /** `fig_text` — copy inventory, optionally with per-character styled runs. */
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { type ToolContext } from './context.js';
4
+ export declare const NAME = "fig_text";
5
+ export declare const DESCRIPTION: string;
6
+ export declare function register(server: McpServer, ctx: ToolContext): void;
7
+ //# sourceMappingURL=text.d.ts.map