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.
- package/LICENSE +21 -0
- package/README.md +447 -0
- package/dist/cache.d.ts +29 -0
- package/dist/cache.js +68 -0
- package/dist/fig/bytebuffer.d.ts +31 -0
- package/dist/fig/bytebuffer.js +98 -0
- package/dist/fig/container.d.ts +32 -0
- package/dist/fig/container.js +80 -0
- package/dist/fig/imagemeta.d.ts +17 -0
- package/dist/fig/imagemeta.js +96 -0
- package/dist/fig/invariants.d.ts +10 -0
- package/dist/fig/invariants.js +63 -0
- package/dist/fig/kiwi.d.ts +38 -0
- package/dist/fig/kiwi.js +144 -0
- package/dist/fig/parse.d.ts +37 -0
- package/dist/fig/parse.js +91 -0
- package/dist/fig/zip.d.ts +23 -0
- package/dist/fig/zip.js +95 -0
- package/dist/mcp/create.d.ts +12 -0
- package/dist/mcp/create.js +48 -0
- package/dist/mcp/respond.d.ts +76 -0
- package/dist/mcp/respond.js +124 -0
- package/dist/mcp/server.d.ts +3 -0
- package/dist/mcp/server.js +22 -0
- package/dist/mcp/tools/blob.d.ts +7 -0
- package/dist/mcp/tools/blob.js +55 -0
- package/dist/mcp/tools/components.d.ts +7 -0
- package/dist/mcp/tools/components.js +54 -0
- package/dist/mcp/tools/context.d.ts +24 -0
- package/dist/mcp/tools/context.js +48 -0
- package/dist/mcp/tools/find.d.ts +7 -0
- package/dist/mcp/tools/find.js +97 -0
- package/dist/mcp/tools/image.d.ts +6 -0
- package/dist/mcp/tools/image.js +100 -0
- package/dist/mcp/tools/instance.d.ts +7 -0
- package/dist/mcp/tools/instance.js +44 -0
- package/dist/mcp/tools/node.d.ts +7 -0
- package/dist/mcp/tools/node.js +49 -0
- package/dist/mcp/tools/overview.d.ts +7 -0
- package/dist/mcp/tools/overview.js +45 -0
- package/dist/mcp/tools/render.d.ts +6 -0
- package/dist/mcp/tools/render.js +128 -0
- package/dist/mcp/tools/style.d.ts +7 -0
- package/dist/mcp/tools/style.js +38 -0
- package/dist/mcp/tools/text.d.ts +7 -0
- package/dist/mcp/tools/text.js +89 -0
- package/dist/mcp/tools/tree.d.ts +7 -0
- package/dist/mcp/tools/tree.js +100 -0
- package/dist/mcp/tools/variables.d.ts +7 -0
- package/dist/mcp/tools/variables.js +71 -0
- package/dist/model/access.d.ts +28 -0
- package/dist/model/access.js +106 -0
- package/dist/model/components.d.ts +72 -0
- package/dist/model/components.js +157 -0
- package/dist/model/index.d.ts +73 -0
- package/dist/model/index.js +192 -0
- package/dist/model/instance.d.ts +87 -0
- package/dist/model/instance.js +208 -0
- package/dist/model/summarize.d.ts +83 -0
- package/dist/model/summarize.js +541 -0
- package/dist/model/text.d.ts +29 -0
- package/dist/model/text.js +61 -0
- package/dist/model/tree.d.ts +47 -0
- package/dist/model/tree.js +89 -0
- package/dist/model/variables.d.ts +50 -0
- package/dist/model/variables.js +141 -0
- package/dist/render/bounds.d.ts +64 -0
- package/dist/render/bounds.js +173 -0
- package/dist/render/color.d.ts +20 -0
- package/dist/render/color.js +41 -0
- package/dist/render/effects.d.ts +34 -0
- package/dist/render/effects.js +196 -0
- package/dist/render/export.d.ts +51 -0
- package/dist/render/export.js +573 -0
- package/dist/render/index.d.ts +42 -0
- package/dist/render/index.js +94 -0
- package/dist/render/instance.d.ts +12 -0
- package/dist/render/instance.js +72 -0
- package/dist/render/matrix.d.ts +46 -0
- package/dist/render/matrix.js +94 -0
- package/dist/render/node.d.ts +41 -0
- package/dist/render/node.js +95 -0
- package/dist/render/paint.d.ts +27 -0
- package/dist/render/paint.js +301 -0
- package/dist/render/path.d.ts +42 -0
- package/dist/render/path.js +156 -0
- package/dist/render/raster.d.ts +31 -0
- package/dist/render/raster.js +69 -0
- package/dist/render/report.d.ts +72 -0
- package/dist/render/report.js +106 -0
- package/dist/render/style.d.ts +31 -0
- package/dist/render/style.js +67 -0
- package/dist/render/svg.d.ts +60 -0
- package/dist/render/svg.js +150 -0
- package/dist/render/text.d.ts +50 -0
- package/dist/render/text.js +90 -0
- package/package.json +47 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* parseFig — the whole Stage A→D pipeline in one call (fig-reading-solution.md §0).
|
|
3
|
+
*
|
|
4
|
+
* Layer 1 boundary: this module knows bytes, chunks and Kiwi. It knows nothing about frames,
|
|
5
|
+
* paints or auto-layout — that lives in ../model.
|
|
6
|
+
*/
|
|
7
|
+
import { openContainer, readFigStream, decompressChunk } from './container.js';
|
|
8
|
+
import { decodeBinarySchema, makeDecoder } from './kiwi.js';
|
|
9
|
+
import { checkInvariants } from './invariants.js';
|
|
10
|
+
function chunkContext(index, raw, codec) {
|
|
11
|
+
const magic = [...raw.subarray(0, 4)].map((b) => b.toString(16).padStart(2, '0')).join(' ');
|
|
12
|
+
const what = index === 0 ? 'Kiwi schema' : 'Message data';
|
|
13
|
+
return (`failed to decode the ${what} (chunk ${index}, ${raw.length} bytes, ` +
|
|
14
|
+
`codec sniffed as ${codec}, first bytes ${magic || '<empty>'})`);
|
|
15
|
+
}
|
|
16
|
+
export function parseFig(buf, opts = {}) {
|
|
17
|
+
const started = performance.now();
|
|
18
|
+
const warnings = [];
|
|
19
|
+
const container = openContainer(buf);
|
|
20
|
+
const { version, chunks } = readFigStream(container.stream);
|
|
21
|
+
const chunkInfos = [];
|
|
22
|
+
const schemaChunk = decompressChunk(chunks[0]);
|
|
23
|
+
chunkInfos.push({
|
|
24
|
+
index: 0,
|
|
25
|
+
compressedSize: chunks[0].length,
|
|
26
|
+
size: schemaChunk.data.length,
|
|
27
|
+
codec: schemaChunk.codec,
|
|
28
|
+
});
|
|
29
|
+
const dataChunk = decompressChunk(chunks[1]);
|
|
30
|
+
chunkInfos.push({
|
|
31
|
+
index: 1,
|
|
32
|
+
compressedSize: chunks[1].length,
|
|
33
|
+
size: dataChunk.data.length,
|
|
34
|
+
codec: dataChunk.codec,
|
|
35
|
+
});
|
|
36
|
+
// Further chunks may exist in other files: record them, never fail on them.
|
|
37
|
+
for (let i = 2; i < chunks.length; i++) {
|
|
38
|
+
chunkInfos.push({
|
|
39
|
+
index: i,
|
|
40
|
+
compressedSize: chunks[i].length,
|
|
41
|
+
size: -1,
|
|
42
|
+
codec: 'stored',
|
|
43
|
+
});
|
|
44
|
+
warnings.push(`chunk ${i} present and ignored (${chunks[i].length} compressed bytes)`);
|
|
45
|
+
}
|
|
46
|
+
// A chunk that matches no known codec is passed through as "stored"; if that guess is wrong
|
|
47
|
+
// the decode below fails. Re-throw with the codec and the chunk's first bytes so a future
|
|
48
|
+
// compression change is a one-line diagnosis rather than a mystery (solution doc §3, §12).
|
|
49
|
+
let schema;
|
|
50
|
+
try {
|
|
51
|
+
schema = decodeBinarySchema(schemaChunk.data);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
throw new Error(`${chunkContext(0, chunks[0], schemaChunk.codec)}: ${err.message}`);
|
|
55
|
+
}
|
|
56
|
+
let message;
|
|
57
|
+
try {
|
|
58
|
+
message = makeDecoder(schema).decode('Message', dataChunk.data);
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
throw new Error(`${chunkContext(1, chunks[1], dataChunk.codec)}: ${err.message}`);
|
|
62
|
+
}
|
|
63
|
+
const nodeChanges = (message['nodeChanges'] ?? []);
|
|
64
|
+
const blobs = (message['blobs'] ?? []);
|
|
65
|
+
let meta;
|
|
66
|
+
const metaBytes = container.zip?.read('meta.json');
|
|
67
|
+
if (metaBytes) {
|
|
68
|
+
try {
|
|
69
|
+
meta = JSON.parse(metaBytes.toString('utf8'));
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
warnings.push(`meta.json is not valid JSON: ${err.message}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const parsed = {
|
|
76
|
+
container: container.kind,
|
|
77
|
+
zip: container.zip,
|
|
78
|
+
meta,
|
|
79
|
+
version,
|
|
80
|
+
chunks: chunkInfos,
|
|
81
|
+
schema,
|
|
82
|
+
message,
|
|
83
|
+
nodeChanges,
|
|
84
|
+
blobs,
|
|
85
|
+
warnings,
|
|
86
|
+
parseMs: performance.now() - started,
|
|
87
|
+
};
|
|
88
|
+
if (opts.checkInvariants !== false)
|
|
89
|
+
warnings.push(...checkInvariants(parsed));
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare const ZIP_MAGIC = 67324752;
|
|
2
|
+
export interface ZipEntry {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
/** 0 = stored, 8 = raw deflate. */
|
|
5
|
+
readonly method: number;
|
|
6
|
+
readonly compressedSize: number;
|
|
7
|
+
readonly uncompressedSize: number;
|
|
8
|
+
readonly dataOffset: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function looksLikeZip(buf: Buffer): boolean;
|
|
11
|
+
export declare class ZipArchive {
|
|
12
|
+
private readonly buf;
|
|
13
|
+
private readonly entries;
|
|
14
|
+
private readonly cache;
|
|
15
|
+
constructor(buf: Buffer);
|
|
16
|
+
get size(): number;
|
|
17
|
+
names(): string[];
|
|
18
|
+
has(name: string): boolean;
|
|
19
|
+
entry(name: string): ZipEntry | undefined;
|
|
20
|
+
/** Decompressed bytes of one entry, or undefined when the entry does not exist. */
|
|
21
|
+
read(name: string): Buffer | undefined;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=zip.d.ts.map
|
package/dist/fig/zip.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal ZIP reader driven by the central directory (fig-reading-solution.md §1).
|
|
3
|
+
*
|
|
4
|
+
* Figma writes entries with the data-descriptor flag set, so local headers carry ZERO for the
|
|
5
|
+
* CRC and both sizes; the real sizes only exist in the central directory. Reading local headers
|
|
6
|
+
* for sizes therefore silently yields empty entries. Entry payloads are decompressed lazily and
|
|
7
|
+
* memoised so a 39 MB archive with 250 image entries costs nothing until an entry is asked for.
|
|
8
|
+
*/
|
|
9
|
+
import * as zlib from 'node:zlib';
|
|
10
|
+
const SIG_LOCAL = 0x04034b50; // PK\x03\x04
|
|
11
|
+
const SIG_CENTRAL = 0x02014b50; // PK\x01\x02
|
|
12
|
+
const SIG_EOCD = 0x06054b50; // PK\x05\x06
|
|
13
|
+
const EOCD_MAX_SCAN = 65558; // 22-byte EOCD + 65535-byte max comment + slack
|
|
14
|
+
export const ZIP_MAGIC = SIG_LOCAL;
|
|
15
|
+
export function looksLikeZip(buf) {
|
|
16
|
+
return buf.length >= 4 && buf.readUInt32LE(0) === SIG_LOCAL;
|
|
17
|
+
}
|
|
18
|
+
export class ZipArchive {
|
|
19
|
+
buf;
|
|
20
|
+
entries = new Map();
|
|
21
|
+
cache = new Map();
|
|
22
|
+
constructor(buf) {
|
|
23
|
+
this.buf = buf;
|
|
24
|
+
const eocd = findEocd(buf);
|
|
25
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
26
|
+
let p = buf.readUInt32LE(eocd + 16);
|
|
27
|
+
for (let i = 0; i < count; i++) {
|
|
28
|
+
if (p + 46 > buf.length)
|
|
29
|
+
throw new Error(`ZIP: central directory entry ${i} out of range`);
|
|
30
|
+
if (buf.readUInt32LE(p) !== SIG_CENTRAL) {
|
|
31
|
+
throw new Error(`ZIP: bad central directory entry ${i} at ${p} (signature ${hex32(buf.readUInt32LE(p))})`);
|
|
32
|
+
}
|
|
33
|
+
const method = buf.readUInt16LE(p + 10);
|
|
34
|
+
const compressedSize = buf.readUInt32LE(p + 20);
|
|
35
|
+
const uncompressedSize = buf.readUInt32LE(p + 24);
|
|
36
|
+
const nameLen = buf.readUInt16LE(p + 28);
|
|
37
|
+
const extraLen = buf.readUInt16LE(p + 30);
|
|
38
|
+
const commentLen = buf.readUInt16LE(p + 32);
|
|
39
|
+
const localOff = buf.readUInt32LE(p + 42);
|
|
40
|
+
const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
|
|
41
|
+
if (localOff + 30 > buf.length)
|
|
42
|
+
throw new Error(`ZIP: local header of "${name}" out of range`);
|
|
43
|
+
if (buf.readUInt32LE(localOff) !== SIG_LOCAL) {
|
|
44
|
+
throw new Error(`ZIP: "${name}" has no local header at ${localOff}`);
|
|
45
|
+
}
|
|
46
|
+
// The local header's own name/extra lengths differ from the central ones in real Figma
|
|
47
|
+
// archives, so the data offset must be computed from the LOCAL header.
|
|
48
|
+
const dataOffset = localOff + 30 + buf.readUInt16LE(localOff + 26) + buf.readUInt16LE(localOff + 28);
|
|
49
|
+
this.entries.set(name, { name, method, compressedSize, uncompressedSize, dataOffset });
|
|
50
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
get size() {
|
|
54
|
+
return this.entries.size;
|
|
55
|
+
}
|
|
56
|
+
names() {
|
|
57
|
+
return [...this.entries.keys()];
|
|
58
|
+
}
|
|
59
|
+
has(name) {
|
|
60
|
+
return this.entries.has(name);
|
|
61
|
+
}
|
|
62
|
+
entry(name) {
|
|
63
|
+
return this.entries.get(name);
|
|
64
|
+
}
|
|
65
|
+
/** Decompressed bytes of one entry, or undefined when the entry does not exist. */
|
|
66
|
+
read(name) {
|
|
67
|
+
const cached = this.cache.get(name);
|
|
68
|
+
if (cached)
|
|
69
|
+
return cached;
|
|
70
|
+
const e = this.entries.get(name);
|
|
71
|
+
if (!e)
|
|
72
|
+
return undefined;
|
|
73
|
+
const raw = this.buf.subarray(e.dataOffset, e.dataOffset + e.compressedSize);
|
|
74
|
+
let out;
|
|
75
|
+
if (e.method === 0)
|
|
76
|
+
out = raw;
|
|
77
|
+
else if (e.method === 8)
|
|
78
|
+
out = zlib.inflateRawSync(raw);
|
|
79
|
+
else
|
|
80
|
+
throw new Error(`ZIP: "${name}" uses unsupported compression method ${e.method}`);
|
|
81
|
+
this.cache.set(name, out);
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function findEocd(buf) {
|
|
86
|
+
const min = Math.max(0, buf.length - EOCD_MAX_SCAN);
|
|
87
|
+
for (let i = buf.length - 22; i >= min; i--) {
|
|
88
|
+
if (buf.readUInt32LE(i) === SIG_EOCD)
|
|
89
|
+
return i;
|
|
90
|
+
}
|
|
91
|
+
throw new Error('ZIP: end-of-central-directory signature (50 4B 05 06) not found');
|
|
92
|
+
}
|
|
93
|
+
function hex32(v) {
|
|
94
|
+
return `0x${(v >>> 0).toString(16).padStart(8, '0')}`;
|
|
95
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server factory, kept separate from the stdio entry point so tests (and any other transport)
|
|
3
|
+
* can build a fully-registered server without connecting to a process's stdin/stdout.
|
|
4
|
+
*/
|
|
5
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
|
+
import type { ToolContext } from './tools/context.js';
|
|
7
|
+
export declare const SERVER_NAME = "figme";
|
|
8
|
+
export declare const SERVER_VERSION = "1.0.0";
|
|
9
|
+
export declare const INSTRUCTIONS: string;
|
|
10
|
+
export declare function createServer(ctx: ToolContext): McpServer;
|
|
11
|
+
export declare function createContext(maxFiles?: number): ToolContext;
|
|
12
|
+
//# sourceMappingURL=create.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server factory, kept separate from the stdio entry point so tests (and any other transport)
|
|
3
|
+
* can build a fully-registered server without connecting to a process's stdin/stdout.
|
|
4
|
+
*/
|
|
5
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
|
+
import { FileCache } from '../cache.js';
|
|
7
|
+
import * as overview from './tools/overview.js';
|
|
8
|
+
import * as tree from './tools/tree.js';
|
|
9
|
+
import * as node from './tools/node.js';
|
|
10
|
+
import * as find from './tools/find.js';
|
|
11
|
+
import * as text from './tools/text.js';
|
|
12
|
+
import * as style from './tools/style.js';
|
|
13
|
+
import * as components from './tools/components.js';
|
|
14
|
+
import * as instance from './tools/instance.js';
|
|
15
|
+
import * as variables from './tools/variables.js';
|
|
16
|
+
import * as image from './tools/image.js';
|
|
17
|
+
import * as blob from './tools/blob.js';
|
|
18
|
+
import * as render from './tools/render.js';
|
|
19
|
+
export const SERVER_NAME = 'figme';
|
|
20
|
+
export const SERVER_VERSION = '1.0.0';
|
|
21
|
+
export const INSTRUCTIONS = [
|
|
22
|
+
'Read-only access to local Figma .fig / .figma files. No Figma account, API or network is',
|
|
23
|
+
'used, and nothing is ever written back to the file.',
|
|
24
|
+
'',
|
|
25
|
+
'Workflow: fig_overview (counts + pages) -> fig_tree on a page (format:"outline" is densest)',
|
|
26
|
+
'-> fig_node / fig_style on interesting guids. fig_find jumps to a name or a string of copy.',
|
|
27
|
+
'fig_text extracts copy, fig_components / fig_instance cover the design system, fig_variables',
|
|
28
|
+
'lists tokens, fig_image returns bitmaps, fig_blob exposes raw vector payloads.',
|
|
29
|
+
'',
|
|
30
|
+
'fig_render returns a picture of any node - the fastest way to understand a frame. Always',
|
|
31
|
+
'check its approximated/unsupported lists before trusting fine visual detail.',
|
|
32
|
+
'',
|
|
33
|
+
'Node guids are "sessionID:localID" strings such as "2:1339". Responses are budgeted: when one',
|
|
34
|
+
'is cut you get truncated:true plus an opaque nextCursor to pass back.',
|
|
35
|
+
].join('\n');
|
|
36
|
+
export function createServer(ctx) {
|
|
37
|
+
const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: INSTRUCTIONS });
|
|
38
|
+
const tools = [
|
|
39
|
+
overview, tree, node, find, text, style, components, instance, variables, image, blob, render,
|
|
40
|
+
];
|
|
41
|
+
for (const mod of tools) {
|
|
42
|
+
mod.register(server, ctx);
|
|
43
|
+
}
|
|
44
|
+
return server;
|
|
45
|
+
}
|
|
46
|
+
export function createContext(maxFiles = 4) {
|
|
47
|
+
return { cache: new FileCache(maxFiles) };
|
|
48
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response budgeting (plan §5) — the single place that decides how much a tool may return.
|
|
3
|
+
*
|
|
4
|
+
* A 116k-node document must stay explorable without ever flooding the agent's context, so:
|
|
5
|
+
* 1. every response has a character budget (default 20k, hard cap 50k);
|
|
6
|
+
* 2. no response carries more than 300 nodes;
|
|
7
|
+
* 3. anything cut sets `truncated: true` and returns an opaque `nextCursor` plus a hint.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEFAULT_BUDGET = 20000;
|
|
10
|
+
export declare const HARD_CAP = 50000;
|
|
11
|
+
export declare const MAX_NODES = 300;
|
|
12
|
+
/**
|
|
13
|
+
* Room left for the response envelope (root summary, counts, cursor, hint) so the SERIALIZED
|
|
14
|
+
* response — not just its item list — stays inside DEFAULT_BUDGET.
|
|
15
|
+
*/
|
|
16
|
+
export declare const ENVELOPE_RESERVE = 1500;
|
|
17
|
+
export interface CallToolResult {
|
|
18
|
+
content: ({
|
|
19
|
+
type: 'text';
|
|
20
|
+
text: string;
|
|
21
|
+
} | {
|
|
22
|
+
type: 'image';
|
|
23
|
+
data: string;
|
|
24
|
+
mimeType: string;
|
|
25
|
+
})[];
|
|
26
|
+
isError?: boolean;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Opaque resume token. The shape is deliberately private to this module. */
|
|
30
|
+
export interface Cursor {
|
|
31
|
+
/** Resume immediately after this guid, in tree (DFS pre-order) order. */
|
|
32
|
+
after?: string;
|
|
33
|
+
/** Resume at this absolute offset, for lists that are not node-ordered. */
|
|
34
|
+
offset?: number;
|
|
35
|
+
}
|
|
36
|
+
export declare function encodeCursor(c: Cursor): string;
|
|
37
|
+
export declare function decodeCursor(s: string | undefined): Cursor;
|
|
38
|
+
export interface PackOptions {
|
|
39
|
+
/** Character budget for the packed items alone (default DEFAULT_BUDGET - ENVELOPE_RESERVE). */
|
|
40
|
+
budget?: number;
|
|
41
|
+
/** Hard node/item ceiling (default MAX_NODES). */
|
|
42
|
+
maxItems?: number;
|
|
43
|
+
/** Caller-requested ceiling, clamped to maxItems. */
|
|
44
|
+
limit?: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Incremental accumulator: callers push items in a stable order and stop as soon as `add`
|
|
48
|
+
* returns false. That keeps truncation deterministic and lets a cursor resume exactly where the
|
|
49
|
+
* previous response stopped.
|
|
50
|
+
*/
|
|
51
|
+
export declare class Packer<T> {
|
|
52
|
+
readonly items: T[];
|
|
53
|
+
truncated: boolean;
|
|
54
|
+
reason: 'budget' | 'items' | 'limit' | undefined;
|
|
55
|
+
private used;
|
|
56
|
+
private readonly budget;
|
|
57
|
+
private readonly cap;
|
|
58
|
+
private readonly capReason;
|
|
59
|
+
constructor(opts?: PackOptions);
|
|
60
|
+
get full(): boolean;
|
|
61
|
+
/** Returns false when the item did not fit; the caller must then stop and emit a cursor. */
|
|
62
|
+
add(item: T, sizeHint?: number): boolean;
|
|
63
|
+
}
|
|
64
|
+
export declare function measure(value: unknown): number;
|
|
65
|
+
export interface JsonResultOptions {
|
|
66
|
+
/** Name of the array field that should shrink first if the payload blows the hard cap. */
|
|
67
|
+
listKey?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Serialize a payload as the tool's single text block, enforcing the hard cap as a last-resort
|
|
71
|
+
* safety net (tools are expected to have budgeted already, via Packer).
|
|
72
|
+
*/
|
|
73
|
+
export declare function jsonResult(payload: Record<string, unknown>, opts?: JsonResultOptions): CallToolResult;
|
|
74
|
+
export declare function textResult(text: string): CallToolResult;
|
|
75
|
+
export declare function errorResult(message: string): CallToolResult;
|
|
76
|
+
//# sourceMappingURL=respond.d.ts.map
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response budgeting (plan §5) — the single place that decides how much a tool may return.
|
|
3
|
+
*
|
|
4
|
+
* A 116k-node document must stay explorable without ever flooding the agent's context, so:
|
|
5
|
+
* 1. every response has a character budget (default 20k, hard cap 50k);
|
|
6
|
+
* 2. no response carries more than 300 nodes;
|
|
7
|
+
* 3. anything cut sets `truncated: true` and returns an opaque `nextCursor` plus a hint.
|
|
8
|
+
*/
|
|
9
|
+
export const DEFAULT_BUDGET = 20_000;
|
|
10
|
+
export const HARD_CAP = 50_000;
|
|
11
|
+
export const MAX_NODES = 300;
|
|
12
|
+
/**
|
|
13
|
+
* Room left for the response envelope (root summary, counts, cursor, hint) so the SERIALIZED
|
|
14
|
+
* response — not just its item list — stays inside DEFAULT_BUDGET.
|
|
15
|
+
*/
|
|
16
|
+
export const ENVELOPE_RESERVE = 1_500;
|
|
17
|
+
export function encodeCursor(c) {
|
|
18
|
+
return Buffer.from(JSON.stringify(c), 'utf8').toString('base64url');
|
|
19
|
+
}
|
|
20
|
+
export function decodeCursor(s) {
|
|
21
|
+
if (!s)
|
|
22
|
+
return {};
|
|
23
|
+
try {
|
|
24
|
+
const parsed = JSON.parse(Buffer.from(s, 'base64url').toString('utf8'));
|
|
25
|
+
if (parsed && typeof parsed === 'object')
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
/* fall through */
|
|
30
|
+
}
|
|
31
|
+
throw new Error(`invalid cursor: ${JSON.stringify(s)}`);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Incremental accumulator: callers push items in a stable order and stop as soon as `add`
|
|
35
|
+
* returns false. That keeps truncation deterministic and lets a cursor resume exactly where the
|
|
36
|
+
* previous response stopped.
|
|
37
|
+
*/
|
|
38
|
+
export class Packer {
|
|
39
|
+
items = [];
|
|
40
|
+
truncated = false;
|
|
41
|
+
reason;
|
|
42
|
+
used = 0;
|
|
43
|
+
budget;
|
|
44
|
+
cap;
|
|
45
|
+
capReason;
|
|
46
|
+
constructor(opts = {}) {
|
|
47
|
+
this.budget = Math.min(opts.budget ?? DEFAULT_BUDGET - ENVELOPE_RESERVE, HARD_CAP);
|
|
48
|
+
const maxItems = opts.maxItems ?? MAX_NODES;
|
|
49
|
+
const requested = opts.limit ?? maxItems;
|
|
50
|
+
this.cap = Math.max(1, Math.min(requested, maxItems));
|
|
51
|
+
this.capReason = requested < maxItems ? 'limit' : 'items';
|
|
52
|
+
}
|
|
53
|
+
get full() {
|
|
54
|
+
return this.truncated;
|
|
55
|
+
}
|
|
56
|
+
/** Returns false when the item did not fit; the caller must then stop and emit a cursor. */
|
|
57
|
+
add(item, sizeHint) {
|
|
58
|
+
if (this.items.length >= this.cap) {
|
|
59
|
+
this.truncated = true;
|
|
60
|
+
this.reason = this.capReason;
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const size = sizeHint ?? measure(item);
|
|
64
|
+
if (this.items.length > 0 && this.used + size > this.budget) {
|
|
65
|
+
this.truncated = true;
|
|
66
|
+
this.reason = 'budget';
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
this.used += size;
|
|
70
|
+
this.items.push(item);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function measure(value) {
|
|
75
|
+
if (typeof value === 'string')
|
|
76
|
+
return value.length + 1;
|
|
77
|
+
try {
|
|
78
|
+
return JSON.stringify(value)?.length ?? 0;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Serialize a payload as the tool's single text block, enforcing the hard cap as a last-resort
|
|
86
|
+
* safety net (tools are expected to have budgeted already, via Packer).
|
|
87
|
+
*/
|
|
88
|
+
export function jsonResult(payload, opts = {}) {
|
|
89
|
+
let out = payload;
|
|
90
|
+
let text = stringify(out);
|
|
91
|
+
if (text.length > HARD_CAP && opts.listKey) {
|
|
92
|
+
const list = out[opts.listKey];
|
|
93
|
+
if (Array.isArray(list)) {
|
|
94
|
+
let items = list;
|
|
95
|
+
while (items.length > 1 && text.length > HARD_CAP) {
|
|
96
|
+
items = items.slice(0, Math.floor(items.length / 2));
|
|
97
|
+
out = { ...out, [opts.listKey]: items, truncated: true, truncatedBy: 'response budget' };
|
|
98
|
+
text = stringify(out);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (text.length > HARD_CAP) {
|
|
103
|
+
out = {
|
|
104
|
+
error: 'response exceeded the hard response cap',
|
|
105
|
+
hint: 'narrow the request: lower depth, add types/scope filters, or use a smaller limit',
|
|
106
|
+
cap: HARD_CAP,
|
|
107
|
+
wouldHaveBeen: text.length,
|
|
108
|
+
};
|
|
109
|
+
text = stringify(out);
|
|
110
|
+
}
|
|
111
|
+
return { content: [{ type: 'text', text }] };
|
|
112
|
+
}
|
|
113
|
+
export function textResult(text) {
|
|
114
|
+
const capped = text.length > HARD_CAP
|
|
115
|
+
? `${text.slice(0, HARD_CAP - 80)}\n... [truncated at ${HARD_CAP} characters]`
|
|
116
|
+
: text;
|
|
117
|
+
return { content: [{ type: 'text', text: capped }] };
|
|
118
|
+
}
|
|
119
|
+
export function errorResult(message) {
|
|
120
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
121
|
+
}
|
|
122
|
+
function stringify(value) {
|
|
123
|
+
return JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)) ?? '';
|
|
124
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* figme — an MCP server that reads local Figma `.fig` files, fully offline.
|
|
4
|
+
*
|
|
5
|
+
* Transport: stdio. Nothing here touches the network, and nothing writes to a .fig file;
|
|
6
|
+
* the only write path is `fig_image { savePath }`, which the caller asks for explicitly.
|
|
7
|
+
*
|
|
8
|
+
* Usage: node dist/mcp/server.js [--max-files N]
|
|
9
|
+
*/
|
|
10
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
11
|
+
import { createContext, createServer } from './create.js';
|
|
12
|
+
function parseMaxFiles(argv) {
|
|
13
|
+
const i = argv.findIndex((a) => a === '--max-files' || a.startsWith('--max-files='));
|
|
14
|
+
if (i < 0)
|
|
15
|
+
return 4;
|
|
16
|
+
const flag = argv[i];
|
|
17
|
+
const raw = flag.includes('=') ? flag.slice(flag.indexOf('=') + 1) : argv[i + 1];
|
|
18
|
+
const n = Number(raw);
|
|
19
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : 4;
|
|
20
|
+
}
|
|
21
|
+
const server = createServer(createContext(parseMaxFiles(process.argv.slice(2))));
|
|
22
|
+
await server.connect(new StdioServerTransport());
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** `fig_blob` — raw access to `message.blobs`, the escape hatch for vector payloads. */
|
|
2
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import { type ToolContext } from './context.js';
|
|
4
|
+
export declare const NAME = "fig_blob";
|
|
5
|
+
export declare const DESCRIPTION: string;
|
|
6
|
+
export declare function register(server: McpServer, ctx: ToolContext): void;
|
|
7
|
+
//# sourceMappingURL=blob.d.ts.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { fileArg, handler, load } from './context.js';
|
|
3
|
+
import { jsonResult } from '../respond.js';
|
|
4
|
+
import { bytes as byteField } from '../../model/access.js';
|
|
5
|
+
export const NAME = 'fig_blob';
|
|
6
|
+
export const DESCRIPTION = [
|
|
7
|
+
'Return the raw bytes of one entry in the file\'s blob table. Vector geometry, glyph outlines',
|
|
8
|
+
'and similar bulk payloads are stored there and referenced by index from fields such as',
|
|
9
|
+
'`vectorData.vectorNetworkBlob` and `Path.commandsBlob` (fig_node reports these as',
|
|
10
|
+
'`vector.networkBlob` / `vector.fillBlobs`). This server does not decode the vector-network',
|
|
11
|
+
'format — you get the bytes, base64 or hex, truncated to maxBytes with a flag when longer.',
|
|
12
|
+
].join(' ');
|
|
13
|
+
const DEFAULT_MAX_BYTES = 65_536;
|
|
14
|
+
export function register(server, ctx) {
|
|
15
|
+
server.registerTool(NAME, {
|
|
16
|
+
title: 'Raw blob bytes',
|
|
17
|
+
description: DESCRIPTION,
|
|
18
|
+
inputSchema: {
|
|
19
|
+
file: fileArg,
|
|
20
|
+
index: z.number().int().min(0).describe('Blob index, as reported by fig_node `vector.*`.'),
|
|
21
|
+
encoding: z.enum(['base64', 'hex']).optional().describe('Default "base64".'),
|
|
22
|
+
maxBytes: z
|
|
23
|
+
.number()
|
|
24
|
+
.int()
|
|
25
|
+
.min(1)
|
|
26
|
+
.max(262_144)
|
|
27
|
+
.optional()
|
|
28
|
+
.describe(`Bytes to return before truncating (default ${DEFAULT_MAX_BYTES}).`),
|
|
29
|
+
},
|
|
30
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
31
|
+
}, handler((args) => {
|
|
32
|
+
const { fig } = load(ctx, args.file);
|
|
33
|
+
const blob = fig.blobs[args.index];
|
|
34
|
+
if (!blob) {
|
|
35
|
+
throw new Error(`blob index ${args.index} is out of range; this file has ${fig.blobs.length} blobs (0..${fig.blobs.length - 1})`);
|
|
36
|
+
}
|
|
37
|
+
const raw = byteField(blob, 'bytes');
|
|
38
|
+
if (!raw)
|
|
39
|
+
throw new Error(`blob ${args.index} carries no bytes field`);
|
|
40
|
+
const maxBytes = args.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
41
|
+
const encoding = args.encoding ?? 'base64';
|
|
42
|
+
const truncated = raw.length > maxBytes;
|
|
43
|
+
const slice = Buffer.from(truncated ? raw.subarray(0, maxBytes) : raw);
|
|
44
|
+
return jsonResult({
|
|
45
|
+
index: args.index,
|
|
46
|
+
byteLength: raw.length,
|
|
47
|
+
returnedBytes: slice.length,
|
|
48
|
+
encoding,
|
|
49
|
+
data: slice.toString(encoding),
|
|
50
|
+
truncated: truncated || undefined,
|
|
51
|
+
hint: truncated ? `raise maxBytes to read past ${maxBytes} bytes` : undefined,
|
|
52
|
+
blobCount: fig.blobs.length,
|
|
53
|
+
});
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** `fig_components` — the component (SYMBOL) catalogue. */
|
|
2
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import { type ToolContext } from './context.js';
|
|
4
|
+
export declare const NAME = "fig_components";
|
|
5
|
+
export declare const DESCRIPTION: string;
|
|
6
|
+
export declare function register(server: McpServer, ctx: ToolContext): void;
|
|
7
|
+
//# sourceMappingURL=components.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { cursorArg, fileArg, handler, load } from './context.js';
|
|
3
|
+
import { Packer, decodeCursor, encodeCursor, jsonResult, measure } from '../respond.js';
|
|
4
|
+
import { componentView } from '../../model/components.js';
|
|
5
|
+
import { str } from '../../model/access.js';
|
|
6
|
+
export const NAME = 'fig_components';
|
|
7
|
+
export const DESCRIPTION = [
|
|
8
|
+
'List the components (SYMBOL nodes) defined in the file: guid, name, description, the',
|
|
9
|
+
'component-set it belongs to when it is a variant, its property definitions with defaults, and',
|
|
10
|
+
'how many instances of it exist. Filter with `query` (case-insensitive substring of the name).',
|
|
11
|
+
'Sorted by instance count, most-used first, so the load-bearing parts of the design system',
|
|
12
|
+
'come back before one-off symbols. Follow up with fig_instance on a specific INSTANCE guid.',
|
|
13
|
+
].join(' ');
|
|
14
|
+
const DEFAULT_LIMIT = 50;
|
|
15
|
+
export function register(server, ctx) {
|
|
16
|
+
server.registerTool(NAME, {
|
|
17
|
+
title: 'Component catalogue',
|
|
18
|
+
description: DESCRIPTION,
|
|
19
|
+
inputSchema: {
|
|
20
|
+
file: fileArg,
|
|
21
|
+
query: z.string().optional().describe('Case-insensitive substring of the component name.'),
|
|
22
|
+
limit: z.number().int().min(1).max(300).optional().describe(`Default ${DEFAULT_LIMIT}.`),
|
|
23
|
+
cursor: cursorArg,
|
|
24
|
+
},
|
|
25
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
26
|
+
}, handler((args) => {
|
|
27
|
+
const { index } = load(ctx, args.file);
|
|
28
|
+
const needle = args.query?.toLowerCase();
|
|
29
|
+
const matches = index.symbols.filter((s) => !needle || (str(s.node, 'name') ?? '').toLowerCase().includes(needle));
|
|
30
|
+
// Stable order: most-instantiated first, guid as the tiebreak so cursors never drift.
|
|
31
|
+
const sorted = [...matches].sort((a, b) => {
|
|
32
|
+
const d = (index.instanceCounts.get(b.key) ?? 0) - (index.instanceCounts.get(a.key) ?? 0);
|
|
33
|
+
return d !== 0 ? d : a.key < b.key ? -1 : 1;
|
|
34
|
+
});
|
|
35
|
+
const { offset = 0 } = decodeCursor(args.cursor);
|
|
36
|
+
const packer = new Packer({ limit: args.limit ?? DEFAULT_LIMIT });
|
|
37
|
+
let i = offset;
|
|
38
|
+
for (; i < sorted.length; i++) {
|
|
39
|
+
const item = componentView(index, sorted[i]);
|
|
40
|
+
if (!packer.add(item, measure(item)))
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
const truncated = packer.truncated && i < sorted.length;
|
|
44
|
+
return jsonResult({
|
|
45
|
+
totalComponents: index.symbols.length,
|
|
46
|
+
matching: sorted.length,
|
|
47
|
+
returned: packer.items.length,
|
|
48
|
+
components: packer.items,
|
|
49
|
+
truncated: truncated || undefined,
|
|
50
|
+
nextCursor: truncated ? encodeCursor({ offset: i }) : undefined,
|
|
51
|
+
hint: truncated ? 'pass nextCursor to continue, or narrow with query' : undefined,
|
|
52
|
+
}, { listKey: 'components' });
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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 type { FileCache, CacheEntry } from '../../cache.js';
|
|
7
|
+
import type { FileIndex } from '../../model/index.js';
|
|
8
|
+
import type { TreeNode } from '../../model/tree.js';
|
|
9
|
+
import { type CallToolResult } from '../respond.js';
|
|
10
|
+
export interface ToolContext {
|
|
11
|
+
readonly cache: FileCache;
|
|
12
|
+
}
|
|
13
|
+
export declare const fileArg: z.ZodString;
|
|
14
|
+
export declare const cursorArg: z.ZodOptional<z.ZodString>;
|
|
15
|
+
export declare function load(ctx: ToolContext, file: string): CacheEntry;
|
|
16
|
+
export declare function requireNode(index: FileIndex, guid: string): TreeNode;
|
|
17
|
+
/** Resolve an optional scope argument to a subtree root, defaulting to the DOCUMENT. */
|
|
18
|
+
export declare function resolveRoot(index: FileIndex, guid: string | undefined): TreeNode;
|
|
19
|
+
/**
|
|
20
|
+
* Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
|
|
21
|
+
* server, and keeps the message actionable (the thrown text is already user-facing).
|
|
22
|
+
*/
|
|
23
|
+
export declare function handler<A>(fn: (args: A) => CallToolResult | Promise<CallToolResult>): (args: A, extra: unknown) => Promise<CallToolResult>;
|
|
24
|
+
//# sourceMappingURL=context.d.ts.map
|