From 8f1d140a1607872df677b7b1e2ba18d01f393ad3 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:25:18 +0000 Subject: [PATCH 01/19] test: tombstone against child_process / exec() returning to src/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CVE-2025-53967 and CVE-2025-15061 were a curl fallback built with child_process.exec. The code is already gone; this keeps it gone through future upstream cherry-picks. 🤖 Generated with BLOCKS! --- src/tests/no-shell-exec.test.ts | 46 +++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/tests/no-shell-exec.test.ts diff --git a/src/tests/no-shell-exec.test.ts b/src/tests/no-shell-exec.test.ts new file mode 100644 index 00000000..96824225 --- /dev/null +++ b/src/tests/no-shell-exec.test.ts @@ -0,0 +1,46 @@ +import { readdirSync, readFileSync, statSync } from "fs"; +import { join, relative } from "path"; +import { describe, expect, it } from "vitest"; + +/** + * Tombstone for CVE-2025-53967 / CVE-2025-15061: both were a `curl` fallback + * built with `child_process.exec` in the fetch path, i.e. command injection in + * the server process. The code is gone (fetch goes through `undici` now); this + * test keeps it gone, including through cherry-picks from upstream, where a + * shell-out can slip back in unnoticed. + */ +const SRC_ROOT = join(__dirname, ".."); + +// The import pattern also matches `require("child_process")` and dynamic +// `import("child_process")`. The call pattern is restricted to bare calls so a +// destructured `exec` is caught while `RegExp.prototype.exec` (`re.exec(...)`) +// is not; a `cp.exec(...)` style call needs the import and is caught there. +const FORBIDDEN = [ + { name: "child_process import", pattern: /["'](?:node:)?child_process["']/ }, + { name: "bare exec()/execSync() call", pattern: /(? { + const full = join(dir, entry); + if (statSync(full).isDirectory()) { + return full === join(SRC_ROOT, "tests") ? [] : listSourceFiles(full); + } + return /\.(ts|js|mjs|cjs)$/.test(entry) ? [full] : []; + }); +} + +describe("no shell execution in src/", () => { + it("never imports child_process or calls exec()/execSync()", () => { + const offenders: string[] = []; + for (const file of listSourceFiles(SRC_ROOT)) { + const contents = readFileSync(file, "utf8"); + for (const { name, pattern } of FORBIDDEN) { + if (pattern.test(contents)) { + offenders.push(`${relative(SRC_ROOT, file)}: ${name}`); + } + } + } + expect(offenders).toEqual([]); + }); +}); From 764a4a1da4efc86d01f4ee103c37742653fdc485 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:28:28 +0000 Subject: [PATCH 02/19] fix(deps): clear the production audit (111 advisories -> 0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - @modelcontextprotocol/sdk 1.29.0 -> ^1.32.2 (OAuth credential leak to the wrong AS, unbounded request body, task/session binding); server API unchanged - undici ^7.30.1, express ^5.3.0, js-yaml ^4.3.2, zod ^4.6.6 (memory exhaustion on oversized collections; schemas needed no changes) - @figma/rest-api-spec ^0.47.0 (May-Oct 2026 API additions) - @jimp/* ^1.6.1: moves jimp off file-type 16 (ASF parser loop) on its own - pnpm.overrides for transitives upstream ranges still allow: proxy-addr (critical, IP spoofing), body-parser, qs, path-to-regexp, hono, @hono/node-server, express-rate-limit, ip-address, fast-uri, and zod for @jimp/types (it only validates jimp's own option objects; image tests pass) - CI: pnpm audit --prod --audit-level=high gate; dependabot weekly (npm + actions) Supersedes upstream PR #405 (older versions of the same overrides). 🤖 Generated with BLOCKS! --- .github/dependabot.yml | 16 ++ .github/workflows/ci.yml | 6 + package.json | 36 ++- pnpm-lock.yaml | 481 +++++++++++++++++++-------------------- 4 files changed, 279 insertions(+), 260 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..3df1f268 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + production-dependencies: + dependency-type: production + development-dependencies: + dependency-type: development + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5873ff63..8d6135d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,3 +27,9 @@ jobs: - name: Test run: pnpm test + + # Runtime dependency tree must stay free of high/critical advisories + # (see the Blocks fork section in README). Dev-only advisories are + # tolerated here; dependabot keeps them moving. + - name: Audit production dependencies + run: pnpm audit --prod --audit-level=high diff --git a/package.json b/package.json index 64a618a4..7712e14c 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,19 @@ "onlyBuiltDependencies": [ "esbuild", "lefthook" - ] + ], + "overrides": { + "proxy-addr": ">=2.0.8", + "body-parser": ">=2.4.0", + "qs": ">=6.16.1", + "path-to-regexp": ">=8.4.0 <9", + "hono": ">=4.13.16", + "@hono/node-server": ">=2.1.3", + "express-rate-limit": ">=8.2.2", + "ip-address": ">=10.7.4", + "fast-uri": ">=3.1.9 <4", + "zod": ">=4.6.6" + } }, "repository": { "type": "git", @@ -50,22 +62,22 @@ "author": "", "license": "MIT", "dependencies": { - "@figma/rest-api-spec": "^0.37.0", - "@jimp/core": "^1.6.0", - "@jimp/js-gif": "^1.6.0", - "@jimp/js-jpeg": "^1.6.0", - "@jimp/js-png": "^1.6.0", - "@jimp/plugin-crop": "^1.6.0", - "@modelcontextprotocol/sdk": "1.29.0", + "@figma/rest-api-spec": "^0.47.0", + "@jimp/core": "^1.6.1", + "@jimp/js-gif": "^1.6.1", + "@jimp/js-jpeg": "^1.6.1", + "@jimp/js-png": "^1.6.1", + "@jimp/plugin-crop": "^1.6.1", + "@modelcontextprotocol/sdk": "^1.32.2", "cleye": "^2.2.1", "cross-env": "^7.0.3", "dotenv": "^16.4.7", - "express": "^5.2.1", - "js-yaml": "^4.1.1", + "express": "^5.3.0", + "js-yaml": "^4.3.2", "posthog-node": "^5.29.2", "remeda": "^2.20.1", - "undici": "^7.25.0", - "zod": "^3.25.76" + "undici": "^7.30.1", + "zod": "^4.6.6" }, "devDependencies": { "@eslint/js": "^9.33.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f4ef152a..535e09e1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,31 +4,43 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + proxy-addr: '>=2.0.8' + body-parser: '>=2.4.0' + qs: '>=6.16.1' + path-to-regexp: '>=8.4.0 <9' + hono: '>=4.13.16' + '@hono/node-server': '>=2.1.3' + express-rate-limit: '>=8.2.2' + ip-address: '>=10.7.4' + fast-uri: '>=3.1.9 <4' + zod: '>=4.6.6' + importers: .: dependencies: '@figma/rest-api-spec': - specifier: ^0.37.0 - version: 0.37.0 + specifier: ^0.47.0 + version: 0.47.0 '@jimp/core': - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 '@jimp/js-gif': - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 '@jimp/js-jpeg': - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 '@jimp/js-png': - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 '@jimp/plugin-crop': - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 '@modelcontextprotocol/sdk': - specifier: 1.29.0 - version: 1.29.0(zod@3.25.76) + specifier: ^1.32.2 + version: 1.32.2(zod@4.6.7) cleye: specifier: ^2.2.1 version: 2.2.1 @@ -39,11 +51,11 @@ importers: specifier: ^16.4.7 version: 16.4.7 express: - specifier: ^5.2.1 - version: 5.2.1 + specifier: ^5.3.0 + version: 5.3.0 js-yaml: - specifier: ^4.1.1 - version: 4.1.1 + specifier: ^4.3.2 + version: 4.3.2 posthog-node: specifier: ^5.29.2 version: 5.29.2 @@ -51,11 +63,11 @@ importers: specifier: ^2.20.1 version: 2.20.1 undici: - specifier: ^7.25.0 - version: 7.25.0 + specifier: ^7.30.1 + version: 7.30.2 zod: - specifier: ^3.25.76 - version: 3.25.76 + specifier: '>=4.6.6' + version: 4.6.7 devDependencies: '@eslint/js': specifier: ^9.33.0 @@ -105,6 +117,9 @@ importers: packages: + '@borewit/text-codec@0.2.3': + resolution: {integrity: sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw==} + '@esbuild/aix-ppc64@0.27.3': resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} engines: {node: '>=18'} @@ -303,14 +318,14 @@ packages: resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@figma/rest-api-spec@0.37.0': - resolution: {integrity: sha512-KKeCgSRiO2gajT/sKCAsn48ubl8NRbYqyIvfkk5+NPK2ar+DVuLKg3fl3/cR1WharC5Dg4V5a9JzDsYv04k50g==} + '@figma/rest-api-spec@0.47.0': + resolution: {integrity: sha512-gU1Z8kF+cXyMREA+0mHVkKF4d6641zsDR7rLxJXIxa4r60SJzrK+etSrumiSWmyoYe/xkkCgTmm7lk0R/KzKDg==} - '@hono/node-server@1.19.10': - resolution: {integrity: sha512-hZ7nOssGqRgyV3FVVQdfi+U4q02uB23bpnYpdvNXkYTRRyWx84b7yf1ans+dnJ/7h41sGL3CeQTfO+ZGxuO+Iw==} - engines: {node: '>=18.14.1'} + '@hono/node-server@2.1.9': + resolution: {integrity: sha512-Sk4NQd3GFY0WZWCzndwFMPwJhtD0y9qjsQ+pjID0/03nK9pxyBCUoUHCho8QYBLBVhi0ssL8UkNPHqbgSOFPIQ==} + engines: {node: '>=20'} peerDependencies: - hono: ^4 + hono: '>=4.13.16' '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} @@ -336,36 +351,36 @@ packages: resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} - '@jimp/core@1.6.0': - resolution: {integrity: sha512-EQQlKU3s9QfdJqiSrZWNTxBs3rKXgO2W+GxNXDtwchF3a4IqxDheFX1ti+Env9hdJXDiYLp2jTRjlxhPthsk8w==} + '@jimp/core@1.6.1': + resolution: {integrity: sha512-+BoKC5G6hkrSy501zcJ2EpfnllP+avPevcBfRcZe/CW+EwEfY6X1EZ8QWyT7NpDIvEEJb1fdJnMMfUnFkxmw9A==} engines: {node: '>=18'} - '@jimp/file-ops@1.6.0': - resolution: {integrity: sha512-Dx/bVDmgnRe1AlniRpCKrGRm5YvGmUwbDzt+MAkgmLGf+jvBT75hmMEZ003n9HQI/aPnm/YKnXjg/hOpzNCpHQ==} + '@jimp/file-ops@1.6.1': + resolution: {integrity: sha512-T+gX6osHjprbDRad0/B71Evyre7ZdVY1z/gFGEG9Z8KOtZPKboWvPeP2UjbZYWQLy9UKCPQX1FNAnDiOPkJL7w==} engines: {node: '>=18'} - '@jimp/js-gif@1.6.0': - resolution: {integrity: sha512-N9CZPHOrJTsAUoWkWZstLPpwT5AwJ0wge+47+ix3++SdSL/H2QzyMqxbcDYNFe4MoI5MIhATfb0/dl/wmX221g==} + '@jimp/js-gif@1.6.1': + resolution: {integrity: sha512-YjY2W26rQa05XhanYhRZ7dingCiNN+T2Ymb1JiigIbABY0B28wHE3v3Cf1/HZPWGu0hOg36ylaKgV5KxF2M58w==} engines: {node: '>=18'} - '@jimp/js-jpeg@1.6.0': - resolution: {integrity: sha512-6vgFDqeusblf5Pok6B2DUiMXplH8RhIKAryj1yn+007SIAQ0khM1Uptxmpku/0MfbClx2r7pnJv9gWpAEJdMVA==} + '@jimp/js-jpeg@1.6.1': + resolution: {integrity: sha512-HT9H3yOmlOFzYmdI15IYdfy6ggQhSRIaHeA+OTJSEORXBqEo97sUZu/DsgHIcX5NJ7TkJBTgZ9BZXsV6UbsyMg==} engines: {node: '>=18'} - '@jimp/js-png@1.6.0': - resolution: {integrity: sha512-AbQHScy3hDDgMRNfG0tPjL88AV6qKAILGReIa3ATpW5QFjBKpisvUaOqhzJ7Reic1oawx3Riyv152gaPfqsBVg==} + '@jimp/js-png@1.6.1': + resolution: {integrity: sha512-SZ/KVhI5UjcSzzlXsXdIi/LhJ7UShf2NkMOtVrbZQcGzsqNtynAelrOXeoTxcanfVqmNhAoVHg8yR2cYoqrYjA==} engines: {node: '>=18'} - '@jimp/plugin-crop@1.6.0': - resolution: {integrity: sha512-KqZkEhvs+21USdySCUDI+GFa393eDIzbi1smBqkUPTE+pRwSWMAf01D5OC3ZWB+xZsNla93BDS9iCkLHA8wang==} + '@jimp/plugin-crop@1.6.1': + resolution: {integrity: sha512-EerRSLlclXyKDnYc/H9w/1amZW7b7v3OGi/VlerPd2M/pAu5X8TkyYWtfqYCXnNp1Ixtd8oCo9zGfY9zoXT4rg==} engines: {node: '>=18'} - '@jimp/types@1.6.0': - resolution: {integrity: sha512-7UfRsiKo5GZTAATxm2qQ7jqmUXP0DxTArztllTcYdyw6Xi5oT4RaoXynVtCD4UyLK5gJgkZJcwonoijrhYFKfg==} + '@jimp/types@1.6.1': + resolution: {integrity: sha512-leI7YbveTNi565m910XgIOwXyuu074H5qazAD1357HImJSv2hqxnWXpwxQbadGWZ7goZRYBDZy5lpqud0p7q5w==} engines: {node: '>=18'} - '@jimp/utils@1.6.0': - resolution: {integrity: sha512-gqFTGEosKbOkYF/WFj26jMHOI5OH2jeP1MmC/zbK6BF6VJBf8rIC5898dPfSzZEbSA0wbbV5slbntWVc5PKLFA==} + '@jimp/utils@1.6.1': + resolution: {integrity: sha512-veFPRd93FCnS7AgmCkPgARVGoDRrJ9cm1ujuNyA+UfQ5VKbED2002sm5XfFLFwTsKC8j04heTrwe+tU1dluXOw==} engines: {node: '>=18'} '@jridgewell/gen-mapping@0.3.8': @@ -386,12 +401,12 @@ packages: '@jridgewell/trace-mapping@0.3.25': resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==} - '@modelcontextprotocol/sdk@1.29.0': - resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==} + '@modelcontextprotocol/sdk@1.32.2': + resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} engines: {node: '>=18'} peerDependencies: '@cfworker/json-schema': ^4.1.1 - zod: ^3.25 || ^4.0 + zod: '>=4.6.6' peerDependenciesMeta: '@cfworker/json-schema': optional: true @@ -531,6 +546,10 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tokenizer/inflate@0.4.1': + resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} + engines: {node: '>=18'} + '@tokenizer/token@0.3.0': resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==} @@ -679,10 +698,6 @@ packages: '@vitest/utils@4.0.18': resolution: {integrity: sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==} - abort-controller@3.0.0: - resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} - engines: {node: '>=6.5'} - accepts@2.0.0: resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} engines: {node: '>= 0.6'} @@ -748,11 +763,8 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - base64-js@1.5.1: - resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} - - body-parser@2.2.2: - resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==} + body-parser@2.4.0: + resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} brace-expansion@1.1.12: @@ -765,9 +777,6 @@ packages: resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==} engines: {node: 18 || 20 || >=22} - buffer@6.0.3: - resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==} - bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -830,14 +839,18 @@ packages: resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} engines: {node: ^14.18.0 || >=16.10.0} - content-disposition@1.0.0: - resolution: {integrity: sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==} - engines: {node: '>= 0.6'} + content-disposition@2.0.1: + resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} + engines: {node: '>=18'} content-type@1.0.5: resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} engines: {node: '>= 0.6'} + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + cookie-signature@1.2.2: resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} engines: {node: '>=6.6.0'} @@ -985,14 +998,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - event-target-shim@5.0.1: - resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} - engines: {node: '>=6'} - - events@3.3.0: - resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} - engines: {node: '>=0.8.x'} - eventsource-parser@3.0.0: resolution: {integrity: sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==} engines: {node: '>=18.0.0'} @@ -1008,14 +1013,14 @@ packages: resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} engines: {node: '>=12.0.0'} - express-rate-limit@8.2.1: - resolution: {integrity: sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==} + express-rate-limit@8.7.5: + resolution: {integrity: sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==} engines: {node: '>= 16'} peerDependencies: express: '>= 4.11' - express@5.2.1: - resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==} + express@5.3.0: + resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==} engines: {node: '>= 18'} fast-deep-equal@3.1.3: @@ -1027,8 +1032,8 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - fast-uri@3.1.0: - resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} @@ -1043,9 +1048,9 @@ packages: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} - file-type@16.5.4: - resolution: {integrity: sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw==} - engines: {node: '>=10'} + file-type@21.3.4: + resolution: {integrity: sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==} + engines: {node: '>=20'} finalhandler@2.1.1: resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} @@ -1132,8 +1137,8 @@ packages: resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} engines: {node: '>= 0.4'} - hono@4.12.5: - resolution: {integrity: sha512-3qq+FUBtlTHhtYxbxheZgY8NIFnkkC/MR8u5TTsr7YZ3wixryQ3cCwn3iZbg8p8B88iDBBAYSfZDS75t8MN7Vg==} + hono@4.13.19: + resolution: {integrity: sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==} engines: {node: '>=16.9.0'} http-errors@2.0.1: @@ -1144,6 +1149,10 @@ packages: resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==} engines: {node: '>=0.10.0'} + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} @@ -1169,8 +1178,8 @@ packages: inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - ip-address@10.0.1: - resolution: {integrity: sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==} + ip-address@10.7.6: + resolution: {integrity: sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==} engines: {node: '>= 12'} ipaddr.js@1.9.1: @@ -1208,8 +1217,8 @@ packages: jpeg-js@0.4.4: resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} - js-yaml@4.1.1: - resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true json-buffer@3.0.1: @@ -1429,17 +1438,12 @@ packages: resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} engines: {node: '>=16 || 14 >=14.18'} - path-to-regexp@8.2.0: - resolution: {integrity: sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==} - engines: {node: '>=16'} + path-to-regexp@8.4.2: + resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} - peek-readable@4.1.0: - resolution: {integrity: sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg==} - engines: {node: '>=8'} - picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -1502,20 +1506,16 @@ packages: engines: {node: '>=14'} hasBin: true - process@0.11.10: - resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==} - engines: {node: '>= 0.6.0'} - - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - qs@6.15.0: - resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} range-parser@1.2.1: @@ -1526,14 +1526,6 @@ packages: resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} engines: {node: '>= 0.10'} - readable-stream@4.7.0: - resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - readable-web-to-node-stream@3.0.4: - resolution: {integrity: sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==} - engines: {node: '>=8'} - readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -1565,9 +1557,6 @@ packages: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} - safe-buffer@5.2.1: - resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} @@ -1595,8 +1584,8 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} side-channel-map@1.0.1: @@ -1607,8 +1596,8 @@ packages: resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} engines: {node: '>= 0.4'} - side-channel@1.1.0: - resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} engines: {node: '>= 0.4'} siginfo@2.0.0: @@ -1644,9 +1633,6 @@ packages: resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} engines: {node: '>=12'} - string_decoder@1.3.0: - resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} - strip-ansi@6.0.1: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} @@ -1659,9 +1645,9 @@ packages: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} - strtok3@6.3.0: - resolution: {integrity: sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw==} - engines: {node: '>=10'} + strtok3@10.8.0: + resolution: {integrity: sha512-e6bW3fD6V01DPmcbLfNtn0cjsiHvTKS/hivgbzqYMfHb/nLes4QQ0H5QBxlkPQayF4xv08AvlSgptGwN86Eemw==} + engines: {node: '>=18'} sucrase@3.35.0: resolution: {integrity: sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==} @@ -1707,9 +1693,9 @@ packages: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} - token-types@4.2.1: - resolution: {integrity: sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ==} - engines: {node: '>=10'} + token-types@6.2.0: + resolution: {integrity: sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg==} + engines: {node: '>=14.16'} tree-kill@1.2.2: resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} @@ -1759,9 +1745,9 @@ packages: type-flag@4.0.3: resolution: {integrity: sha512-YA09cL07U7hSV+/doSfKl+RkIZ2olCnevZsVgAuyBUG3h2ROf9Oh2vmbq5Rf26aA9/qu9RtStuc7ap5PC6k/vw==} - type-is@2.0.1: - resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==} - engines: {node: '>= 0.6'} + type-is@2.1.0: + resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} + engines: {node: '>= 18'} typescript@5.7.3: resolution: {integrity: sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==} @@ -1771,14 +1757,18 @@ packages: ufo@1.6.3: resolution: {integrity: sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==} + uint8array-extras@1.6.0: + resolution: {integrity: sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==} + engines: {node: '>=18'} + undici-types@6.19.8: resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==} undici-types@7.18.2: resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} - undici@7.25.0: - resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} engines: {node: '>=20.18.1'} unpipe@1.0.0: @@ -1898,13 +1888,15 @@ packages: zod-to-json-schema@3.25.1: resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==} peerDependencies: - zod: ^3.25 || ^4 + zod: '>=4.6.6' - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} snapshots: + '@borewit/text-codec@0.2.3': {} + '@esbuild/aix-ppc64@0.27.3': optional: true @@ -2014,7 +2006,7 @@ snapshots: globals: 14.0.0 ignore: 5.3.2 import-fresh: 3.3.1 - js-yaml: 4.1.1 + js-yaml: 4.3.2 minimatch: 3.1.5 strip-json-comments: 3.1.1 transitivePeerDependencies: @@ -2031,11 +2023,11 @@ snapshots: '@eslint/core': 0.17.0 levn: 0.4.1 - '@figma/rest-api-spec@0.37.0': {} + '@figma/rest-api-spec@0.47.0': {} - '@hono/node-server@1.19.10(hono@4.12.5)': + '@hono/node-server@2.1.9(hono@4.13.19)': dependencies: - hono: 4.12.5 + hono: 4.13.19 '@humanfs/core@0.19.1': {} @@ -2059,51 +2051,61 @@ snapshots: wrap-ansi: 8.1.0 wrap-ansi-cjs: wrap-ansi@7.0.0 - '@jimp/core@1.6.0': + '@jimp/core@1.6.1': dependencies: - '@jimp/file-ops': 1.6.0 - '@jimp/types': 1.6.0 - '@jimp/utils': 1.6.0 + '@jimp/file-ops': 1.6.1 + '@jimp/types': 1.6.1 + '@jimp/utils': 1.6.1 await-to-js: 3.0.0 exif-parser: 0.1.12 - file-type: 16.5.4 + file-type: 21.3.4 mime: 3.0.0 + transitivePeerDependencies: + - supports-color - '@jimp/file-ops@1.6.0': {} + '@jimp/file-ops@1.6.1': {} - '@jimp/js-gif@1.6.0': + '@jimp/js-gif@1.6.1': dependencies: - '@jimp/core': 1.6.0 - '@jimp/types': 1.6.0 + '@jimp/core': 1.6.1 + '@jimp/types': 1.6.1 gifwrap: 0.10.1 omggif: 1.0.10 + transitivePeerDependencies: + - supports-color - '@jimp/js-jpeg@1.6.0': + '@jimp/js-jpeg@1.6.1': dependencies: - '@jimp/core': 1.6.0 - '@jimp/types': 1.6.0 + '@jimp/core': 1.6.1 + '@jimp/types': 1.6.1 jpeg-js: 0.4.4 + transitivePeerDependencies: + - supports-color - '@jimp/js-png@1.6.0': + '@jimp/js-png@1.6.1': dependencies: - '@jimp/core': 1.6.0 - '@jimp/types': 1.6.0 + '@jimp/core': 1.6.1 + '@jimp/types': 1.6.1 pngjs: 7.0.0 + transitivePeerDependencies: + - supports-color - '@jimp/plugin-crop@1.6.0': + '@jimp/plugin-crop@1.6.1': dependencies: - '@jimp/core': 1.6.0 - '@jimp/types': 1.6.0 - '@jimp/utils': 1.6.0 - zod: 3.25.76 + '@jimp/core': 1.6.1 + '@jimp/types': 1.6.1 + '@jimp/utils': 1.6.1 + zod: 4.6.7 + transitivePeerDependencies: + - supports-color - '@jimp/types@1.6.0': + '@jimp/types@1.6.1': dependencies: - zod: 3.25.76 + zod: 4.6.7 - '@jimp/utils@1.6.0': + '@jimp/utils@1.6.1': dependencies: - '@jimp/types': 1.6.0 + '@jimp/types': 1.6.1 tinycolor2: 1.6.0 '@jridgewell/gen-mapping@0.3.8': @@ -2123,9 +2125,9 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@modelcontextprotocol/sdk@1.29.0(zod@3.25.76)': + '@modelcontextprotocol/sdk@1.32.2(zod@4.6.7)': dependencies: - '@hono/node-server': 1.19.10(hono@4.12.5) + '@hono/node-server': 2.1.9(hono@4.13.19) ajv: 8.18.0 ajv-formats: 3.0.1(ajv@8.18.0) content-type: 1.0.5 @@ -2133,15 +2135,15 @@ snapshots: cross-spawn: 7.0.6 eventsource: 3.0.5 eventsource-parser: 3.0.0 - express: 5.2.1 - express-rate-limit: 8.2.1(express@5.2.1) - hono: 4.12.5 + express: 5.3.0 + express-rate-limit: 8.7.5(express@5.3.0) + hono: 4.13.19 jose: 6.1.3 json-schema-typed: 8.0.2 pkce-challenge: 5.0.0 raw-body: 3.0.2 - zod: 3.25.76 - zod-to-json-schema: 3.25.1(zod@3.25.76) + zod: 4.6.7 + zod-to-json-schema: 3.25.1(zod@4.6.7) transitivePeerDependencies: - supports-color @@ -2227,6 +2229,13 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@tokenizer/inflate@0.4.1': + dependencies: + debug: 4.4.3 + token-types: 6.2.0 + transitivePeerDependencies: + - supports-color + '@tokenizer/token@0.3.0': {} '@types/body-parser@1.19.5': @@ -2426,10 +2435,6 @@ snapshots: '@vitest/pretty-format': 4.0.18 tinyrainbow: 3.0.3 - abort-controller@3.0.0: - dependencies: - event-target-shim: 5.0.1 - accepts@2.0.0: dependencies: mime-types: 3.0.2 @@ -2455,7 +2460,7 @@ snapshots: ajv@8.18.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.0 + fast-uri: 3.1.9 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -2481,19 +2486,17 @@ snapshots: balanced-match@4.0.4: {} - base64-js@1.5.1: {} - - body-parser@2.2.2: + body-parser@2.4.0: dependencies: bytes: 3.1.2 - content-type: 1.0.5 + content-type: 2.1.0 debug: 4.4.3 http-errors: 2.0.1 - iconv-lite: 0.7.2 + iconv-lite: 0.7.3 on-finished: 2.4.1 - qs: 6.15.0 + qs: 6.17.1 raw-body: 3.0.2 - type-is: 2.0.1 + type-is: 2.1.0 transitivePeerDependencies: - supports-color @@ -2510,11 +2513,6 @@ snapshots: dependencies: balanced-match: 4.0.4 - buffer@6.0.3: - dependencies: - base64-js: 1.5.1 - ieee754: 1.2.1 - bundle-require@5.1.0(esbuild@0.27.3): dependencies: esbuild: 0.27.3 @@ -2566,12 +2564,12 @@ snapshots: consola@3.4.2: {} - content-disposition@1.0.0: - dependencies: - safe-buffer: 5.2.1 + content-disposition@2.0.1: {} content-type@1.0.5: {} + content-type@2.1.0: {} + cookie-signature@1.2.2: {} cookie@0.7.1: {} @@ -2738,10 +2736,6 @@ snapshots: etag@1.8.1: {} - event-target-shim@5.0.1: {} - - events@3.3.0: {} - eventsource-parser@3.0.0: {} eventsource@3.0.5: @@ -2752,17 +2746,20 @@ snapshots: expect-type@1.3.0: {} - express-rate-limit@8.2.1(express@5.2.1): + express-rate-limit@8.7.5(express@5.3.0): dependencies: - express: 5.2.1 - ip-address: 10.0.1 + debug: 4.4.3 + express: 5.3.0 + ip-address: 10.7.6 + transitivePeerDependencies: + - supports-color - express@5.2.1: + express@5.3.0: dependencies: accepts: 2.0.0 - body-parser: 2.2.2 - content-disposition: 1.0.0 - content-type: 1.0.5 + body-parser: 2.4.0 + content-disposition: 2.0.1 + content-type: 2.1.0 cookie: 0.7.1 cookie-signature: 1.2.2 debug: 4.4.3 @@ -2778,14 +2775,14 @@ snapshots: on-finished: 2.4.1 once: 1.4.0 parseurl: 1.3.3 - proxy-addr: 2.0.7 - qs: 6.15.0 + proxy-addr: 2.0.8 + qs: 6.17.1 range-parser: 1.2.1 router: 2.2.0 send: 1.2.1 serve-static: 2.2.1 statuses: 2.0.2 - type-is: 2.0.1 + type-is: 2.1.0 vary: 1.1.2 transitivePeerDependencies: - supports-color @@ -2796,7 +2793,7 @@ snapshots: fast-levenshtein@2.0.6: {} - fast-uri@3.1.0: {} + fast-uri@3.1.9: {} fdir@6.5.0(picomatch@4.0.3): optionalDependencies: @@ -2806,11 +2803,14 @@ snapshots: dependencies: flat-cache: 4.0.1 - file-type@16.5.4: + file-type@21.3.4: dependencies: - readable-web-to-node-stream: 3.0.4 - strtok3: 6.3.0 - token-types: 4.2.1 + '@tokenizer/inflate': 0.4.1 + strtok3: 10.8.0 + token-types: 6.2.0 + uint8array-extras: 1.6.0 + transitivePeerDependencies: + - supports-color finalhandler@2.1.1: dependencies: @@ -2909,7 +2909,7 @@ snapshots: dependencies: function-bind: 1.1.2 - hono@4.12.5: {} + hono@4.13.19: {} http-errors@2.0.1: dependencies: @@ -2923,6 +2923,10 @@ snapshots: dependencies: safer-buffer: 2.1.2 + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + ieee754@1.2.1: {} ignore@5.3.2: {} @@ -2942,7 +2946,7 @@ snapshots: inherits@2.0.4: {} - ip-address@10.0.1: {} + ip-address@10.7.6: {} ipaddr.js@1.9.1: {} @@ -2970,7 +2974,7 @@ snapshots: jpeg-js@0.4.4: {} - js-yaml@4.1.1: + js-yaml@4.3.2: dependencies: argparse: 2.0.1 @@ -3153,12 +3157,10 @@ snapshots: lru-cache: 10.4.3 minipass: 7.1.2 - path-to-regexp@8.2.0: {} + path-to-regexp@8.4.2: {} pathe@2.0.3: {} - peek-readable@4.1.0: {} - picocolors@1.1.1: {} picomatch@4.0.3: {} @@ -3196,18 +3198,17 @@ snapshots: prettier@3.5.0: {} - process@0.11.10: {} - - proxy-addr@2.0.7: + proxy-addr@2.0.8: dependencies: forwarded: 0.2.0 ipaddr.js: 1.9.1 punycode@2.3.1: {} - qs@6.15.0: + qs@6.17.1: dependencies: - side-channel: 1.1.0 + es-define-property: 1.0.1 + side-channel: 1.1.1 range-parser@1.2.1: {} @@ -3218,18 +3219,6 @@ snapshots: iconv-lite: 0.7.2 unpipe: 1.0.0 - readable-stream@4.7.0: - dependencies: - abort-controller: 3.0.0 - buffer: 6.0.3 - events: 3.3.0 - process: 0.11.10 - string_decoder: 1.3.0 - - readable-web-to-node-stream@3.0.4: - dependencies: - readable-stream: 4.7.0 - readdirp@4.1.2: {} remeda@2.20.1: @@ -3281,12 +3270,10 @@ snapshots: depd: 2.0.0 is-promise: 4.0.0 parseurl: 1.3.3 - path-to-regexp: 8.2.0 + path-to-regexp: 8.4.2 transitivePeerDependencies: - supports-color - safe-buffer@5.2.1: {} - safer-buffer@2.1.2: {} semver@7.7.4: {} @@ -3324,7 +3311,7 @@ snapshots: shebang-regex@3.0.0: {} - side-channel-list@1.0.0: + side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 object-inspect: 1.13.4 @@ -3344,11 +3331,11 @@ snapshots: object-inspect: 1.13.4 side-channel-map: 1.0.1 - side-channel@1.1.0: + side-channel@1.1.1: dependencies: es-errors: 1.3.0 object-inspect: 1.13.4 - side-channel-list: 1.0.0 + side-channel-list: 1.0.1 side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 @@ -3378,10 +3365,6 @@ snapshots: emoji-regex: 9.2.2 strip-ansi: 7.1.0 - string_decoder@1.3.0: - dependencies: - safe-buffer: 5.2.1 - strip-ansi@6.0.1: dependencies: ansi-regex: 5.0.1 @@ -3392,10 +3375,9 @@ snapshots: strip-json-comments@3.1.1: {} - strtok3@6.3.0: + strtok3@10.8.0: dependencies: '@tokenizer/token': 0.3.0 - peek-readable: 4.1.0 sucrase@3.35.0: dependencies: @@ -3438,8 +3420,9 @@ snapshots: toidentifier@1.0.1: {} - token-types@4.2.1: + token-types@6.2.0: dependencies: + '@borewit/text-codec': 0.2.3 '@tokenizer/token': 0.3.0 ieee754: 1.2.1 @@ -3494,9 +3477,9 @@ snapshots: type-flag@4.0.3: {} - type-is@2.0.1: + type-is@2.1.0: dependencies: - content-type: 1.0.5 + content-type: 2.1.0 media-typer: 1.1.0 mime-types: 3.0.2 @@ -3504,11 +3487,13 @@ snapshots: ufo@1.6.3: {} + uint8array-extras@1.6.0: {} + undici-types@6.19.8: {} undici-types@7.18.2: {} - undici@7.25.0: {} + undici@7.30.2: {} unpipe@1.0.0: {} @@ -3595,8 +3580,8 @@ snapshots: yocto-queue@0.1.0: {} - zod-to-json-schema@3.25.1(zod@3.25.76): + zod-to-json-schema@3.25.1(zod@4.6.7): dependencies: - zod: 3.25.76 + zod: 4.6.7 - zod@3.25.76: {} + zod@4.6.7: {} From de82b8d3f13283ac6ab15611dfa7b3aad7cf2a71 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:34:26 +0000 Subject: [PATCH 03/19] feat: remove telemetry and stop reading ./.env in stdio mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Blocks-maintained fork must not phone home: drop src/telemetry (PostHog) and posthog-node, the --no-telemetry flag, FRAMELINK_TELEMETRY / DO_NOT_TRACK, and the per-call outcome hooks that only existed to feed it. The validateToolInput monkey patch stays, reduced to its user-facing half ("Invalid : "), as src/mcp/validation-errors.ts. A stdio server is spawned with an arbitrary cwd — in a Blocks sandbox the user's repository — so it no longer auto-loads ./.env (dotenv's override:true would let a repo file replace the host-injected credentials). An explicit --env still loads; HTTP mode and the fetch CLI keep the implicit load. 🤖 Generated with BLOCKS! --- package.json | 1 - pnpm-lock.yaml | 21 --- src/bin.ts | 4 - src/commands/fetch.ts | 29 +-- src/config.ts | 44 ++--- src/mcp/index.ts | 52 +----- src/mcp/tools/download-figma-images-tool.ts | 65 ++----- src/mcp/tools/get-figma-data-tool.ts | 11 -- src/mcp/validation-capture.ts | 161 ----------------- src/mcp/validation-errors.ts | 110 ++++++++++++ src/server.ts | 59 ++---- src/services/download-figma-images.ts | 190 ++++++++------------ src/services/figma.ts | 8 +- src/services/get-figma-data.ts | 163 +++++++---------- src/telemetry/capture.ts | 152 ---------------- src/telemetry/client.ts | 182 ------------------- src/telemetry/index.ts | 29 --- src/telemetry/types.ts | 87 --------- src/tests/config.test.ts | 38 +++- src/tests/path-validation.test.ts | 43 +---- src/tests/telemetry-redaction.test.ts | 101 ----------- src/tests/validation-reject.test.ts | 114 +++--------- src/utils/error-meta.ts | 7 +- src/utils/fetch-json.ts | 2 +- src/utils/proxy-env.ts | 4 +- 25 files changed, 385 insertions(+), 1292 deletions(-) delete mode 100644 src/mcp/validation-capture.ts create mode 100644 src/mcp/validation-errors.ts delete mode 100644 src/telemetry/capture.ts delete mode 100644 src/telemetry/client.ts delete mode 100644 src/telemetry/index.ts delete mode 100644 src/telemetry/types.ts delete mode 100644 src/tests/telemetry-redaction.test.ts diff --git a/package.json b/package.json index 7712e14c..842216cb 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,6 @@ "dotenv": "^16.4.7", "express": "^5.3.0", "js-yaml": "^4.3.2", - "posthog-node": "^5.29.2", "remeda": "^2.20.1", "undici": "^7.30.1", "zod": "^4.6.6" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 535e09e1..77ed78b5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -56,9 +56,6 @@ importers: js-yaml: specifier: ^4.3.2 version: 4.3.2 - posthog-node: - specifier: ^5.29.2 - version: 5.29.2 remeda: specifier: ^2.20.1 version: 2.20.1 @@ -415,9 +412,6 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} - '@posthog/core@1.25.2': - resolution: {integrity: sha512-h2FO7ut/BbfwpAXWpwdDHTzQgUo9ibDFEs6ZO+3cI3KPWQt5XwczK1OLAuPprcjm8T/jl0SH8jSFo5XdU4RbTg==} - '@rollup/rollup-android-arm-eabi@4.59.0': resolution: {integrity: sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==} cpu: [arm] @@ -1488,15 +1482,6 @@ packages: resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} engines: {node: ^10 || ^12 || >=14} - posthog-node@5.29.2: - resolution: {integrity: sha512-rI7kkF0XqDc0G1qjx+Hb4iuY9NAlL+XQNoGOpnEpRNTUcXvjY6WlsRGZ9m2whgc39emrrYdszi/YT8wZkr2xsg==} - engines: {node: ^20.20.0 || >=22.22.0} - peerDependencies: - rxjs: ^7.0.0 - peerDependenciesMeta: - rxjs: - optional: true - prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -2150,8 +2135,6 @@ snapshots: '@pkgjs/parseargs@0.11.0': optional: true - '@posthog/core@1.25.2': {} - '@rollup/rollup-android-arm-eabi@4.59.0': optional: true @@ -3190,10 +3173,6 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - posthog-node@5.29.2: - dependencies: - '@posthog/core': 1.25.2 - prelude-ls@1.2.1: {} prettier@3.5.0: {} diff --git a/src/bin.ts b/src/bin.ts index c6075341..4bac32df 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -55,10 +55,6 @@ const argv = cli({ type: Boolean, description: "Run in stdio transport mode for MCP clients", }, - noTelemetry: { - type: Boolean, - description: "Disable usage telemetry (telemetry is on by default)", - }, }, commands: [fetchCommand], }); diff --git a/src/commands/fetch.ts b/src/commands/fetch.ts index 7ab4d89c..b3838027 100644 --- a/src/commands/fetch.ts +++ b/src/commands/fetch.ts @@ -8,7 +8,6 @@ import { } from "~/config.js"; import { FigmaService } from "~/services/figma.js"; import { parseFigmaUrl } from "~/utils/figma-url.js"; -import { authMode, initTelemetry, captureGetFigmaDataCall, shutdown } from "~/telemetry/index.js"; import { getFigmaData } from "~/services/get-figma-data.js"; import type { OutputFormat } from "~/utils/serialize.js"; @@ -50,19 +49,13 @@ export const fetchCommand: Command = command( type: String, description: "Path to .env file", }, - noTelemetry: { - type: Boolean, - description: "Disable usage telemetry", - }, }, }, (argv) => { - run(argv.flags, argv._) - .catch((error) => { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; - }) - .finally(() => shutdown()); + run(argv.flags, argv._).catch((error) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); }, ); @@ -76,7 +69,6 @@ async function run( figmaApiKey?: string; figmaOauthToken?: string; env?: string; - noTelemetry?: boolean; }, positionals: string[], ) { @@ -106,15 +98,6 @@ async function run( // one from `getAuthHeaders`. requireGlobalCredentials(auth); - // Initialize telemetry only after input validation succeeds, so every - // captured event corresponds to an actual fetch attempt (not a usage error). - initTelemetry({ - optOut: flags.noTelemetry, - immediateFlush: true, - redactFromErrors: [auth.figmaApiKey, auth.figmaOAuthToken], - }); - - const mode = authMode(auth); // The fetch CLI stays yaml-by-default (unlike the MCP server, which defaults // to tree): its output is piped into standard tooling (`> out.yaml`, `| jq`), // where tree's bespoke indented format isn't parseable. Tree's token-efficiency @@ -126,10 +109,6 @@ async function run( new FigmaService(auth), { fileKey, nodeId, depth: flags.depth }, outputFormat, - { - onComplete: (outcome) => - captureGetFigmaDataCall(outcome, { transport: "cli", authMode: mode }), - }, ); console.log(result.formatted); } diff --git a/src/config.ts b/src/config.ts index 97c98bcf..ad67939b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,7 +1,6 @@ import { config as loadEnv } from "dotenv"; import { resolve as resolvePath } from "path"; import type { FigmaAuthOptions } from "./services/figma.js"; -import { resolveTelemetryEnabled } from "./telemetry/index.js"; import { VALID_OUTPUT_FORMATS, isOutputFormat, type OutputFormat } from "./utils/serialize.js"; export type Source = "cli" | "env" | "default"; @@ -23,7 +22,6 @@ export interface ServerFlags { imageDir?: string; proxy?: string; stdio?: boolean; - noTelemetry?: boolean; } export interface ServerConfig { @@ -35,7 +33,6 @@ export interface ServerConfig { skipImageDownloads: boolean; imageDir: string; isStdioMode: boolean; - noTelemetry: boolean; configSources: Record; } @@ -65,10 +62,9 @@ export function envBool(name: string): boolean | undefined { return undefined; } -// Throws on invalid input so callers control how the failure surfaces — the -// server entry point exits the process, but the `fetch` CLI command needs to -// run its `finally` (telemetry shutdown) before exiting, which `process.exit` -// would bypass. +// Throws on invalid input so callers control how the failure surfaces (the +// server entry point exits the process; the `fetch` CLI sets an exit code) and +// so the validators stay pure for library consumers. export function parseOutputFormat( value: string | undefined, source: string, @@ -85,9 +81,19 @@ function maskApiKey(key: string): string { return `****${key.slice(-4)}`; } -export function loadEnvFile(envPath?: string): string { +/** + * Load an env file. An explicit `--env ` is always honored. Without one, + * `./.env` is only picked up when `implicit` is set: HTTP mode and the `fetch` + * CLI are run by a person from their own project, but a stdio server is + * spawned by an MCP client with an arbitrary cwd — in a Blocks sandbox that is + * the user's repository, whose `.env` must not be able to override the + * credentials the host injected (`override: true` lets the file win). + */ +export function loadEnvFile(envPath: string | undefined, { implicit = true } = {}): string { const envFilePath = envPath ? resolvePath(envPath) : resolvePath(process.cwd(), ".env"); - loadEnv({ path: envFilePath, override: true }); + if (envPath || implicit) { + loadEnv({ path: envFilePath, override: true }); + } return envFilePath; } @@ -137,8 +143,10 @@ export function requireGlobalCredentials(auth: FigmaAuthOptions): void { } export function getServerConfig(flags: ServerFlags): ServerConfig { + const isStdioMode = flags.stdio === true; + // Load .env before resolving env-backed values - const envFilePath = loadEnvFile(flags.env); + const envFilePath = loadEnvFile(flags.env, { implicit: !isStdioMode }); const envFileSource: Source = flags.env !== undefined ? "cli" : "default"; // Auth @@ -173,16 +181,6 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { const formatFromEnv = parseOutputFormat(envStr("OUTPUT_FORMAT"), "OUTPUT_FORMAT"); const outputFormat = resolve(formatFromFlag, formatFromEnv, "tree"); - const isStdioMode = flags.stdio === true; - - const noTelemetry = flags.noTelemetry ?? false; - const telemetrySource: Source = - flags.noTelemetry === true - ? "cli" - : process.env.FRAMELINK_TELEMETRY !== undefined || process.env.DO_NOT_TRACK !== undefined - ? "env" - : "default"; - const configSources: Record = { envFile: envFileSource, figmaApiKey: figmaApiKey.source, @@ -193,7 +191,6 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { outputFormat: outputFormat.source, skipImageDownloads: skipImageDownloads.source, imageDir: imageDir.source, - telemetry: telemetrySource, }; if (!isStdioMode) { @@ -220,10 +217,6 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { `- SKIP_IMAGE_DOWNLOADS: ${skipImageDownloads.value} (source: ${configSources.skipImageDownloads})`, ); console.log(`- IMAGE_DIR: ${imageDir.value} (source: ${configSources.imageDir})`); - const telemetryEnabled = resolveTelemetryEnabled(noTelemetry); - console.log( - `- TELEMETRY: ${telemetryEnabled ? "enabled" : "disabled"} (source: ${configSources.telemetry})`, - ); console.log(); } @@ -236,7 +229,6 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { skipImageDownloads: skipImageDownloads.value, imageDir: imageDir.value, isStdioMode, - noTelemetry, configSources, }; } diff --git a/src/mcp/index.ts b/src/mcp/index.ts index 1ff61999..1e796d12 100644 --- a/src/mcp/index.ts +++ b/src/mcp/index.ts @@ -1,9 +1,8 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { FigmaService, type FigmaAuthOptions } from "../services/figma.js"; import { Logger } from "../utils/logger.js"; -import { authMode, type AuthMode, type ClientInfo, type Transport } from "~/telemetry/index.js"; import type { OutputFormat } from "~/utils/serialize.js"; -import { installValidationRejectCapture } from "./validation-capture.js"; +import { installFriendlyValidationErrors } from "./validation-errors.js"; import type { ToolExtra } from "./progress.js"; import { downloadFigmaImagesTool, @@ -19,7 +18,7 @@ const serverInfo = { "Gives AI coding agents access to Figma design data, providing layout, styling, and content information for implementing designs.", }; -type ServerTransport = Extract; +type ServerTransport = "stdio" | "http"; export type CreateServerOptions = { transport: ServerTransport; @@ -34,29 +33,9 @@ function createServer( ) { const server = new McpServer(serverInfo); const figmaService = new FigmaService(authOptions); - const mode = authMode(authOptions); - const getClientInfo = (): ClientInfo | undefined => { - const info = server.server.getClientVersion(); - if (!info) return undefined; - return { name: info.name, version: info.version }; - }; - - registerTools(server, figmaService, { - transport, - authMode: mode, - outputFormat, - skipImageDownloads, - imageDir, - getClientInfo, - }); - - installValidationRejectCapture(server, { - transport, - authMode: mode, - outputFormat, - getClientInfo, - }); + registerTools(server, figmaService, { outputFormat, skipImageDownloads, imageDir }); + installFriendlyValidationErrors(server); Logger.isHTTP = transport !== "stdio"; @@ -64,12 +43,9 @@ function createServer( } type RegisterToolsOptions = { - transport: ServerTransport; - authMode: AuthMode; outputFormat: OutputFormat; skipImageDownloads: boolean; imageDir?: string; - getClientInfo: () => ClientInfo | undefined; }; function registerTools( @@ -86,15 +62,7 @@ function registerTools( annotations: { readOnlyHint: true }, }, (params: GetFigmaDataParams, extra: ToolExtra) => - getFigmaDataTool.handler( - params, - figmaService, - options.outputFormat, - options.transport, - options.authMode, - options.getClientInfo(), - extra, - ), + getFigmaDataTool.handler(params, figmaService, options.outputFormat, extra), ); if (!options.skipImageDownloads) { @@ -107,15 +75,7 @@ function registerTools( annotations: { openWorldHint: true }, }, (params: DownloadImagesParams, extra: ToolExtra) => - downloadFigmaImagesTool.handler( - params, - figmaService, - options.imageDir, - options.transport, - options.authMode, - options.getClientInfo(), - extra, - ), + downloadFigmaImagesTool.handler(params, figmaService, options.imageDir, extra), ); } } diff --git a/src/mcp/tools/download-figma-images-tool.ts b/src/mcp/tools/download-figma-images-tool.ts index 25103568..4a465a13 100644 --- a/src/mcp/tools/download-figma-images-tool.ts +++ b/src/mcp/tools/download-figma-images-tool.ts @@ -1,12 +1,5 @@ import path from "path"; import { z } from "zod"; -import { - type AuthMode, - type ClientInfo, - captureDownloadImagesCall, - captureValidationReject, - type Transport, -} from "~/telemetry/index.js"; import { downloadFigmaImages as runDownloadFigmaImages } from "../../services/download-figma-images.js"; import type { FigmaService } from "../../services/figma.js"; import { type ResolveLocalPathFailureReason, resolveLocalPath } from "../../utils/local-path.js"; @@ -95,9 +88,6 @@ async function downloadFigmaImages( params: DownloadImagesParams, figmaService: FigmaService, imageDir: string | undefined, - transport: Transport, - authMode: AuthMode, - clientInfo: ClientInfo | undefined, extra: ToolExtra, ) { try { @@ -110,22 +100,11 @@ async function downloadFigmaImages( const baseDir = imageDir ?? process.cwd(); const resolution = resolveLocalPath(localPath, baseDir); if (!resolution.ok) { - // Path-traversal rejection happens after schema validation, so the SDK - // wrapper in mcp/index.ts never sees it. Capture it here as a validation - // reject so we can track how often LLMs trip over the localPath contract. - const details = rejectionDetails(resolution.reason, localPath, baseDir); - captureValidationReject( - { - tool: "download_figma_images", - field: "localPath", - rule: details.rule, - message: details.telemetryMessage, - }, - { transport, authMode, clientInfo }, - ); return { isError: true, - content: [{ type: "text" as const, text: details.userMessage }], + content: [ + { type: "text" as const, text: rejectionMessage(resolution.reason, localPath, baseDir) }, + ], }; } const resolvedPath = resolution.resolvedPath; @@ -144,12 +123,6 @@ async function downloadFigmaImages( onDownloadComplete: () => { stopHeartbeat?.(); }, - onComplete: (outcome) => - captureDownloadImagesCall(outcome, { - transport, - authMode, - clientInfo, - }), }, ); @@ -207,24 +180,17 @@ function getDescription(imageDir?: string) { return `Download SVG and PNG images used in a Figma file based on the IDs of image or icon nodes. Images will be saved relative to the server's image directory: ${baseDir}`; } -function rejectionDetails( +function rejectionMessage( reason: ResolveLocalPathFailureReason, localPath: string, baseDir: string, -): { - rule: ResolveLocalPathFailureReason; - userMessage: string; - telemetryMessage: string; -} { +): string { switch (reason) { case "drive_letter_on_posix": - return { - rule: reason, - telemetryMessage: `Drive-letter path on POSIX server: ${localPath}`, - userMessage: - `Invalid path: "${localPath}" starts with a Windows drive letter, but this server is running on POSIX where drive letters don't exist. ` + - `The server's image directory is "${baseDir}"; pass a path relative to it (e.g., "public/images").`, - }; + return ( + `Invalid path: "${localPath}" starts with a Windows drive letter, but this server is running on POSIX where drive letters don't exist. ` + + `The server's image directory is "${baseDir}"; pass a path relative to it (e.g., "public/images").` + ); case "outside_image_dir": { // Leading-slash inputs used to be silently re-interpreted as relative // under the old path.join hack. They now reject; spell out the retry so @@ -233,14 +199,11 @@ function rejectionDetails( const leadingSlashHint = /^[/\\]/.test(localPath) ? ` If you meant a directory inside the image directory, drop the leading slash (e.g., use "${localPath.replace(/^[/\\]+/, "")}").` : ""; - return { - rule: reason, - telemetryMessage: `Path resolves outside allowed image directory: ${localPath}`, - userMessage: - `Invalid path: "${localPath}" resolves outside the allowed image directory. ` + - `The server's image directory is "${baseDir}". Provide a path relative to this directory (e.g., "public/images" or "assets/icons").` + - leadingSlashHint, - }; + return ( + `Invalid path: "${localPath}" resolves outside the allowed image directory. ` + + `The server's image directory is "${baseDir}". Provide a path relative to this directory (e.g., "public/images" or "assets/icons").` + + leadingSlashHint + ); } } } diff --git a/src/mcp/tools/get-figma-data-tool.ts b/src/mcp/tools/get-figma-data-tool.ts index 89c19c28..0580d1d0 100644 --- a/src/mcp/tools/get-figma-data-tool.ts +++ b/src/mcp/tools/get-figma-data-tool.ts @@ -2,12 +2,6 @@ import { z } from "zod"; import { FigmaService } from "~/services/figma.js"; import { Logger } from "~/utils/logger.js"; import { sendProgress, startProgressHeartbeat, type ToolExtra } from "~/mcp/progress.js"; -import { - captureGetFigmaDataCall, - type AuthMode, - type ClientInfo, - type Transport, -} from "~/telemetry/index.js"; import { getFigmaData as runGetFigmaData } from "~/services/get-figma-data.js"; import type { OutputFormat } from "~/utils/serialize.js"; @@ -43,9 +37,6 @@ async function getFigmaData( params: GetFigmaDataParams, figmaService: FigmaService, outputFormat: OutputFormat, - transport: Transport, - authMode: AuthMode, - clientInfo: ClientInfo | undefined, extra: ToolExtra, ) { try { @@ -85,8 +76,6 @@ async function getFigmaData( onSerializeStart: async () => { await sendProgress(extra, 2, 3, "Simplified design, serializing response"); }, - onComplete: (outcome) => - captureGetFigmaDataCall(outcome, { transport, authMode, clientInfo }), }); Logger.log(`Successfully extracted data: ${result.metrics.simplifiedNodeCount} nodes`); diff --git a/src/mcp/validation-capture.ts b/src/mcp/validation-capture.ts deleted file mode 100644 index 40de5939..00000000 --- a/src/mcp/validation-capture.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js"; -import { - captureValidationReject, - type ClientInfo, - type Transport, - type AuthMode, -} from "~/telemetry/index.js"; -import type { OutputFormat } from "~/utils/serialize.js"; - -/** - * The MCP SDK validates tool input against the registered zod schema BEFORE - * calling our handler — failed validations bubble up as `McpError` and never - * reach our code, so we can't observe them from inside the tool callback. - * - * To capture validation rejects we monkey-patch the McpServer instance's - * `validateToolInput` method (private SDK API). Knowing exactly what shape of - * tool call LLMs are getting wrong is one of the most actionable analytics - * signals available — worth the small coupling cost. We patch the instance - * (not the prototype) so concurrent McpServer instances in HTTP mode each - * own their patched copy. - * - * Hardening notes: - * - Fails open if `validateToolInput` ever disappears from the SDK — losing - * telemetry is preferable to crashing the server during creation. - * - The second parse (used to extract structured field/rule info) runs inside - * its own try/catch so a future schema with side-effecting refinements can't - * corrupt the SDK's normal error response. - * - Prefers `safeParseAsync` so async-aware schemas don't throw on sync parse. - * - Normalizes numeric path segments to `[]` so `nodes.0.fileName` and - * `nodes.1.fileName` collapse to `nodes[].fileName` instead of inflating - * `validation_field` cardinality in PostHog. - * - Replaces the SDK's noisy "MCP error -32602: Input validation error: ..." - * message with a clean, LLM-friendly version: "Invalid : ". - */ -export function installValidationRejectCapture( - server: McpServer, - context: { - transport: Transport; - authMode: AuthMode; - outputFormat: OutputFormat; - getClientInfo: () => ClientInfo | undefined; - }, -): void { - type ZodIssue = { - path?: Array; - code?: string; - message?: string; - }; - type SafeParseResult = { success: boolean; error?: { issues?: ZodIssue[] } }; - type ValidatableSchema = { - safeParse?: (args: unknown) => SafeParseResult; - safeParseAsync?: (args: unknown) => Promise; - }; - type ValidatedTool = { inputSchema?: ValidatableSchema }; - type Patchable = { - validateToolInput?: (tool: ValidatedTool, args: unknown, toolName: string) => Promise; - }; - - const patchable = server as unknown as Patchable; - // Fail open if the SDK ever renames or removes this private method — we - // lose validation reject telemetry, but the server still starts. - if (typeof patchable.validateToolInput !== "function") { - return; - } - const original = patchable.validateToolInput.bind(server); - - patchable.validateToolInput = async (tool, args, toolName) => { - try { - return await original(tool, args, toolName); - } catch (error) { - if (error instanceof McpError && error.code === ErrorCode.InvalidParams) { - const issue = await extractIssue(tool, args); - - if (toolName === "get_figma_data" || toolName === "download_figma_images") { - captureValidationReject( - { - tool: toolName, - field: normalizeFieldPath(issue?.path), - rule: issue?.code ?? "unknown", - message: issue?.message ?? error.message, - outputFormat: context.outputFormat, - }, - { - transport: context.transport, - authMode: context.authMode, - clientInfo: context.getClientInfo(), - }, - ); - } - - // Replace the SDK's noisy "MCP error -32602: Input validation error: - // Invalid arguments for tool ...: [{...JSON...}]" with a clean message - // the LLM can act on. The SDK's createToolError uses error.message - // regardless of error type, so a plain Error works fine here. - if (issue) { - throw new Error(`Invalid ${normalizeFieldPath(issue.path)}: ${issue.message}`); - } - } - throw error; - } - }; -} - -type ZodIssue = { - path?: Array; - code?: string; - message?: string; -}; - -/** - * Best-effort structured issue extraction. Prefers `safeParseAsync` to align - * with how the SDK validates — async schemas (refinements/transforms) need it. - * Wrapped in try/catch so a future schema with side effects can't corrupt the - * SDK's normal error response. - */ -async function extractIssue( - tool: { - inputSchema?: { - safeParse?: (args: unknown) => { success: boolean; error?: { issues?: ZodIssue[] } }; - safeParseAsync?: ( - args: unknown, - ) => Promise<{ success: boolean; error?: { issues?: ZodIssue[] } }>; - }; - }, - args: unknown, -): Promise { - try { - const schema = tool.inputSchema; - if (schema?.safeParseAsync) { - const result = await schema.safeParseAsync(args); - if (!result.success) return result.error?.issues?.[0]; - } else if (schema?.safeParse) { - const result = schema.safeParse(args); - if (!result.success) return result.error?.issues?.[0]; - } - } catch { - // The second parse can throw if a future schema has side-effecting - // refinements. Falling back loses field/rule precision but keeps the - // SDK's normal error response intact for the client. - } - return undefined; -} - -/** - * Render a zod error path with array indexes collapsed to `[]`. Without this, - * `nodes.0.fileName` / `nodes.1.fileName` would explode validation_field - * cardinality with no analytical value. - */ -export function normalizeFieldPath(path: Array | undefined): string { - if (!path || path.length === 0) return "(root)"; - let out = ""; - for (const segment of path) { - if (typeof segment === "number") { - out += "[]"; - } else { - out += out.length > 0 ? "." + segment : segment; - } - } - return out; -} diff --git a/src/mcp/validation-errors.ts b/src/mcp/validation-errors.ts new file mode 100644 index 00000000..82b22aea --- /dev/null +++ b/src/mcp/validation-errors.ts @@ -0,0 +1,110 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js"; + +/** + * The MCP SDK validates tool input against the registered zod schema BEFORE + * calling our handler, and reports failures as "MCP error -32602: Input + * validation error: Invalid arguments for tool ...: [{...JSON...}]" — noise an + * LLM rarely recovers from. We monkey-patch the McpServer instance's + * `validateToolInput` (private SDK API) to rethrow the first issue as a clean + * "Invalid : " the model can act on. + * + * Patched per instance (not on the prototype) so concurrent McpServer + * instances in HTTP mode each own their copy. + * + * Hardening notes: + * - Fails open if `validateToolInput` ever disappears from the SDK — a noisier + * message is preferable to crashing the server during creation. + * - The second parse (used to extract the structured issue) runs inside its + * own try/catch so a future schema with side-effecting refinements can't + * corrupt the SDK's normal error response. + * - Prefers `safeParseAsync` so async-aware schemas don't throw on sync parse. + */ +export function installFriendlyValidationErrors(server: McpServer): void { + type SafeParseResult = { success: boolean; error?: { issues?: ZodIssue[] } }; + type ValidatableSchema = { + safeParse?: (args: unknown) => SafeParseResult; + safeParseAsync?: (args: unknown) => Promise; + }; + type ValidatedTool = { inputSchema?: ValidatableSchema }; + type Patchable = { + validateToolInput?: (tool: ValidatedTool, args: unknown, toolName: string) => Promise; + }; + + const patchable = server as unknown as Patchable; + if (typeof patchable.validateToolInput !== "function") { + return; + } + const original = patchable.validateToolInput.bind(server); + + patchable.validateToolInput = async (tool, args, toolName) => { + try { + return await original(tool, args, toolName); + } catch (error) { + if (error instanceof McpError && error.code === ErrorCode.InvalidParams) { + const issue = await extractIssue(tool, args); + // The SDK's createToolError uses error.message regardless of error + // type, so a plain Error works fine here. + if (issue) { + throw new Error(`Invalid ${normalizeFieldPath(issue.path)}: ${issue.message}`); + } + } + throw error; + } + }; +} + +type ZodIssue = { + path?: Array; + code?: string; + message?: string; +}; + +/** + * Best-effort structured issue extraction. Prefers `safeParseAsync` to align + * with how the SDK validates — async schemas (refinements/transforms) need it. + */ +async function extractIssue( + tool: { + inputSchema?: { + safeParse?: (args: unknown) => { success: boolean; error?: { issues?: ZodIssue[] } }; + safeParseAsync?: ( + args: unknown, + ) => Promise<{ success: boolean; error?: { issues?: ZodIssue[] } }>; + }; + }, + args: unknown, +): Promise { + try { + const schema = tool.inputSchema; + if (schema?.safeParseAsync) { + const result = await schema.safeParseAsync(args); + if (!result.success) return result.error?.issues?.[0]; + } else if (schema?.safeParse) { + const result = schema.safeParse(args); + if (!result.success) return result.error?.issues?.[0]; + } + } catch { + // The second parse can throw if a future schema has side-effecting + // refinements. Falling back loses field precision but keeps the SDK's + // normal error response intact for the client. + } + return undefined; +} + +/** + * Render a zod error path with array indexes collapsed to `[]`, so the message + * names the field (`nodes[].nodeId`) rather than one row of it. + */ +export function normalizeFieldPath(path: Array | undefined): string { + if (!path || path.length === 0) return "(root)"; + let out = ""; + for (const segment of path) { + if (typeof segment === "number") { + out += "[]"; + } else { + out += out.length > 0 ? "." + segment : segment; + } + } + return out; +} diff --git a/src/server.ts b/src/server.ts index 136c8fc7..2e2e318f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,7 +11,6 @@ import { requireGlobalCredentials, type ServerConfig } from "./config.js"; import type { FigmaAuthOptions } from "./services/figma.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { ErrorCode } from "@modelcontextprotocol/sdk/types.js"; -import * as telemetry from "./telemetry/index.js"; let httpServer: Server | null = null; @@ -27,8 +26,7 @@ const activeConnections = new Set(); export async function startServer(config: ServerConfig): Promise { // Stdio has no per-request credential channel, so the server is unusable // without something resolved at startup. Fail fast BEFORE any side effects - // (proxy install, telemetry init) — preserves the pre-PR behavior where - // resolveAuth() exited early during config resolution. + // (proxy install). if (config.isStdioMode) { requireGlobalCredentials(config.auth); } @@ -50,20 +48,6 @@ export async function startServer(config: ServerConfig): Promise { setProxyMode("env"); } - const telemetryEnabled = telemetry.initTelemetry({ - optOut: config.noTelemetry, - redactFromErrors: [config.auth.figmaApiKey, config.auth.figmaOAuthToken], - }); - - if (telemetryEnabled) { - // stderr (not Logger.log) because in HTTP mode Logger.log writes to stdout, - // and in stdio mode stdout is reserved for MCP protocol messages. stderr - // is safe in both modes. - process.stderr.write( - "Usage telemetry enabled. Disable: FRAMELINK_TELEMETRY=off or DO_NOT_TRACK=1\n", - ); - } - const serverOptions = { transport: config.isStdioMode ? ("stdio" as const) : ("http" as const), outputFormat: config.outputFormat, @@ -100,9 +84,9 @@ export async function startServer(config: ServerConfig): Promise { } /** - * Register SIGINT + SIGTERM handlers that run mode-specific cleanup and then - * flush telemetry before exiting. MCP hosts commonly send SIGTERM, so both - * signals must be handled in both transport modes. + * Register SIGINT + SIGTERM handlers that run mode-specific cleanup and exit. + * MCP hosts commonly send SIGTERM, so both signals must be handled in both + * transport modes. * * Idempotent: if both signals fire (or a signal fires twice) the second * invocation is ignored so we never double-shutdown. @@ -112,13 +96,11 @@ function registerShutdownHandlers(onShutdown: () => Promise): void { const handle = async () => { if (shuttingDown) return; shuttingDown = true; - // onShutdown may throw (e.g. stopHttpServer failures); telemetry.shutdown - // swallows its own errors (see src/telemetry/client.ts). Use try/finally - // so process.exit(0) always runs regardless of onShutdown failure. + // onShutdown may throw (e.g. stopHttpServer failures); try/finally so + // process.exit(0) always runs regardless. try { await onShutdown(); } finally { - await telemetry.shutdown(); process.exit(0); } }; @@ -143,26 +125,19 @@ export async function startHttpServer( const requestKey = getRequestApiKey(req); const requestBearerToken = getRequestBearerToken(req); const auth = resolveRequestAuth(baseAuth, requestKey, requestBearerToken); - const requestSecrets = [requestKey, requestBearerToken].filter( - (secret): secret is string => !!secret, - ); - // Request-level credentials are not known to telemetry's init-time - // redaction list, so make them available only for this request scope. - await telemetry.withRequestSecrets(requestSecrets, async () => { - const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); - const mcpServer = createServer(auth, { ...serverOptions, transport: "http" }); - const conn: ActiveConnection = { transport, server: mcpServer }; - activeConnections.add(conn); - res.on("close", () => { - activeConnections.delete(conn); - transport.close(); - mcpServer.close(); - }); - await mcpServer.connect(transport); - await transport.handleRequest(req, res, req.body); - Logger.log("StreamableHTTP request handled"); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); + const mcpServer = createServer(auth, { ...serverOptions, transport: "http" }); + const conn: ActiveConnection = { transport, server: mcpServer }; + activeConnections.add(conn); + res.on("close", () => { + activeConnections.delete(conn); + transport.close(); + mcpServer.close(); }); + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + Logger.log("StreamableHTTP request handled"); }; const handleMethodNotAllowed = (_req: Request, res: Response) => { diff --git a/src/services/download-figma-images.ts b/src/services/download-figma-images.ts index 759e7c92..2d74e112 100644 --- a/src/services/download-figma-images.ts +++ b/src/services/download-figma-images.ts @@ -34,23 +34,9 @@ export type DownloadFigmaImagesResult = { successCount: number; }; -export type DownloadImagesOutcome = { - input: DownloadFigmaImagesInput; - durationMs: number; - imageCount: number; - successCount?: number; - error?: unknown; -}; - export type DownloadFigmaImagesHooks = { onDownloadStart?: (downloadCount: number) => void | Promise; onDownloadComplete?: () => void; - /** - * Fires exactly once per call, after the pipeline completes (success or - * failure). Observer errors are swallowed silently — a broken observer - * must never break the pipeline. - */ - onComplete?: (outcome: DownloadImagesOutcome) => void; }; /** @@ -67,116 +53,92 @@ export async function downloadFigmaImages( input: DownloadFigmaImagesInput, hooks: DownloadFigmaImagesHooks = {}, ): Promise { - const startedAt = Date.now(); - const imageCount = input.nodes.length; - let successCount: number | undefined; - let caughtError: unknown; - - try { - const { fileKey, nodes, localPath, pngScale } = input; - - // Resolve the set of unique downloads and track which requested - // filenames each one satisfies (so the caller can render aliases). - const downloadItems: Array<{ - fileName: string; - needsCropping: boolean; - cropTransform?: Transform; - requiresImageDimensions: boolean; - imageRef?: string; - gifRef?: string; - nodeId?: string; - }> = []; - const downloadToRequests = new Map(); - const seenDownloads = new Map(); - - for (const rawNode of nodes) { - const { nodeId: rawNodeId, ...node } = rawNode; - - // Replace - with : in nodeId for our query — Figma API expects :. - const nodeId = rawNodeId?.replace(/-/g, ":"); - - let finalFileName = node.fileName; - if (node.filenameSuffix && !finalFileName.includes(node.filenameSuffix)) { - const ext = finalFileName.split(".").pop(); - const nameWithoutExt = finalFileName.substring(0, finalFileName.lastIndexOf(".")); - finalFileName = `${nameWithoutExt}-${node.filenameSuffix}.${ext}`; - } + const { fileKey, nodes, localPath, pngScale } = input; + + // Resolve the set of unique downloads and track which requested + // filenames each one satisfies (so the caller can render aliases). + const downloadItems: Array<{ + fileName: string; + needsCropping: boolean; + cropTransform?: Transform; + requiresImageDimensions: boolean; + imageRef?: string; + gifRef?: string; + nodeId?: string; + }> = []; + const downloadToRequests = new Map(); + const seenDownloads = new Map(); + + for (const rawNode of nodes) { + const { nodeId: rawNodeId, ...node } = rawNode; + + // Replace - with : in nodeId for our query — Figma API expects :. + const nodeId = rawNodeId?.replace(/-/g, ":"); + + let finalFileName = node.fileName; + if (node.filenameSuffix && !finalFileName.includes(node.filenameSuffix)) { + const ext = finalFileName.split(".").pop(); + const nameWithoutExt = finalFileName.substring(0, finalFileName.lastIndexOf(".")); + finalFileName = `${nameWithoutExt}-${node.filenameSuffix}.${ext}`; + } - const downloadItem = { - fileName: finalFileName, - needsCropping: node.needsCropping || false, - cropTransform: node.cropTransform, - requiresImageDimensions: node.requiresImageDimensions || false, - }; + const downloadItem = { + fileName: finalFileName, + needsCropping: node.needsCropping || false, + cropTransform: node.cropTransform, + requiresImageDimensions: node.requiresImageDimensions || false, + }; + + if (node.gifRef) { + // GIF fills are always unique downloads (animated, no dedup needed). + const downloadIndex = downloadItems.length; + downloadItems.push({ ...downloadItem, gifRef: node.gifRef }); + downloadToRequests.set(downloadIndex, [finalFileName]); + } else if (node.imageRef) { + const uniqueKey = `${node.imageRef}-${node.filenameSuffix || "none"}`; + + if (!node.filenameSuffix && seenDownloads.has(uniqueKey)) { + const downloadIndex = seenDownloads.get(uniqueKey)!; + const requests = downloadToRequests.get(downloadIndex)!; + if (!requests.includes(finalFileName)) { + requests.push(finalFileName); + } - if (node.gifRef) { - // GIF fills are always unique downloads (animated, no dedup needed). - const downloadIndex = downloadItems.length; - downloadItems.push({ ...downloadItem, gifRef: node.gifRef }); - downloadToRequests.set(downloadIndex, [finalFileName]); - } else if (node.imageRef) { - const uniqueKey = `${node.imageRef}-${node.filenameSuffix || "none"}`; - - if (!node.filenameSuffix && seenDownloads.has(uniqueKey)) { - const downloadIndex = seenDownloads.get(uniqueKey)!; - const requests = downloadToRequests.get(downloadIndex)!; - if (!requests.includes(finalFileName)) { - requests.push(finalFileName); - } - - if (downloadItem.requiresImageDimensions) { - downloadItems[downloadIndex].requiresImageDimensions = true; - } - } else { - const downloadIndex = downloadItems.length; - downloadItems.push({ ...downloadItem, imageRef: node.imageRef }); - downloadToRequests.set(downloadIndex, [finalFileName]); - seenDownloads.set(uniqueKey, downloadIndex); + if (downloadItem.requiresImageDimensions) { + downloadItems[downloadIndex].requiresImageDimensions = true; } } else { - // Rendered nodes are always unique. const downloadIndex = downloadItems.length; - downloadItems.push({ ...downloadItem, nodeId }); + downloadItems.push({ ...downloadItem, imageRef: node.imageRef }); downloadToRequests.set(downloadIndex, [finalFileName]); + seenDownloads.set(uniqueKey, downloadIndex); } + } else { + // Rendered nodes are always unique. + const downloadIndex = downloadItems.length; + downloadItems.push({ ...downloadItem, nodeId }); + downloadToRequests.set(downloadIndex, [finalFileName]); } + } - await hooks.onDownloadStart?.(downloadItems.length); - let allDownloads: ImageProcessingResult[]; - try { - allDownloads = await figmaService.downloadImages(fileKey, localPath, downloadItems, { - pngScale, - }); - } catch (error) { - tagError(error, { phase: "download" }); - } finally { - hooks.onDownloadComplete?.(); - } - - successCount = allDownloads.filter(Boolean).length; - - const downloads = allDownloads.map((result, index) => ({ - result, - requestedFileNames: downloadToRequests.get(index) ?? [result.filePath], - })); - - return { downloads, successCount }; + await hooks.onDownloadStart?.(downloadItems.length); + let allDownloads: ImageProcessingResult[]; + try { + allDownloads = await figmaService.downloadImages(fileKey, localPath, downloadItems, { + pngScale, + }); } catch (error) { - caughtError = error; - throw error; + tagError(error, { phase: "download" }); } finally { - if (hooks.onComplete) { - try { - hooks.onComplete({ - input, - durationMs: Date.now() - startedAt, - imageCount, - successCount, - error: caughtError, - }); - } catch { - // intentionally empty - } - } + hooks.onDownloadComplete?.(); } + + const successCount = allDownloads.filter(Boolean).length; + + const downloads = allDownloads.map((result, index) => ({ + result, + requestedFileNames: downloadToRequests.get(index) ?? [result.filePath], + })); + + return { downloads, successCount }; } diff --git a/src/services/figma.ts b/src/services/figma.ts index b056844d..d0f14e74 100644 --- a/src/services/figma.ts +++ b/src/services/figma.ts @@ -71,8 +71,8 @@ export class FigmaService { /** * Like `request`, but also surfaces the raw response body size so callers - * can record it for telemetry. Only used by endpoints whose payload size - * we care about (`getRawFile` / `getRawNode`); image-fetching endpoints + * can report it in metrics. Only used by endpoints whose payload size we + * care about (`getRawFile` / `getRawNode`); image-fetching endpoints * continue to use `request` unchanged. */ private async requestWithSize(endpoint: string): Promise<{ data: T; rawSize: number }> { @@ -304,7 +304,7 @@ export class FigmaService { * Get raw Figma API response for a file (for use with flexible extractors). * * Returns the parsed body alongside the raw body size in bytes so callers - * can record payload size in telemetry. + * can report payload size in metrics. */ async getRawFile( fileKey: string, @@ -323,7 +323,7 @@ export class FigmaService { * Get raw Figma API response for specific nodes (for use with flexible extractors). * * Returns the parsed body alongside the raw body size in bytes so callers - * can record payload size in telemetry. + * can report payload size in metrics. */ async getRawNode( fileKey: string, diff --git a/src/services/get-figma-data.ts b/src/services/get-figma-data.ts index a144a4ab..b692b89f 100644 --- a/src/services/get-figma-data.ts +++ b/src/services/get-figma-data.ts @@ -29,14 +29,6 @@ export type GetFigmaDataResult = { metrics: GetFigmaDataMetrics; }; -export type GetFigmaDataOutcome = { - input: GetFigmaDataInput; - outputFormat: OutputFormat; - durationMs: number; - metrics?: GetFigmaDataMetrics; - error?: unknown; -}; - /** * Live progress reader exposed to onSimplifyStart so callers can render * heartbeats showing real-time node counts. Closes over the per-call counter @@ -52,13 +44,6 @@ export type GetFigmaDataHooks = { onSimplifyStart?: (progress: SimplifyProgress) => void | Promise; onSimplifyComplete?: () => void | Promise; onSerializeStart?: () => void | Promise; - /** - * Fires exactly once per call, after the pipeline completes (success or - * failure). Lets shells observe outcomes without embedding telemetry - * bookkeeping in the core. Observer errors are swallowed silently — a - * broken observer must never break the pipeline. - */ - onComplete?: (outcome: GetFigmaDataOutcome) => void; }; /** @@ -77,102 +62,78 @@ export async function getFigmaData( hooks: GetFigmaDataHooks = {}, ): Promise { const { fileKey, nodeId, depth } = input; - const startedAt = Date.now(); - let metrics: GetFigmaDataMetrics | undefined; - let caughtError: unknown; // Per-call counter shared with the walker. Lives in the call closure so // overlapping HTTP requests each have their own — no module-global state. const nodeCounter = { count: 0 }; + await hooks.onFetchStart?.(); + let rawResult: { data: GetFileResponse | GetFileNodesResponse; rawSize: number }; + const fetchStart = Date.now(); try { - await hooks.onFetchStart?.(); - let rawResult: { data: GetFileResponse | GetFileNodesResponse; rawSize: number }; - const fetchStart = Date.now(); - try { - if (nodeId) { - rawResult = await figmaService.getRawNode(fileKey, nodeId, depth); - } else { - rawResult = await figmaService.getRawFile(fileKey, depth); - } - } catch (error) { - tagError(error, { phase: "fetch" }); - } finally { - await hooks.onFetchComplete?.(); - } - const fetchMs = Date.now() - fetchStart; - const rawApiResponse = rawResult.data; - const rawSizeKb = rawResult.rawSize / 1024; - - await hooks.onSimplifyStart?.({ getNodeCount: () => nodeCounter.count }); - let simplifiedDesign; - const simplifyStart = Date.now(); - try { - simplifiedDesign = await simplifyRawFigmaObject(rawApiResponse, allExtractors, { - maxDepth: depth, - afterChildren: collapseSvgContainers, - nodeCounter, - }); - } catch (error) { - tagError(error, { phase: "simplify" }); - } finally { - await hooks.onSimplifyComplete?.(); + if (nodeId) { + rawResult = await figmaService.getRawNode(fileKey, nodeId, depth); + } else { + rawResult = await figmaService.getRawFile(fileKey, depth); } - const simplifyMs = Date.now() - simplifyStart; + } catch (error) { + tagError(error, { phase: "fetch" }); + } finally { + await hooks.onFetchComplete?.(); + } + const fetchMs = Date.now() - fetchStart; + const rawApiResponse = rawResult.data; + const rawSizeKb = rawResult.rawSize / 1024; - writeLogs("figma-simplified.json", simplifiedDesign); + await hooks.onSimplifyStart?.({ getNodeCount: () => nodeCounter.count }); + let simplifiedDesign; + const simplifyStart = Date.now(); + try { + simplifiedDesign = await simplifyRawFigmaObject(rawApiResponse, allExtractors, { + maxDepth: depth, + afterChildren: collapseSvgContainers, + nodeCounter, + }); + } catch (error) { + tagError(error, { phase: "simplify" }); + } finally { + await hooks.onSimplifyComplete?.(); + } + const simplifyMs = Date.now() - simplifyStart; - const rawNodeCount = nodeCounter.count; - const hasVariables = detectVariables(rawApiResponse); - const namedStyleCount = countNamedStyles(rawApiResponse); - const measured = measureSimplifiedDesign(simplifiedDesign); + writeLogs("figma-simplified.json", simplifiedDesign); - await hooks.onSerializeStart?.(); - const serializeStart = Date.now(); - let formatted: string; - try { - formatted = serializeResult(wrapForSerialization(simplifiedDesign), outputFormat); - } catch (error) { - tagError(error, { phase: "serialize" }); - } - const simplifiedSizeKb = Buffer.byteLength(formatted, "utf8") / 1024; - const serializeMs = Date.now() - serializeStart; + const rawNodeCount = nodeCounter.count; + const hasVariables = detectVariables(rawApiResponse); + const namedStyleCount = countNamedStyles(rawApiResponse); + const measured = measureSimplifiedDesign(simplifiedDesign); - metrics = { - rawSizeKb, - simplifiedSizeKb, - rawNodeCount, - simplifiedNodeCount: measured.simplifiedNodeCount, - maxDepth: measured.maxDepth, - namedStyleCount, - componentCount: measured.componentCount, - instanceCount: measured.instanceCount, - textNodeCount: measured.textNodeCount, - imageNodeCount: measured.imageNodeCount, - componentPropertyCount: measured.componentPropertyCount, - hasVariables, - fetchMs, - simplifyMs, - serializeMs, - }; - return { formatted, metrics }; + await hooks.onSerializeStart?.(); + const serializeStart = Date.now(); + let formatted: string; + try { + formatted = serializeResult(wrapForSerialization(simplifiedDesign), outputFormat); } catch (error) { - caughtError = error; - throw error; - } finally { - if (hooks.onComplete) { - // Observer errors must never break the pipeline — e.g. a telemetry - // failure should not mask the tool's real result or its original error. - try { - hooks.onComplete({ - input, - outputFormat, - durationMs: Date.now() - startedAt, - metrics, - error: caughtError, - }); - } catch { - // intentionally empty - } - } + tagError(error, { phase: "serialize" }); } + const simplifiedSizeKb = Buffer.byteLength(formatted, "utf8") / 1024; + const serializeMs = Date.now() - serializeStart; + + const metrics: GetFigmaDataMetrics = { + rawSizeKb, + simplifiedSizeKb, + rawNodeCount, + simplifiedNodeCount: measured.simplifiedNodeCount, + maxDepth: measured.maxDepth, + namedStyleCount, + componentCount: measured.componentCount, + instanceCount: measured.instanceCount, + textNodeCount: measured.textNodeCount, + imageNodeCount: measured.imageNodeCount, + componentPropertyCount: measured.componentPropertyCount, + hasVariables, + fetchMs, + simplifyMs, + serializeMs, + }; + return { formatted, metrics }; } diff --git a/src/telemetry/capture.ts b/src/telemetry/capture.ts deleted file mode 100644 index c9d8a01a..00000000 --- a/src/telemetry/capture.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { getErrorMeta } from "~/utils/error-meta.js"; -import type { GetFigmaDataOutcome } from "~/services/get-figma-data.js"; -import type { DownloadImagesOutcome } from "~/services/download-figma-images.js"; -import { captureEvent } from "./client.js"; -import type { - CommonCallProps, - GetFigmaDataCall, - DownloadFigmaImagesCall, - ToolCallProperties, - ToolCallContext, - ValidationRejectInput, -} from "./types.js"; - -function captureToolCall(props: ToolCallProperties): void { - captureEvent("tool_called", props as unknown as Record); -} - -function errorFields( - error: unknown, -): Pick< - CommonCallProps, - | "is_error" - | "error_type" - | "error_message" - | "error_phase" - | "error_category" - | "http_status" - | "network_code" - | "fs_code" - | "is_retryable" -> { - if (error === undefined) return { is_error: false }; - const meta = getErrorMeta(error); - const rawMessage = error instanceof Error ? error.message : String(error); - return { - is_error: true, - error_type: error instanceof Error ? error.constructor.name : "Unknown", - error_message: rawMessage, - error_phase: meta.phase, - error_category: meta.category, - http_status: meta.http_status, - network_code: meta.network_code, - fs_code: meta.fs_code, - is_retryable: meta.is_retryable, - }; -} - -function toGetFigmaDataEvent( - outcome: GetFigmaDataOutcome, - context: ToolCallContext, -): GetFigmaDataCall { - return { - tool: "get_figma_data", - duration_ms: outcome.durationMs, - transport: context.transport, - auth_mode: context.authMode, - client_name: context.clientInfo?.name, - client_version: context.clientInfo?.version, - output_format: outcome.outputFormat, - depth: outcome.input.depth ?? null, - has_node_id: Boolean(outcome.input.nodeId), - raw_size_kb: outcome.metrics?.rawSizeKb, - simplified_size_kb: outcome.metrics?.simplifiedSizeKb, - raw_node_count: outcome.metrics?.rawNodeCount, - simplified_node_count: outcome.metrics?.simplifiedNodeCount, - max_depth: outcome.metrics?.maxDepth, - named_style_count: outcome.metrics?.namedStyleCount, - component_count: outcome.metrics?.componentCount, - instance_count: outcome.metrics?.instanceCount, - text_node_count: outcome.metrics?.textNodeCount, - image_node_count: outcome.metrics?.imageNodeCount, - component_property_count: outcome.metrics?.componentPropertyCount, - has_variables: outcome.metrics?.hasVariables, - fetch_ms: outcome.metrics?.fetchMs, - simplify_ms: outcome.metrics?.simplifyMs, - serialize_ms: outcome.metrics?.serializeMs, - ...errorFields(outcome.error), - }; -} - -function toDownloadImagesEvent( - outcome: DownloadImagesOutcome, - context: ToolCallContext, -): DownloadFigmaImagesCall { - return { - tool: "download_figma_images", - duration_ms: outcome.durationMs, - transport: context.transport, - auth_mode: context.authMode, - client_name: context.clientInfo?.name, - client_version: context.clientInfo?.version, - image_count: outcome.imageCount, - success_count: outcome.successCount, - ...errorFields(outcome.error), - }; -} - -export function captureGetFigmaDataCall( - outcome: GetFigmaDataOutcome, - context: ToolCallContext, -): void { - captureToolCall(toGetFigmaDataEvent(outcome, context)); -} - -export function captureDownloadImagesCall( - outcome: DownloadImagesOutcome, - context: ToolCallContext, -): void { - captureToolCall(toDownloadImagesEvent(outcome, context)); -} - -/** - * Capture a tool call that was rejected by input validation. Fires a regular - * `tool_called` event so PostHog dashboards can aggregate it alongside successful - * calls (filter by `error_phase == "validate"`). Most tool-specific metric - * fields are absent because the pipeline never ran — only validation context. - */ -export function captureValidationReject( - input: ValidationRejectInput, - context: ToolCallContext, -): void { - const common: CommonCallProps = { - duration_ms: input.durationMs ?? 0, - transport: context.transport, - auth_mode: context.authMode, - client_name: context.clientInfo?.name, - client_version: context.clientInfo?.version, - is_error: true, - error_type: "ValidationError", - error_message: input.message, - error_phase: "validate", - error_category: "invalid_input", - validation_field: input.field, - validation_rule: input.rule, - }; - - if (input.tool === "get_figma_data") { - captureToolCall({ - ...common, - tool: "get_figma_data", - output_format: input.outputFormat ?? "tree", - depth: null, - has_node_id: false, - }); - } else { - captureToolCall({ - ...common, - tool: "download_figma_images", - image_count: 0, - }); - } -} diff --git a/src/telemetry/client.ts b/src/telemetry/client.ts deleted file mode 100644 index 24b02a71..00000000 --- a/src/telemetry/client.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { AsyncLocalStorage } from "node:async_hooks"; -import { randomUUID } from "node:crypto"; -import { PostHog } from "posthog-node"; -import { proxyMode, type ProxyMode } from "~/utils/proxy-env.js"; -import type { InitTelemetryOptions } from "./types.js"; - -// Write-only project key for the Framelink MCP analytics project. -// This is intentionally embedded in the published package — it's a public -// ingest key that cannot read data, only send events. -const POSTHOG_API_KEY = "phc_w69pYvKwGNLsUHU4TGGpgAiscm8nhjudHgAJzAdzXkJV"; -const POSTHOG_HOST = "https://us.i.posthog.com"; - -type CommonProperties = { - server_version: string; - os_platform: NodeJS.Platform; - nodejs_major: number; - is_ci: boolean; - /** - * Which dispatcher the server installed for outbound fetches: - * `none` (Node default), `explicit` (--proxy/FIGMA_PROXY), or `env` - * (EnvHttpProxyAgent driven by HTTP_PROXY/HTTPS_PROXY/NO_PROXY). - * - * Lets us correlate failure rates (especially auth-category 403s — see - * issue #358) with the proxy configuration a user was actually running - * under, without logging the proxy URL itself. - */ - proxy_mode: ProxyMode; -}; - -let client: PostHog | undefined; -let sessionId: string | undefined; -let commonProps: CommonProperties | undefined; -let disabled = true; -let initialized = false; -let redactionSecrets: string[] = []; - -// Per-request redaction context. The init-time `redactionSecrets` list only -// covers credentials known at startup; with HTTP `X-Figma-Token` auth the -// real credential arrives per request and must not leak into telemetry. Each -// HTTP handler runs its body inside `withRequestSecrets(...)`, and capture -// merges the request-scoped list with the global one. AsyncLocalStorage -// propagates the value through the request's promise chain without us having -// to thread it down through every call site. -const requestSecrets = new AsyncLocalStorage(); - -export function withRequestSecrets( - secrets: readonly string[], - fn: () => Promise, -): Promise { - // Filter empties to avoid `replaceAll("", ...)`, which loops over every - // character of the message and produces nonsense output. - const filtered = secrets.filter(Boolean); - if (filtered.length === 0) return fn(); - return requestSecrets.run(filtered, fn); -} - -function parseNodeMajor(version: string): number { - return Number.parseInt(version.split(".")[0], 10); -} - -function redactErrorMessage(message: string): string { - let result = message; - for (const secret of redactionSecrets) { - result = result.replaceAll(secret, "[REDACTED]"); - } - for (const secret of requestSecrets.getStore() ?? []) { - result = result.replaceAll(secret, "[REDACTED]"); - } - return result; -} - -/** - * Telemetry is enabled by default. Any single opt-out signal disables it — - * the `optOut` flag (CLI), FRAMELINK_TELEMETRY=off, or a truthy DO_NOT_TRACK. - * Signals are OR'd, not prioritized, so users can't accidentally re-enable - * telemetry by setting one variable when another is already opting out. - * - * DO_NOT_TRACK follows the https://consoledonottrack.com/ convention: any - * non-empty value other than "0" means opt-out. - */ -export function resolveTelemetryEnabled(optOut?: boolean): boolean { - if (optOut === true) return false; - if (process.env.FRAMELINK_TELEMETRY === "off") return false; - const doNotTrack = process.env.DO_NOT_TRACK; - if (doNotTrack && doNotTrack !== "0") return false; - return true; -} - -export function initTelemetry(opts?: InitTelemetryOptions): boolean { - if (initialized) return !disabled; - - if (!resolveTelemetryEnabled(opts?.optOut)) { - disabled = true; - // Intentionally do NOT mark `initialized` here. An opted-out init must - // not poison subsequent re-init attempts (e.g. tests that opt out then - // opt in to verify capture). Re-running resolveTelemetryEnabled is cheap. - return false; - } - - initialized = true; - disabled = false; - sessionId = randomUUID(); - redactionSecrets = (opts?.redactFromErrors ?? []).filter(Boolean); - - commonProps = { - server_version: process.env.NPM_PACKAGE_VERSION ?? "unknown", - os_platform: process.platform, - nodejs_major: parseNodeMajor(process.versions.node), - is_ci: Boolean(process.env.CI), - proxy_mode: proxyMode(), - }; - - // disableGeoip: false is load-bearing — the Node SDK defaults GeoIP to off, - // and our geography analytics depend on it being enabled. - client = new PostHog(POSTHOG_API_KEY, { - host: POSTHOG_HOST, - disableGeoip: false, - ...(opts?.immediateFlush ? { flushAt: 1, flushInterval: 0 } : {}), - }); - - return true; -} - -/** - * Low-level event capture. Handles disabled state, redaction, and common - * property merging. Capture functions in capture.ts shape the event and - * delegate here. - * - * Telemetry must never surface errors to callers — this runs inside lifecycle - * observers where throwing would mask the tool's real return value (or its - * original error). Swallow silently; no logging because telemetry is supposed - * to be invisible. - */ -const MAX_ERROR_MESSAGE_LENGTH = 2000; - -function truncateForTelemetry(message: string): string { - return message.length > MAX_ERROR_MESSAGE_LENGTH - ? message.slice(0, MAX_ERROR_MESSAGE_LENGTH) + "…[truncated]" - : message; -} - -export function captureEvent(event: string, properties: Record): void { - if (disabled || !client || !sessionId || !commonProps) return; - - // Redact secrets BEFORE truncating so a token straddling the cut point - // can't survive as a partial match. - const errorMessage = properties.error_message; - const processed = - typeof errorMessage === "string" - ? { - ...properties, - error_message: truncateForTelemetry(redactErrorMessage(errorMessage)), - } - : properties; - - try { - client.capture({ - distinctId: sessionId, - event, - properties: { ...commonProps, ...processed }, - }); - } catch { - // intentionally empty - } -} - -export async function shutdown(): Promise { - if (disabled || !client) return; - - const current = client; - client = undefined; - disabled = true; - try { - await current.shutdown(); - } catch { - // Telemetry shutdown must never break callers — the server.ts shutdown - // handler and the fetch.ts cleye chain both depend on this resolving. - } - // Reset so the module can be re-initialized in the same process (relevant - // for tests; harmless in production where shutdown runs only at exit). - initialized = false; -} diff --git a/src/telemetry/index.ts b/src/telemetry/index.ts deleted file mode 100644 index 61e8d78c..00000000 --- a/src/telemetry/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { FigmaAuthOptions } from "~/services/figma.js"; -import type { AuthMode } from "./types.js"; - -export { initTelemetry, shutdown, resolveTelemetryEnabled, withRequestSecrets } from "./client.js"; -export { - captureGetFigmaDataCall, - captureDownloadImagesCall, - captureValidationReject, -} from "./capture.js"; -export type { - Transport, - AuthMode, - InitTelemetryOptions, - ClientInfo, - ToolCallContext, - ValidationRejectInput, -} from "./types.js"; - -/** - * Single source of truth for converting auth options into a telemetry - * `AuthMode`. `none` represents an HTTP server with no global credentials and - * no `X-Figma-Token` on the request — the call will fail in `getAuthHeaders`, - * and reporting it as `api_key` would skew multi-tenant deployment metrics. - */ -export function authMode(auth: FigmaAuthOptions): AuthMode { - if (auth.useOAuth) return "oauth"; - if (auth.figmaApiKey) return "api_key"; - return "none"; -} diff --git a/src/telemetry/types.ts b/src/telemetry/types.ts deleted file mode 100644 index 63d88cea..00000000 --- a/src/telemetry/types.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { OutputFormat } from "~/utils/serialize.js"; - -export type Transport = "stdio" | "http" | "cli"; -export type AuthMode = "oauth" | "api_key" | "none"; -export type ClientInfo = { name?: string; version?: string }; - -export interface InitTelemetryOptions { - optOut?: boolean; - /** - * Flush events immediately instead of batching. For short-lived processes - * (e.g. the `fetch` CLI command) that would otherwise exit before the - * default flush interval fires and drop the event. - */ - immediateFlush?: boolean; - /** - * Strings to scrub from `error_message` before sending events to PostHog. - * The shell passes whatever it considers sensitive (API keys, OAuth tokens, - * etc). Empty strings are filtered automatically so callers don't have to. - */ - redactFromErrors?: string[]; -} - -export type ToolCallContext = { - transport: Transport; - authMode: AuthMode; - clientInfo?: ClientInfo; -}; - -export type ValidationRejectInput = { - tool: "get_figma_data" | "download_figma_images"; - durationMs?: number; - field: string; - rule: string; - message: string; - outputFormat?: OutputFormat; -}; - -// Event schemas — used by capture.ts for shaping PostHog events. - -export type CommonCallProps = { - duration_ms: number; - transport: Transport; - auth_mode: AuthMode; - client_name?: string; - client_version?: string; - is_error: boolean; - error_type?: string; - error_message?: string; - error_phase?: string; - error_category?: string; - http_status?: number; - network_code?: string; - fs_code?: string; - is_retryable?: boolean; - validation_field?: string; - validation_rule?: string; -}; - -export type GetFigmaDataCall = CommonCallProps & { - tool: "get_figma_data"; - output_format: OutputFormat; - raw_size_kb?: number; - simplified_size_kb?: number; - raw_node_count?: number; - simplified_node_count?: number; - max_depth?: number; - named_style_count?: number; - component_count?: number; - instance_count?: number; - text_node_count?: number; - image_node_count?: number; - component_property_count?: number; - has_variables?: boolean; - fetch_ms?: number; - simplify_ms?: number; - serialize_ms?: number; - depth: number | null; - has_node_id: boolean; -}; - -export type DownloadFigmaImagesCall = CommonCallProps & { - tool: "download_figma_images"; - image_count: number; - success_count?: number; -}; - -export type ToolCallProperties = GetFigmaDataCall | DownloadFigmaImagesCall; diff --git a/src/tests/config.test.ts b/src/tests/config.test.ts index e8852000..a04d72bd 100644 --- a/src/tests/config.test.ts +++ b/src/tests/config.test.ts @@ -1,5 +1,8 @@ +import { mkdtempSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { envBool, envInt, envStr, resolve } from "~/config.js"; +import { envBool, envInt, envStr, loadEnvFile, resolve } from "~/config.js"; describe("resolve", () => { it("CLI flag wins over env and default", () => { @@ -87,3 +90,36 @@ describe("envBool", () => { expect(envBool("TEST_BOOL_MISSING")).toBeUndefined(); }); }); + +describe("loadEnvFile", () => { + const originalCwd = process.cwd(); + + afterEach(() => { + process.chdir(originalCwd); + vi.unstubAllEnvs(); + }); + + function projectWithDotEnv(): string { + const dir = mkdtempSync(join(tmpdir(), "figma-mcp-env-")); + writeFileSync(join(dir, ".env"), "FIGMA_API_KEY=from-repo-dotenv\n"); + return dir; + } + + it("ignores ./.env when implicit loading is off (stdio mode)", () => { + vi.stubEnv("FIGMA_API_KEY", "from-host"); + process.chdir(projectWithDotEnv()); + + loadEnvFile(undefined, { implicit: false }); + + expect(process.env.FIGMA_API_KEY).toBe("from-host"); + }); + + it("still honors an explicit --env path when implicit loading is off", () => { + vi.stubEnv("FIGMA_API_KEY", "from-host"); + const dir = projectWithDotEnv(); + + loadEnvFile(join(dir, ".env"), { implicit: false }); + + expect(process.env.FIGMA_API_KEY).toBe("from-repo-dotenv"); + }); +}); diff --git a/src/tests/path-validation.test.ts b/src/tests/path-validation.test.ts index e5827ebe..b6716436 100644 --- a/src/tests/path-validation.test.ts +++ b/src/tests/path-validation.test.ts @@ -1,19 +1,9 @@ import path from "path"; -import { describe, expect, it, vi, beforeEach } from "vitest"; - -vi.mock("~/telemetry/index.js", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - captureValidationReject: vi.fn(), - }; -}); - +import { describe, expect, it } from "vitest"; import { downloadFigmaImagesTool } from "~/mcp/tools/download-figma-images-tool.js"; import { downloadFigmaImage } from "~/utils/common.js"; import { resolveLocalPath, isWithin } from "~/utils/local-path.js"; import type { ToolExtra } from "~/mcp/progress.js"; -import * as telemetry from "~/telemetry/index.js"; const stubFigmaService = { downloadImages: () => Promise.resolve([]), @@ -33,31 +23,16 @@ const validParams = { describe("download path validation (handler)", () => { const imageDir = path.resolve("/project/root"); - beforeEach(() => { - vi.mocked(telemetry.captureValidationReject).mockClear(); - }); - - it("captures path-traversal attempts as validation rejects", async () => { + it("rejects path-traversal attempts without touching the Figma service", async () => { const result = await downloadFigmaImagesTool.handler( { ...validParams, localPath: "../../etc" }, stubFigmaService, imageDir, - "stdio", - "api_key", - undefined, stubExtra, ); expect(result.isError).toBe(true); - - const captureSpy = vi.mocked(telemetry.captureValidationReject); - expect(captureSpy).toHaveBeenCalledOnce(); - const [input, context] = captureSpy.mock.calls[0]; - expect(input.tool).toBe("download_figma_images"); - expect(input.field).toBe("localPath"); - expect(input.rule).toBe("outside_image_dir"); - expect(context.transport).toBe("stdio"); - expect(context.authMode).toBe("api_key"); + expect(result.content[0].text).toContain("resolves outside the allowed image directory"); }); it("rejects localPath that traverses outside imageDir", async () => { @@ -65,9 +40,6 @@ describe("download path validation (handler)", () => { { ...validParams, localPath: "../../etc" }, stubFigmaService, imageDir, - "stdio", - "api_key", - undefined, stubExtra, ); @@ -81,9 +53,6 @@ describe("download path validation (handler)", () => { { ...validParams, localPath: "/some/elsewhere" }, stubFigmaService, imageDir, - "stdio", - "api_key", - undefined, stubExtra, ); @@ -97,9 +66,6 @@ describe("download path validation (handler)", () => { { ...validParams, localPath: "public/images" }, stubFigmaService, imageDir, - "stdio", - "api_key", - undefined, stubExtra, ); @@ -115,9 +81,6 @@ describe("download path validation (handler)", () => { { ...validParams, localPath: "project/src/static/images/test" }, stubFigmaService, driveRoot, - "stdio", - "api_key", - undefined, stubExtra, ); diff --git a/src/tests/telemetry-redaction.test.ts b/src/tests/telemetry-redaction.test.ts deleted file mode 100644 index 60e8c2e7..00000000 --- a/src/tests/telemetry-redaction.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -// Mock posthog-node so we can observe what the telemetry client sends without -// hitting the network. We're testing OUR code (withRequestSecrets, ALS -// propagation, redactErrorMessage merge logic) end-to-end — only the system -// boundary is mocked. -const captureSpy = vi.fn(); -const shutdownSpy = vi.fn(async () => {}); -vi.mock("posthog-node", () => ({ - PostHog: class { - capture = captureSpy; - shutdown = shutdownSpy; - }, -})); - -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; -import type { Server } from "http"; -import type { AddressInfo } from "net"; -import { startHttpServer, stopHttpServer } from "~/server.js"; -import { initTelemetry, shutdown as shutdownTelemetry } from "~/telemetry/index.js"; - -const PER_REQUEST_KEY = "figd_TENANT_SECRET_xyz789"; - -describe("per-request telemetry redaction", () => { - let client: Client; - let httpServer: Server | undefined; - - beforeEach(() => { - captureSpy.mockClear(); - // Init with NO global redaction secrets so the assertion proves the - // per-request AsyncLocalStorage path is what's doing the scrubbing. - initTelemetry({ optOut: false, immediateFlush: true, redactFromErrors: [] }); - - // Stub fetch to fail with the per-request token embedded in the error - // message. FigmaService wraps the original message into a new Error, so - // the secret survives into `outcome.error.message` and reaches captureEvent. - const realFetch = globalThis.fetch; - vi.stubGlobal( - "fetch", - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - if (String(input).startsWith("https://api.figma.com")) { - throw new Error(`upstream failure (token=${PER_REQUEST_KEY})`); - } - return realFetch(input, init); - }), - ); - }); - - afterEach(async () => { - await client?.close(); - if (httpServer) { - await stopHttpServer(); - httpServer = undefined; - } - await shutdownTelemetry(); - vi.unstubAllGlobals(); - }); - - it("scrubs per-request X-Figma-Token from telemetry error_message", async () => { - httpServer = await startHttpServer( - "127.0.0.1", - 0, - { figmaApiKey: "", figmaOAuthToken: "", useOAuth: false }, - {}, - ); - const port = (httpServer.address() as AddressInfo).port; - - client = new Client({ name: "redaction-test", version: "1.0.0" }); - await client.connect( - new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { - requestInit: { headers: { "X-Figma-Token": PER_REQUEST_KEY } }, - }), - ); - - const result = await client.request( - { - method: "tools/call", - params: { name: "get_figma_data", arguments: { fileKey: "abc123" } }, - }, - CallToolResultSchema, - ); - // Sanity: the tool call should fail (fetch threw), so we know the error - // path actually fired. - expect(result.isError).toBe(true); - - const errorEvents = captureSpy.mock.calls - .map(([args]) => args) - .filter((args) => args?.properties?.is_error === true); - expect(errorEvents.length).toBeGreaterThan(0); - - for (const event of errorEvents) { - const message = String(event.properties.error_message ?? ""); - expect(message, `event ${event.event} leaked the per-request token`).not.toContain( - PER_REQUEST_KEY, - ); - expect(message).toContain("[REDACTED]"); - } - }); -}); diff --git a/src/tests/validation-reject.test.ts b/src/tests/validation-reject.test.ts index e2dae154..969b53d6 100644 --- a/src/tests/validation-reject.test.ts +++ b/src/tests/validation-reject.test.ts @@ -1,35 +1,21 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("~/telemetry/index.js", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - captureValidationReject: vi.fn(), - captureGetFigmaDataCall: vi.fn(), - captureDownloadImagesCall: vi.fn(), - }; -}); - +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createServer } from "~/mcp/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import * as telemetry from "~/telemetry/index.js"; /** * These tests cover the McpServer.validateToolInput monkey patch in - * src/mcp/index.ts. They use a real Client/Server pair over InMemoryTransport - * so the SDK validation path runs end-to-end — anything less wouldn't catch - * SDK upgrades that change the validation signature. + * src/mcp/validation-errors.ts. They use a real Client/Server pair over + * InMemoryTransport so the SDK validation path runs end-to-end — anything less + * wouldn't catch SDK upgrades that change the validation signature. */ -describe("validation reject capture (monkey patch)", () => { +describe("friendly validation errors (monkey patch)", () => { let client: Client; let server: McpServer; beforeEach(async () => { - vi.mocked(telemetry.captureValidationReject).mockClear(); - server = createServer( { figmaApiKey: "test-key", figmaOAuthToken: "", useOAuth: false }, { transport: "stdio" }, @@ -44,80 +30,34 @@ describe("validation reject capture (monkey patch)", () => { await server.close(); }); - it("captures structured field/rule when get_figma_data fileKey fails regex", async () => { - // McpServer catches the validation McpError and turns it into a tool - // result with isError=true (rather than rejecting the JSON-RPC request). - // Our monkey patch fires before that conversion. - const result = await client.request( - { - method: "tools/call", - params: { - name: "get_figma_data", - arguments: { fileKey: "invalid-key!" }, - }, - }, + async function callTool(name: string, args: Record) { + return client.request( + { method: "tools/call", params: { name, arguments: args } }, CallToolResultSchema, ); - expect(result.isError).toBe(true); + } - const captureSpy = vi.mocked(telemetry.captureValidationReject); - expect(captureSpy).toHaveBeenCalledOnce(); - const [input] = captureSpy.mock.calls[0]; - expect(input.tool).toBe("get_figma_data"); - expect(input.field).toBe("fileKey"); - // Zod regex failures emit invalid_string in v3 and invalid_format in v4 — - // accept either so the test doesn't break across SDK upgrades. - expect(input.rule).toMatch(/invalid_string|invalid_format/); - }); + function textOf(result: Awaited>): string { + const first = result.content[0]; + return first?.type === "text" ? first.text : ""; + } - it("normalizes array indexes to [] in nested validation_field", async () => { - // download_figma_images.nodes[0].nodeId fails the nodeId regex. - const result = await client.request( - { - method: "tools/call", - params: { - name: "download_figma_images", - arguments: { - fileKey: "abc123", - nodes: [{ nodeId: "BAD!!!", fileName: "x.png" }], - localPath: "images", - }, - }, - }, - CallToolResultSchema, - ); + it("names the failing field when get_figma_data fileKey fails its regex", async () => { + // McpServer catches the validation McpError and turns it into a tool + // result with isError=true (rather than rejecting the JSON-RPC request). + // Our monkey patch rewrites the message before that conversion. + const result = await callTool("get_figma_data", { fileKey: "invalid-key!" }); expect(result.isError).toBe(true); - - const captureSpy = vi.mocked(telemetry.captureValidationReject); - expect(captureSpy).toHaveBeenCalledOnce(); - const [input] = captureSpy.mock.calls[0]; - expect(input.tool).toBe("download_figma_images"); - // The literal index 0 should be collapsed so `nodes.0.nodeId` doesn't - // appear with high cardinality in PostHog. - expect(input.field).toBe("nodes[].nodeId"); + expect(textOf(result)).toMatch(/^Invalid fileKey: File key must be alphanumeric/); }); - it("does not capture validation rejects on successful tool calls", async () => { - // We don't actually want this to run the full pipeline — we only need to - // confirm the monkey patch doesn't fire on the success path. Use a - // syntactically valid fileKey; the call will fail later (no real API), but - // SDK validation will pass and captureValidationReject must not be called. - await client - .request( - { - method: "tools/call", - params: { - name: "get_figma_data", - arguments: { fileKey: "abc123" }, - }, - }, - CallToolResultSchema, - ) - .catch(() => { - // Network failure or tool-level error is fine — we don't care about the - // outcome, only that the validation hook stayed quiet. - }); - - expect(vi.mocked(telemetry.captureValidationReject)).not.toHaveBeenCalled(); + it("collapses array indexes to [] in nested field paths", async () => { + const result = await callTool("download_figma_images", { + fileKey: "abc123", + nodes: [{ nodeId: "BAD!!!", fileName: "x.png" }], + localPath: "images", + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/^Invalid nodes\[\]\.nodeId: Node ID must be like/); }); }); diff --git a/src/utils/error-meta.ts b/src/utils/error-meta.ts index f8dff388..7a0b8f7d 100644 --- a/src/utils/error-meta.ts +++ b/src/utils/error-meta.ts @@ -1,7 +1,8 @@ /** - * Structured metadata attached to thrown errors so telemetry can categorize - * failures without parsing error messages. Producers tag errors via `tagError`; - * consumers read merged meta from the error chain via `getErrorMeta`. + * Structured metadata attached to thrown errors so callers can branch on what + * failed (HTTP status, network code) without parsing error messages. Producers + * tag errors via `tagError`; consumers read merged meta from the error chain + * via `getErrorMeta`. * * Why a Symbol key: it never collides with caller-defined error fields and * doesn't show up in `Object.keys` or `JSON.stringify`, so attaching meta is diff --git a/src/utils/fetch-json.ts b/src/utils/fetch-json.ts index 4382888f..119ef3f8 100644 --- a/src/utils/fetch-json.ts +++ b/src/utils/fetch-json.ts @@ -81,7 +81,7 @@ export async function fetchJSON( is_retryable: RETRYABLE_STATUSES.has(response.status), }); } - // Read as text first so we can measure the raw body size for telemetry, + // Read as text first so we can report the raw body size in metrics, // then parse. This is the same work response.json() does internally, just // split so we can observe the byte count before parsing. const text = await response.text(); diff --git a/src/utils/proxy-env.ts b/src/utils/proxy-env.ts index a36ddacc..cd2680da 100644 --- a/src/utils/proxy-env.ts +++ b/src/utils/proxy-env.ts @@ -10,8 +10,8 @@ const PROXY_ENV_VARS = ["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"]; /** * Whether the host environment has any HTTP proxy var set (case-insensitive). - * Shared so server.ts, telemetry/client.ts, and figma.ts agree on what counts - * as "proxy env" — don't inline this check. + * Shared so every caller agrees on what counts as "proxy env" — don't inline + * this check. */ export function hasProxyEnv(): boolean { return PROXY_ENV_VARS.some((n) => process.env[n] || process.env[n.toLowerCase()]); From 7d466cd848cb31d8eb4aa19da5d5f18da0dffec5 Mon Sep 17 00:00:00 2001 From: "vitalii.semianchuk" Date: Mon, 6 Jul 2026 21:08:20 +0100 Subject: [PATCH 04/19] fix: envInt returns NaN for non-numeric env vars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parseInt("abc", 10) returns NaN which propagated as a valid number through the config system — setting PORT=abc would try to listen on port NaN. added isNaN check so non-numeric values are skipped. (cherry picked from commit 1fe9b8b890bbd10af8857bae723febde6a158d95) 🤖 Generated with BLOCKS! --- json-render | 1 + src/config.ts | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 160000 json-render diff --git a/json-render b/json-render new file mode 160000 index 00000000..e2d00fae --- /dev/null +++ b/json-render @@ -0,0 +1 @@ +Subproject commit e2d00faeaabe2871ca18a4594a9ec39a245f9b6c diff --git a/src/config.ts b/src/config.ts index ad67939b..34b2e32b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -50,7 +50,10 @@ export function envStr(name: string): string | undefined { export function envInt(...names: string[]): number | undefined { for (const name of names) { const val = process.env[name]; - if (val) return parseInt(val, 10); + if (val) { + const n = parseInt(val, 10); + if (!isNaN(n)) return n; + } } return undefined; } From 387c2a93c31dbe2526860f8950231d3b0a845808 Mon Sep 17 00:00:00 2001 From: Gillian Rode Date: Sat, 22 Aug 2026 09:37:53 -0700 Subject: [PATCH 05/19] fix: pass unknown paint types through marked instead of throwing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parsePaint threw on any paint type outside its known set, and the throw failed the entire get_figma_data request. Paint types absent from the REST spec reach real files (Figma code-component CUSTOM paints, observed 2026-08-22), so one such paint on one node made a whole file/subtree uncapturable. Unknown paint types now return { type, unknownPaint: true, raw } with the original paint preserved, log an error line, and leave the rest of the simplification untouched. Co-Authored-By: Claude Fable 5 (cherry picked from commit 5fdb96042624aa4d1a3f3337be06ed3737b2b66d) 🤖 Generated with BLOCKS! --- src/tests/unknown-paint.test.ts | 55 +++++++++++++++++++++++++++++++++ src/transformers/style.ts | 22 +++++++++++-- 2 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 src/tests/unknown-paint.test.ts diff --git a/src/tests/unknown-paint.test.ts b/src/tests/unknown-paint.test.ts new file mode 100644 index 00000000..0659248d --- /dev/null +++ b/src/tests/unknown-paint.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { parsePaint, buildSimplifiedStrokes } from "~/transformers/style.js"; +import type { Paint, Node as FigmaDocumentNode } from "@figma/rest-api-spec"; + +// Paint types outside the REST spec reach real files: Figma code-component +// CUSTOM paints (customEffectId + componentPropAssignments) were observed live +// on 2026-08-22. The spec's Paint union cannot express them, so the fixture +// casts through unknown exactly the way the API payload arrives at runtime. +const customPaint = { + type: "CUSTOM", + visible: true, + blendMode: "NORMAL", + customEffectId: "CodeComponentId:20e41e41-fixture", + componentPropAssignments: [{ defId: "1:2", value: "fixture" }], +} as unknown as Paint; + +const solidRed: Paint = { + type: "SOLID", + blendMode: "NORMAL", + color: { r: 1, g: 0, b: 0, a: 1 }, +}; + +describe("unknown paint types", () => { + it("degrades to a marked passthrough instead of throwing", () => { + const fill = parsePaint(customPaint); + expect(fill).toEqual({ type: "CUSTOM", unknownPaint: true, raw: customPaint }); + }); + + it("preserves the raw Figma fields for later consumers", () => { + const fill = parsePaint(customPaint) as { raw: Record }; + expect(fill.raw).toBe(customPaint); + expect(fill.raw.customEffectId).toBe("CodeComponentId:20e41e41-fixture"); + expect(fill.raw.componentPropAssignments).toEqual([{ defId: "1:2", value: "fixture" }]); + }); + + it("leaves known paints untouched", () => { + expect(parsePaint(solidRed)).toMatch(/^#ff0000$/i); + }); + + it("does not abort stroke parsing when one stroke paint is unknown", () => { + const node = { + id: "1:1", + name: "mixed-strokes", + type: "RECTANGLE", + strokes: [solidRed, customPaint], + strokeWeight: 2, + } as unknown as FigmaDocumentNode; + const strokes = buildSimplifiedStrokes(node); + expect(strokes.colors).toHaveLength(2); + // Reversed to CSS stacking order: the unknown top paint leads, marked. + expect(strokes.colors[0]).toEqual({ type: "CUSTOM", unknownPaint: true, raw: customPaint }); + expect(strokes.colors[1]).toMatch(/^#ff0000$/i); + expect(strokes.strokeWeight).toBe("2px"); + }); +}); diff --git a/src/transformers/style.ts b/src/transformers/style.ts index a58a1163..ab90a801 100644 --- a/src/transformers/style.ts +++ b/src/transformers/style.ts @@ -1,7 +1,7 @@ import type { Node as FigmaDocumentNode, Paint } from "@figma/rest-api-spec"; import { generateCSSShorthand, isVisible } from "~/utils/common.js"; -import { tagError } from "~/utils/error-meta.js"; import { hasValue, isStrokeWeights } from "~/utils/identity.js"; +import { Logger } from "~/utils/logger.js"; import { convertColor, formatRGBAColor } from "./style/color.js"; import { translateScaleMode, handleImageTransform, parsePatternPaint } from "./style/image.js"; @@ -21,10 +21,22 @@ import type { CSSRGBAColor, CSSHexColor } from "./style/color.js"; import type { SimplifiedPatternFill } from "./style/image.js"; import type { SimplifiedGradientFill } from "./style/gradient.js"; +/** + * A paint whose type this transformer does not recognize, passed through + * marked instead of dropped or thrown on. `raw` is the untouched Figma paint, + * so consumers that learn a new type later lose nothing in the meantime. + */ +export type SimplifiedUnknownFill = { + type: string; + unknownPaint: true; + raw: Paint; +}; + export type SimplifiedFill = | SimplifiedImageFill | SimplifiedGradientFill | SimplifiedPatternFill + | SimplifiedUnknownFill | CSSRGBAColor | CSSHexColor; @@ -148,6 +160,12 @@ export function parsePaint(raw: Paint, hasChildren: boolean = false): Simplified gradient: convertGradientToCss(raw), }; } else { - tagError(new Error(`Unknown paint type: ${raw.type}`), { category: "internal" }); + // Figma ships paint types faster than this transformer learns them (live + // example: code-component CUSTOM paints, which are absent from the REST + // spec). Throwing here failed an entire get_figma_data response over one + // paint on one node, so unknown types degrade instead: marked, with the + // raw paint preserved, and the rest of the simplification stays usable. + Logger.error(`Unknown paint type "${raw.type}" passed through unparsed.`); + return { type: raw.type, unknownPaint: true, raw }; } } From c0588be501888b0f81cb0bf25949ff8c74950ac6 Mon Sep 17 00:00:00 2001 From: Iams4kura <126048986+Iams4kura@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:38:54 +0800 Subject: [PATCH 06/19] fix: emit valid CSS for text shadows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit ad28cd4e004463d6b4771e4396efaee0355d4935) 🤖 Generated with BLOCKS! --- src/tests/effects.test.ts | 63 ++++++++++++++++++++++++++++++++++++- src/transformers/effects.ts | 22 ++++++++----- 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/src/tests/effects.test.ts b/src/tests/effects.test.ts index 6a397863..f713b5a0 100644 --- a/src/tests/effects.test.ts +++ b/src/tests/effects.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { buildSimplifiedEffects } from "~/transformers/effects.js"; -import type { Node as FigmaNode } from "@figma/rest-api-spec"; +import type { DropShadowEffect, InnerShadowEffect, Node as FigmaNode } from "@figma/rest-api-spec"; // Only the effects array is read; cast through unknown like the other walker tests. function nodeWithEffects(effects: unknown[]): FigmaNode { @@ -37,3 +37,64 @@ describe("buildSimplifiedEffects — blur", () => { expect(result.backdropFilter).toBeUndefined(); }); }); + +describe("buildSimplifiedEffects — shadows", () => { + const dropShadow: DropShadowEffect = { + type: "DROP_SHADOW", + showShadowBehindNode: false, + visible: true, + blendMode: "NORMAL", + color: { r: 0, g: 0, b: 0, a: 0.5 }, + offset: { x: 2, y: 3 }, + radius: 4, + }; + const innerShadow: InnerShadowEffect = { + ...dropShadow, + type: "INNER_SHADOW", + spread: 2, + }; + + it.each([undefined, 0, 5])("omits spread %s from CSS text-shadow", (spread) => { + const node = { + ...nodeWithEffects([{ ...dropShadow, spread }]), + type: "TEXT", + } as FigmaNode; + + expect(buildSimplifiedEffects(node)).toEqual({ + textShadow: "2px 3px 4px rgba(0, 0, 0, 0.5)", + }); + }); + + it("keeps visible text drop shadows without an unsupported inset entry", () => { + const node = { + ...nodeWithEffects([ + dropShadow, + innerShadow, + { ...dropShadow, visible: false }, + { ...dropShadow, offset: { x: -2, y: -3 }, radius: 0 }, + ]), + type: "TEXT", + } as FigmaNode; + + expect(buildSimplifiedEffects(node)).toEqual({ + textShadow: "2px 3px 4px rgba(0, 0, 0, 0.5), -2px -3px 0px rgba(0, 0, 0, 0.5)", + }); + }); + + it("omits unsupported text inner shadows without dropping blur effects", () => { + const node = { + ...nodeWithEffects([innerShadow, { type: "LAYER_BLUR", radius: 8, visible: true }]), + type: "TEXT", + } as FigmaNode; + + expect(buildSimplifiedEffects(node)).toEqual({ filter: "blur(4px)" }); + }); + + it("preserves spread and inset for non-text box shadows", () => { + expect( + buildSimplifiedEffects(nodeWithEffects([{ ...dropShadow, spread: 5 }, innerShadow])), + ).toEqual({ + boxShadow: "2px 3px 4px 5px rgba(0, 0, 0, 0.5), inset 2px 3px 4px 2px rgba(0, 0, 0, 0.5)", + }); + }); +}); diff --git a/src/transformers/effects.ts b/src/transformers/effects.ts index edc02554..5b87ecdf 100644 --- a/src/transformers/effects.ts +++ b/src/transformers/effects.ts @@ -18,17 +18,19 @@ export type SimplifiedEffects = { export function buildSimplifiedEffects(n: FigmaDocumentNode): SimplifiedEffects { if (!hasValue("effects", n)) return {}; const effects = n.effects.filter((e) => e.visible); + const isText = n.type === "TEXT"; - // Handle drop and inner shadows (both go into CSS box-shadow) + // CSS text-shadow supports neither spread nor inset; an unsupported entry + // would invalidate the entire shadow list, including valid drop shadows. const dropShadows = effects .filter((e): e is DropShadowEffect => e.type === "DROP_SHADOW") - .map(simplifyDropShadow); + .map((effect) => (isText ? simplifyTextShadow(effect) : simplifyDropShadow(effect))); const innerShadows = effects - .filter((e): e is InnerShadowEffect => e.type === "INNER_SHADOW") + .filter((e): e is InnerShadowEffect => !isText && e.type === "INNER_SHADOW") .map(simplifyInnerShadow); - const boxShadow = [...dropShadows, ...innerShadows].join(", "); + const shadow = [...dropShadows, ...innerShadows].join(", "); // Handle blur effects - separate by CSS property. A zero-radius blur is a // no-op, so drop it entirely rather than emit a dead `blur(0px)`. @@ -46,11 +48,11 @@ export function buildSimplifiedEffects(n: FigmaDocumentNode): SimplifiedEffects const result: SimplifiedEffects = {}; - if (boxShadow) { - if (n.type === "TEXT") { - result.textShadow = boxShadow; + if (shadow) { + if (isText) { + result.textShadow = shadow; } else { - result.boxShadow = boxShadow; + result.boxShadow = shadow; } } if (filterBlurValues) result.filter = filterBlurValues; @@ -59,6 +61,10 @@ export function buildSimplifiedEffects(n: FigmaDocumentNode): SimplifiedEffects return result; } +function simplifyTextShadow(effect: DropShadowEffect) { + return `${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${formatRGBAColor(effect.color)}`; +} + function simplifyDropShadow(effect: DropShadowEffect) { return `${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread ?? 0}px ${formatRGBAColor(effect.color)}`; } From 6a8d51780a00f8379a33032e0ceb02416b72fc46 Mon Sep 17 00:00:00 2001 From: Gillian Rode Date: Fri, 21 Aug 2026 20:25:05 -0700 Subject: [PATCH 07/19] fix: preserve node rotation, true size, ink bounds, and explicit line breaks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit db3081a8eaaf6342dae1cf08d372e9654b1675d7) 🤖 Generated with BLOCKS! --- src/services/figma.ts | 4 +- src/tests/rotation-transform.test.ts | 138 +++++++++++++++++++++++++++ src/transformers/layout.ts | 84 +++++++++++++++- src/transformers/layout/common.ts | 16 ++++ src/transformers/text.ts | 9 +- 5 files changed, 244 insertions(+), 7 deletions(-) create mode 100644 src/tests/rotation-transform.test.ts diff --git a/src/services/figma.ts b/src/services/figma.ts index d0f14e74..4a19fdd8 100644 --- a/src/services/figma.ts +++ b/src/services/figma.ts @@ -310,7 +310,7 @@ export class FigmaService { fileKey: string, depth?: number | null, ): Promise<{ data: GetFileResponse; rawSize: number }> { - const endpoint = `/files/${fileKey}${depth ? `?depth=${depth}` : ""}`; + const endpoint = `/files/${fileKey}?geometry=paths${depth ? `&depth=${depth}` : ""}`; Logger.log(`Retrieving raw Figma file: ${fileKey} (depth: ${depth ?? "default"})`); const result = await this.requestWithSize(endpoint); @@ -330,7 +330,7 @@ export class FigmaService { nodeId: string, depth?: number | null, ): Promise<{ data: GetFileNodesResponse; rawSize: number }> { - const endpoint = `/files/${fileKey}/nodes?ids=${nodeId}${depth ? `&depth=${depth}` : ""}`; + const endpoint = `/files/${fileKey}/nodes?ids=${nodeId}&geometry=paths${depth ? `&depth=${depth}` : ""}`; Logger.log( `Retrieving raw Figma node: ${nodeId} from ${fileKey} (depth: ${depth ?? "default"})`, ); diff --git a/src/tests/rotation-transform.test.ts b/src/tests/rotation-transform.test.ts new file mode 100644 index 00000000..cf0771ea --- /dev/null +++ b/src/tests/rotation-transform.test.ts @@ -0,0 +1,138 @@ +import { describe, test, expect } from "vitest"; +import { buildSimplifiedLayout } from "~/transformers/layout.js"; +import type { Node as FigmaDocumentNode } from "@figma/rest-api-spec"; + +// Values from a real production design (a marketing collage of tilted book +// covers), cross-checked against Figma plugin-API measurements of the same +// nodes. A 100x148.75 rectangle rotated -18.3° (Figma sign, CCW-positive) +// whose relativeTransform translation is (111.43, 40). +const CSS_PHI = (18.3 * Math.PI) / 180; // CSS clockwise angle for Figma -18.3 +const COS = Math.cos(CSS_PHI); +const SIN = Math.sin(CSS_PHI); + +function makeParent(overrides: Record = {}) { + return { + id: "1:1", + type: "FRAME", + clipsContent: false, + children: [], + absoluteBoundingBox: { x: 100, y: 200, width: 1440, height: 750 }, + relativeTransform: [ + [1, 0, 100], + [0, 1, 200], + ], + size: { x: 1440, y: 750 }, + ...overrides, + } as unknown as FigmaDocumentNode; +} + +function makeRotatedChild(overrides: Record = {}) { + return { + id: "1:2", + type: "RECTANGLE", + layoutSizingHorizontal: "FIXED", + layoutSizingVertical: "FIXED", + relativeTransform: [ + [COS, -SIN, 111.43], + [SIN, COS, 40], + ], + size: { x: 100, y: 148.75 }, + absoluteBoundingBox: { + x: 100 + 111.43 - 148.75 * SIN, + y: 200 + 40, + width: 100 * COS + 148.75 * SIN, + height: 100 * SIN + 148.75 * COS, + }, + ...overrides, + } as unknown as FigmaDocumentNode; +} + +describe("rotated-node transforms (geometry=paths)", () => { + test("rotated child emits rotation, true size, and pre-rotation top-left", () => { + const layout = buildSimplifiedLayout(makeRotatedChild(), makeParent()); + expect(layout.rotation).toBeCloseTo(-18.3, 1); + expect(layout.dimensions?.width).toBeCloseTo(100, 1); + expect(layout.dimensions?.height).toBeCloseTo(148.75, 1); + expect(layout.locationRelativeToParent?.x).toBeCloseTo(111.43, 1); + expect(layout.locationRelativeToParent?.y).toBeCloseTo(40, 1); + }); + + test("unrotated child under an unrotated parent is unchanged (no rotation field, AABB location)", () => { + const child = { + id: "1:3", + type: "RECTANGLE", + layoutSizingHorizontal: "FIXED", + layoutSizingVertical: "FIXED", + relativeTransform: [ + [1, 0, 1270.99], + [0, 1, 313], + ], + size: { x: 100, y: 150 }, + absoluteBoundingBox: { x: 100 + 1270.99, y: 200 + 313, width: 100, height: 150 }, + } as unknown as FigmaDocumentNode; + const layout = buildSimplifiedLayout(child, makeParent()); + expect(layout.rotation).toBeUndefined(); + expect(layout.locationRelativeToParent?.x).toBeCloseTo(1270.99, 1); + expect(layout.locationRelativeToParent?.y).toBeCloseTo(313, 1); + }); + + test("unrotated child of a ROTATED group still takes the transform path so nesting composes", () => { + const rotatedGroup = makeParent({ + type: "GROUP", + relativeTransform: [ + [COS, -SIN, 500], + [SIN, COS, 300], + ], + }); + const child = { + id: "1:4", + type: "RECTANGLE", + layoutSizingHorizontal: "FIXED", + layoutSizingVertical: "FIXED", + relativeTransform: [ + [1, 0, 30], + [0, 1, 10], + ], + size: { x: 64, y: 64 }, + absoluteBoundingBox: { x: 0, y: 0, width: 90, height: 90 }, + } as unknown as FigmaDocumentNode; + const layout = buildSimplifiedLayout(child, rotatedGroup); + // Local rotation ~0 → no rotation field, but location/size must come from + // the transform (the AABB delta would be in a different, mixed frame). + expect(layout.rotation).toBeUndefined(); + expect(layout.dimensions?.width).toBeCloseTo(64, 1); + expect(layout.locationRelativeToParent?.x).toBeCloseTo(30, 1); + expect(layout.locationRelativeToParent?.y).toBeCloseTo(10, 1); + }); + + test("vector-class node with ink bounds away from its layout box emits parent-relative renderBounds", () => { + const textPath = { + id: "1:5", + type: "TEXT_PATH", + layoutSizingHorizontal: "FIXED", + layoutSizingVertical: "FIXED", + relativeTransform: [ + [1, 0, -149], + [0, 1, 44], + ], + size: { x: 1481, y: 933 }, + absoluteBoundingBox: { x: 100 - 149, y: 200 + 44, width: 1481, height: 933 }, + absoluteRenderBounds: { x: 100, y: 200 + 300, width: 1380, height: 576 }, + } as unknown as FigmaDocumentNode; + const layout = buildSimplifiedLayout(textPath, makeParent()); + expect(layout.renderBounds).toEqual({ x: 0, y: 300, width: 1380, height: 576 }); + }); + + test("renderBounds is not emitted when ink matches the layout box", () => { + const vector = { + id: "1:6", + type: "VECTOR", + layoutSizingHorizontal: "FIXED", + layoutSizingVertical: "FIXED", + absoluteBoundingBox: { x: 150, y: 250, width: 40, height: 40 }, + absoluteRenderBounds: { x: 150.2, y: 250.2, width: 39.8, height: 39.8 }, + } as unknown as FigmaDocumentNode; + const layout = buildSimplifiedLayout(vector, makeParent()); + expect(layout.renderBounds).toBeUndefined(); + }); +}); diff --git a/src/transformers/layout.ts b/src/transformers/layout.ts index dae3d182..3fa18550 100644 --- a/src/transformers/layout.ts +++ b/src/transformers/layout.ts @@ -1,5 +1,5 @@ import { isInAutoLayoutFlow, isFrame, isLayout, isRectangle } from "~/utils/identity.js"; -import type { Node as FigmaDocumentNode, HasLayoutTrait } from "@figma/rest-api-spec"; +import type { Node as FigmaDocumentNode, HasLayoutTrait, Transform } from "@figma/rest-api-spec"; import { generateCSSShorthand, pixelRound } from "~/utils/common.js"; import { convertSelfAlign, @@ -178,5 +178,87 @@ function buildSimplifiedLayoutValues( } } + // When geometry=paths supplies true transforms, undo the axis-aligned + // flattening for rotated nodes: absoluteBoundingBox is the box AROUND a + // rotated node — inflated and corner-anchored — which mis-sizes and + // mis-places anything tilted (a 100x148.75 cover at -18.3° reads as an + // unrotated 141.6x172.6). Emit the unrotated size, the pre-rotation + // top-left (the relativeTransform translation, already parent-relative), + // and the angle itself. Children of rotated groups take this path even + // when unrotated locally, so nested transforms compose. + const ln = n as unknown as HasLayoutTrait; + const pln = parent as unknown as HasLayoutTrait | undefined; + if (ln.relativeTransform && ln.size) { + const rotation = matrixRotationDeg(ln.relativeTransform); + const parentRotation = pln?.relativeTransform ? matrixRotationDeg(pln.relativeTransform) : 0; + if ( + Math.abs(rotation) > ROTATION_EPSILON_DEG || + Math.abs(parentRotation) > ROTATION_EPSILON_DEG + ) { + if (Math.abs(rotation) > ROTATION_EPSILON_DEG) { + layoutValues.rotation = pixelRound(rotation); + } + layoutValues.dimensions = { + width: pixelRound(ln.size.x), + height: pixelRound(ln.size.y), + }; + layoutValues.locationRelativeToParent = { + x: pixelRound(ln.relativeTransform[0][2]), + y: pixelRound(ln.relativeTransform[1][2]), + }; + } + } + + // Vector-class nodes can render ink well inside their layout box — a + // text-on-path node's box says nothing about where the glyphs sit, so an + // exported asset placed at the box lands in the wrong place. Surface the + // ink bounds parent-relative when they differ materially from the box. + const rb = ( + n as { absoluteRenderBounds?: { x: number; y: number; width: number; height: number } | null } + ).absoluteRenderBounds; + if ( + rb && + ln.absoluteBoundingBox && + pln?.absoluteBoundingBox && + VECTOR_RENDER_BOUND_TYPES.has(n.type) + ) { + const bb = ln.absoluteBoundingBox; + const differs = + Math.abs(rb.x - bb.x) > 1 || + Math.abs(rb.y - bb.y) > 1 || + Math.abs(rb.width - bb.width) > 1 || + Math.abs(rb.height - bb.height) > 1; + if (differs) { + layoutValues.renderBounds = { + x: pixelRound(rb.x - pln.absoluteBoundingBox.x), + y: pixelRound(rb.y - pln.absoluteBoundingBox.y), + width: pixelRound(rb.width), + height: pixelRound(rb.height), + }; + } + } + return layoutValues; } + +// Below this, rounding noise in exported files produces spurious sub-pixel +// "rotations"; at or under it a node is treated as upright. +const ROTATION_EPSILON_DEG = 0.05; + +// Node types whose ink routinely diverges from their layout box. TEXT_PATH is +// compared as a string because @figma/rest-api-spec predates it. +const VECTOR_RENDER_BOUND_TYPES = new Set([ + "TEXT_PATH", + "VECTOR", + "BOOLEAN_OPERATION", + "STAR", + "LINE", + "POLYGON", +]); + +// Rotation angle encoded in a Figma transform, in degrees with Figma's sign +// convention (counter-clockwise positive). For a rotation by θ the matrix rows +// are [[cos θ, sin θ, tx], [-sin θ, cos θ, ty]]. +function matrixRotationDeg(t: Transform): number { + return (Math.atan2(t[0][1], t[0][0]) * 180) / Math.PI; +} diff --git a/src/transformers/layout/common.ts b/src/transformers/layout/common.ts index 703fdc5f..96f76542 100644 --- a/src/transformers/layout/common.ts +++ b/src/transformers/layout/common.ts @@ -50,6 +50,22 @@ export interface SimplifiedLayout { }; overflowScroll?: ("x" | "y")[]; position?: "absolute"; + // Present only when the node is rotated (or sits inside a rotated group, + // so nested transforms compose). Degrees, Figma sign convention: + // counter-clockwise positive — the CSS equivalent is + // `transform: rotate(-deg)` with `transform-origin: top left`. + // When the rotated path is taken, `dimensions` and + // `locationRelativeToParent` describe the UNROTATED box and its + // pre-rotation top-left in the parent's coordinate space, not the + // axis-aligned bounds (which are inflated and corner-anchored for any + // tilted node). Requires `relativeTransform`/`size` in the REST payload + // (`geometry=paths`). + rotation?: number; + // Ink bounds (absoluteRenderBounds) relative to the parent's bounding box, + // emitted for vector-class nodes whose rendered ink differs from their + // layout box (e.g. text-on-path, where the box says nothing about where + // the glyphs sit). Lets an exported derivative be placed exactly. + renderBounds?: { x: number; y: number; width: number; height: number }; } export function convertSizing( diff --git a/src/transformers/text.ts b/src/transformers/text.ts index 13f3e718..6cd3d917 100644 --- a/src/transformers/text.ts +++ b/src/transformers/text.ts @@ -310,8 +310,9 @@ export function buildFormattedText( } /** - * Split characters into lines at `\n` / `\u2029` (paragraph separator — the - * Figma API allows both). Each line carries its slice of the overrides + * Split characters into lines at `\n` / `\u2028` (line separator — what + * Shift+Return inserts) / `\u2029` (paragraph separator — the Figma API + * allows all three). Each line carries its slice of the overrides * array. The newline character itself is discarded along with its override. * * The returned line count matches what Figma's `lineTypes` / @@ -326,7 +327,7 @@ function splitLines( let lineStart = 0; for (let i = 0; i <= codePoints.length; i++) { const ch = i < codePoints.length ? codePoints[i] : null; - if (ch === "\n" || ch === "\u2029" || ch === null) { + if (ch === "\n" || ch === "\u2028" || ch === "\u2029" || ch === null) { lines.push({ codePoints: codePoints.slice(lineStart, i), overrides: overrides.slice(lineStart, i), @@ -735,7 +736,7 @@ function classifyRun( const MARKDOWN_ESCAPE_CHARS = /[\\*_~[\](){}]/g; function escapeMarkdown(text: string): string { - return text.replace(MARKDOWN_ESCAPE_CHARS, "\\$&").replace(/[\n\u2029]/g, "\\n"); + return text.replace(MARKDOWN_ESCAPE_CHARS, "\\$&").replace(/[\n\u2028\u2029]/g, "\\n"); } /** From 01577ca0128005778d7852be0d3877f3a4b2cda0 Mon Sep 17 00:00:00 2001 From: Graham Lipsman Date: Tue, 23 Jun 2026 22:59:23 -0700 Subject: [PATCH 08/19] test: add characterization tests for FigmaService request/error path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 11df79aa39a1f368c514c785e1ca2ad35cad3e50) 🤖 Generated with BLOCKS! --- src/tests/figma-service.test.ts | 232 ++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 src/tests/figma-service.test.ts diff --git a/src/tests/figma-service.test.ts b/src/tests/figma-service.test.ts new file mode 100644 index 00000000..d208e3ba --- /dev/null +++ b/src/tests/figma-service.test.ts @@ -0,0 +1,232 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { FigmaService } from "~/services/figma.js"; + +/** + * Characterization tests for FigmaService's request/error path. These pin the + * CURRENT behavior of endpoint construction, auth-header selection, and the + * HTTP-status-to-message translation in `requestWithSize`. They mock the global + * `fetch` (not `fetchJSON`) so the real fetch-json + error-meta flow runs + * end-to-end — that's the layer that tags `http_status`, which FigmaService + * branches on. Modeled on `http-header-auth.test.ts`. + * + * Error-message assertions deliberately match stable substrings, not full + * strings: `src/services/errors/*` is designed to be reworded without a release. + */ + +const figmaFileResponse = { + name: "Test File", + lastModified: "2026-01-01T00:00:00Z", + thumbnailUrl: "", + version: "1", + document: { id: "0:0", name: "Document", type: "DOCUMENT", children: [] }, + components: {}, + componentSets: {}, + schemaVersion: 0, + styles: {}, +}; + +describe("FigmaService request/error path", () => { + let fetchMock: ReturnType; + + /** Configure the stubbed fetch to answer api.figma.com with a given response. */ + function stubFigmaResponse(makeResponse: () => Response) { + const realFetch = globalThis.fetch; + fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).startsWith("https://api.figma.com")) { + return makeResponse(); + } + return realFetch(input, init); + }); + vi.stubGlobal("fetch", fetchMock); + } + + function firstRequestUrl(): string { + return String(fetchMock.mock.calls[0][0]); + } + + function firstRequestHeaders(): Record { + const init = fetchMock.mock.calls[0][1] as RequestInit & { headers?: Record }; + return init.headers ?? {}; + } + + /** Await a promise expecting it to reject, and return the thrown Error. */ + async function captureError(promise: Promise): Promise { + try { + await promise; + } catch (e) { + return e as Error; + } + throw new Error("expected promise to reject, but it resolved"); + } + + beforeEach(() => { + stubFigmaResponse(() => Response.json(figmaFileResponse)); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + describe("endpoint construction", () => { + it("builds the nodes endpoint for getRawNode", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + await service.getRawNode("ABC", "1:2"); + + expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2"); + }); + + it("appends depth to the nodes endpoint when provided", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + await service.getRawNode("ABC", "1:2", 3); + + expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2&depth=3"); + }); + + it("builds the file endpoint for getRawFile", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + await service.getRawFile("ABC"); + + expect(firstRequestUrl()).toMatch(/\/files\/ABC$/); + }); + + it("appends depth to the file endpoint when provided", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + await service.getRawFile("ABC", 2); + + expect(firstRequestUrl()).toContain("/files/ABC?depth=2"); + }); + }); + + describe("auth headers", () => { + it("sends X-Figma-Token when using a personal access token", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + await service.getRawFile("ABC"); + + expect(firstRequestHeaders()).toMatchObject({ "X-Figma-Token": "test-key" }); + }); + + it("sends Authorization Bearer when using OAuth", async () => { + const service = new FigmaService({ + figmaApiKey: "", + figmaOAuthToken: "tok", + useOAuth: true, + }); + + await service.getRawFile("ABC"); + + expect(firstRequestHeaders()).toMatchObject({ Authorization: "Bearer tok" }); + }); + }); + + describe("happy path return shape", () => { + it("returns parsed data alongside a positive rawSize", async () => { + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + const { data, rawSize } = await service.getRawFile("ABC"); + + expect(data).toMatchObject({ name: "Test File" }); + expect(rawSize).toBeGreaterThan(0); + }); + }); + + describe("error translation", () => { + it("translates 429 into the rate-limit guidance message", async () => { + stubFigmaResponse( + () => new Response("rate limited body", { status: 429, statusText: "Too Many Requests" }), + ); + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + const error = await captureError(service.getRawNode("ABC", "1:2")); + + expect(error.message).toContain("Figma API rate limit hit (429)."); + expect(error.message).toContain("https://developers.figma.com/docs/rest-api/rate-limits/"); + expect(error.cause).toBeDefined(); + }); + + it("translates 403 into the forbidden guidance message", async () => { + stubFigmaResponse( + () => new Response("forbidden body", { status: 403, statusText: "Forbidden" }), + ); + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + const error = await captureError(service.getRawNode("ABC", "1:2")); + + expect(error.message).toContain( + "https://www.framelink.ai/docs/troubleshooting#cannot-access-file", + ); + expect(error.message).toContain("returned 403 Forbidden"); + expect(error.message).toContain("forbidden body"); + expect(error.cause).toBeDefined(); + }); + + it("translates other failures into the generic endpoint message", async () => { + stubFigmaResponse( + () => + new Response("server error body", { status: 500, statusText: "Internal Server Error" }), + ); + const service = new FigmaService({ + figmaApiKey: "test-key", + figmaOAuthToken: "", + useOAuth: false, + }); + + const error = await captureError(service.getRawNode("ABC", "1:2")); + + expect(error.message).toContain("Failed to make request to Figma API endpoint"); + expect(error.message).toContain("/files/ABC/nodes?ids=1:2"); + expect(error.cause).toBeDefined(); + }); + }); + + describe("missing-auth guard", () => { + it("rejects without making a request when no credentials are configured", async () => { + const service = new FigmaService({ + figmaApiKey: "", + figmaOAuthToken: "", + useOAuth: false, + }); + + const error = await captureError(service.getRawFile("ABC")); + + expect(error.message).toContain("authentication is required"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + }); +}); From ccbb628ea022349e97eac034f35b8482be5ff3f2 Mon Sep 17 00:00:00 2001 From: Graham Lipsman Date: Tue, 23 Jun 2026 23:02:33 -0700 Subject: [PATCH 09/19] feat: support fetching multiple nodes in get_figma_data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 78e6168b0c5074ce7fc70f7052e6addc332d1129) 🤖 Generated with BLOCKS! --- src/extractors/design-extractor.ts | 35 +++++++--- src/mcp/tools/get-figma-data-tool.ts | 6 +- src/tests/multi-node.test.ts | 95 ++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 13 deletions(-) create mode 100644 src/tests/multi-node.test.ts diff --git a/src/extractors/design-extractor.ts b/src/extractors/design-extractor.ts index d590ef88..c3316c08 100644 --- a/src/extractors/design-extractor.ts +++ b/src/extractors/design-extractor.ts @@ -63,12 +63,32 @@ function parseAPIResponse(data: GetFileResponse | GetFileNodesResponse) { let nodesToParse: Array; if ("nodes" in data) { - // GetFileNodesResponse - const [nodeId, nodeData] = Object.entries(data.nodes)[0]; - if (nodeData === null) { + // GetFileNodesResponse — may contain multiple requested nodes when the + // caller passed comma-separated ids. Aggregate every node the API returned; + // a null entry is a node the API couldn't resolve (deleted/inaccessible/ + // wrong file) and is skipped. Only error if NONE resolved — that's the + // "not found" case the single-node path used to handle. + const documents: FigmaDocumentNode[] = []; + const missingNodeIds: string[] = []; + for (const [nodeId, nodeData] of Object.entries(data.nodes)) { + if (nodeData === null) { + missingNodeIds.push(nodeId); + continue; + } + Object.assign(aggregatedComponents, nodeData.components); + Object.assign(aggregatedComponentSets, nodeData.componentSets); + if (nodeData.styles) { + Object.assign(extraStyles, nodeData.styles); + } + documents.push(nodeData.document); + } + + if (documents.length === 0) { + const requested = Object.keys(data.nodes); + const idList = (requested.length ? requested : ["(none returned)"]).join(", "); tagError( new Error( - `Node ${nodeId} was not found in the Figma file. Likely causes: ` + + `No requested nodes were found in the Figma file (${idList}). Likely causes: ` + `(1) The source URL was a /proto/, /figjam/, /slides/, /board/, or /deck/ link — ` + `only /design/ and /file/ URLs are supported by the Figma REST API. ` + `(2) The node is inside a Figma branch — branches have their own fileKey ` + @@ -80,12 +100,7 @@ function parseAPIResponse(data: GetFileResponse | GetFileNodesResponse) { ); } - Object.assign(aggregatedComponents, nodeData.components); - Object.assign(aggregatedComponentSets, nodeData.componentSets); - if (nodeData.styles) { - Object.assign(extraStyles, nodeData.styles); - } - nodesToParse = [nodeData.document]; + nodesToParse = documents; } else { // GetFileResponse Object.assign(aggregatedComponents, data.components); diff --git a/src/mcp/tools/get-figma-data-tool.ts b/src/mcp/tools/get-figma-data-tool.ts index 0580d1d0..a42a7bae 100644 --- a/src/mcp/tools/get-figma-data-tool.ts +++ b/src/mcp/tools/get-figma-data-tool.ts @@ -15,12 +15,12 @@ const parameters = { nodeId: z .string() .regex( - /^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*$/, - "Node ID must be like '1234:5678' or 'I5666:180910;1:10515;1:10336'", + /^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*(?:,I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*)*$/, + "Node ID must be like '1234:5678', a semicolon-joined instance path, or a comma-separated list of these", ) .optional() .describe( - "The ID of the node to fetch, often found as URL parameter node-id=, always use if provided. Use format '1234:5678' for a standard node, or 'I5666:180910;1:10515;1:10336' for a deeply nested instance node (the semicolon-joined path represents the instance override chain — it's still a single node ID, not multiple nodes).", + "The ID(s) of the node(s) to fetch, often found as the URL parameter node-id=; always use if provided. Use '1234:5678' for a standard node. A semicolon-joined value like 'I5666:180910;1:10515;1:10336' is a SINGLE deeply-nested instance node (the override chain), not multiple nodes. To fetch MULTIPLE top-level nodes in one call, comma-separate their ids, e.g. '1:2,3:4'.", ), depth: z .number() diff --git a/src/tests/multi-node.test.ts b/src/tests/multi-node.test.ts new file mode 100644 index 00000000..eb49bd2e --- /dev/null +++ b/src/tests/multi-node.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { simplifyRawFigmaObject } from "~/extractors/design-extractor.js"; +import { allExtractors } from "~/extractors/built-in.js"; +import { getFigmaDataTool } from "~/mcp/tools/get-figma-data-tool.js"; +import { getErrorMeta } from "~/utils/error-meta.js"; +import type { GetFileNodesResponse, Node as FigmaNode } from "@figma/rest-api-spec"; + +// Same casting strategy as tree-walker.test.ts: the walker only reads a small +// subset of the deeply-discriminated Figma node union, so build fixtures loosely +// and cast through unknown. +function makeNode(overrides: Record): FigmaNode { + return { visible: true, ...overrides } as unknown as FigmaNode; +} + +// A GetFileNodesResponse entry wraps each requested node's document plus its +// associated components/styles. A null entry means the API couldn't resolve it. +function makeNodesResponse( + nodes: Record, +): GetFileNodesResponse { + const wrapped: Record = {}; + for (const [id, value] of Object.entries(nodes)) { + wrapped[id] = + value === null + ? null + : { document: value.document, components: {}, componentSets: {}, styles: {} }; + } + return { name: "Test File", nodes: wrapped } as unknown as GetFileNodesResponse; +} + +describe("multi-node GetFileNodesResponse handling", () => { + it("aggregates every returned node into the top-level nodes array", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, + "3:4": { document: makeNode({ id: "3:4", name: "Frame B", type: "FRAME" }) }, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + expect(result.nodes).toHaveLength(2); + expect(result.nodes.map((n) => n.name)).toEqual(["Frame A", "Frame B"]); + expect(result.nodes.map((n) => n.id)).toEqual(["1:2", "3:4"]); + }); + + it("skips null entries and resolves with just the found nodes", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, + "9:9": null, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + expect(result.nodes).toHaveLength(1); + expect(result.nodes[0].name).toBe("Frame A"); + }); + + it("rejects with a not_found error when every requested node is null", async () => { + const response = makeNodesResponse({ "1:2": null, "3:4": null }); + + await expect(simplifyRawFigmaObject(response, allExtractors)).rejects.toMatchObject({ + message: expect.stringContaining("No requested nodes were found"), + }); + + const error = await simplifyRawFigmaObject(response, allExtractors).catch((e) => e); + expect(getErrorMeta(error).category).toBe("not_found"); + }); + + it("rejects with not_found (not a TypeError) on an empty nodes object", async () => { + const response = makeNodesResponse({}); + + const error = await simplifyRawFigmaObject(response, allExtractors).catch((e) => e); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(TypeError); + expect(getErrorMeta(error).category).toBe("not_found"); + expect((error as Error).message).toContain("No requested nodes were found"); + }); +}); + +describe("get_figma_data nodeId schema", () => { + it("accepts a comma-separated list of node ids", () => { + const result = getFigmaDataTool.parametersSchema.safeParse({ + fileKey: "abc", + nodeId: "1:2,3:4", + }); + expect(result.success).toBe(true); + }); + + it("rejects a malformed node id", () => { + const result = getFigmaDataTool.parametersSchema.safeParse({ + fileKey: "abc", + nodeId: "not a node id", + }); + expect(result.success).toBe(false); + }); +}); From ecdc40f88c7fee873304d3d0c846aad02f163d6a Mon Sep 17 00:00:00 2001 From: Graham Lipsman Date: Wed, 24 Jun 2026 09:28:10 -0700 Subject: [PATCH 10/19] fix: prevent partial-miss crash and tidy multi-node parse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Normalize both API response shapes into a common slice list so parseAPIResponse aggregates roots/components/styles declaratively, and make the metrics pass (countNamedStyles, detectVariables) skip null node entries so a partial miss (some ids resolve, some don't) no longer crashes with a TypeError after simplify. Also surface skipped ids via Logger, tighten the nodeId regex grammar, and add cross-node dedup + partial-miss regression tests. (cherry picked from commit d96cfb952b47bc722e90fc1fd761d5974c12ceb4) 🤖 Generated with BLOCKS! --- src/extractors/design-extractor.ts | 179 ++++++++++++++++--------- src/mcp/tools/get-figma-data-tool.ts | 9 +- src/services/get-figma-data-metrics.ts | 9 +- src/tests/multi-node.test.ts | 110 ++++++++++++++- 4 files changed, 236 insertions(+), 71 deletions(-) diff --git a/src/extractors/design-extractor.ts b/src/extractors/design-extractor.ts index c3316c08..24ca5bbf 100644 --- a/src/extractors/design-extractor.ts +++ b/src/extractors/design-extractor.ts @@ -8,6 +8,7 @@ import type { } from "@figma/rest-api-spec"; import { simplifyComponents, simplifyComponentSets } from "~/transformers/component.js"; import { tagError } from "~/utils/error-meta.js"; +import { Logger } from "~/utils/logger.js"; import type { ExtractorFn, TraversalOptions, SimplifiedDesign } from "./types.js"; import { extractFromDesign } from "./node-walker.js"; import { finalizeDesign } from "./finalize.js"; @@ -21,10 +22,21 @@ export async function simplifyRawFigmaObject( options: TraversalOptions = {}, ): Promise { // Extract components, componentSets, and raw nodes from API response - const { metadata, rawNodes, components, componentSets, extraStyles } = + const { name, rawNodes, components, componentSets, extraStyles, missingNodeIds } = parseAPIResponse(apiResponse); - // Process nodes using the flexible extractor system + // Partial miss: some requested ids didn't resolve but others did. We proceed + // with what we have (see parseAPIResponse) and surface the gap here rather than + // failing the whole call — the caller asked for several roots and most came back. + if (missingNodeIds.length > 0) { + Logger.log( + `Skipped ${missingNodeIds.length} unresolved node id(s): ${missingNodeIds.join(", ")}`, + ); + } + + // Process nodes using the flexible extractor system. The walk shares one + // globalVars + traversalState across every root, so style/element dedup spans + // all requested nodes — a value used once in either root is still seen twice. const { nodes: extractedNodes, globalVars: walkedGlobalVars, @@ -41,7 +53,7 @@ export async function simplifyRawFigmaObject( ); return { - ...metadata, + name, nodes, components: simplifyComponents(components, traversalState.componentPropertyDefinitions), componentSets: simplifyComponentSets( @@ -54,72 +66,111 @@ export async function simplifyRawFigmaObject( } /** - * Parse the raw Figma API response to extract metadata, nodes, and components. + * One requested-or-whole-file unit of raw design data: a set of root nodes plus + * the component/style dictionaries that came alongside them. Both API response + * shapes normalize to a list of these, so the rest of parsing is shape-agnostic. */ -function parseAPIResponse(data: GetFileResponse | GetFileNodesResponse) { - const aggregatedComponents: Record = {}; - const aggregatedComponentSets: Record = {}; - let extraStyles: Record = {}; - let nodesToParse: Array; - - if ("nodes" in data) { - // GetFileNodesResponse — may contain multiple requested nodes when the - // caller passed comma-separated ids. Aggregate every node the API returned; - // a null entry is a node the API couldn't resolve (deleted/inaccessible/ - // wrong file) and is skipped. Only error if NONE resolved — that's the - // "not found" case the single-node path used to handle. - const documents: FigmaDocumentNode[] = []; - const missingNodeIds: string[] = []; - for (const [nodeId, nodeData] of Object.entries(data.nodes)) { - if (nodeData === null) { - missingNodeIds.push(nodeId); - continue; - } - Object.assign(aggregatedComponents, nodeData.components); - Object.assign(aggregatedComponentSets, nodeData.componentSets); - if (nodeData.styles) { - Object.assign(extraStyles, nodeData.styles); - } - documents.push(nodeData.document); - } +type RawSlice = { + roots: FigmaDocumentNode[]; + components?: Record; + componentSets?: Record; + styles?: Record; +}; - if (documents.length === 0) { - const requested = Object.keys(data.nodes); - const idList = (requested.length ? requested : ["(none returned)"]).join(", "); - tagError( - new Error( - `No requested nodes were found in the Figma file (${idList}). Likely causes: ` + - `(1) The source URL was a /proto/, /figjam/, /slides/, /board/, or /deck/ link — ` + - `only /design/ and /file/ URLs are supported by the Figma REST API. ` + - `(2) The node is inside a Figma branch — branches have their own fileKey ` + - `(the value after /branch/ in the URL), use that instead of the parent file's key. ` + - `(3) The link is stale or the node was deleted. ` + - `Ask the user for a fresh /design/ URL pointing to the specific frame.`, - ), - { category: "not_found" }, - ); - } +type ParsedAPIResponse = { + name: string; + rawNodes: FigmaDocumentNode[]; + components: Record; + componentSets: Record; + extraStyles: Record; + /** Requested node ids the API returned as null (deleted/inaccessible/wrong file). */ + missingNodeIds: string[]; +}; - nodesToParse = documents; - } else { - // GetFileResponse - Object.assign(aggregatedComponents, data.components); - Object.assign(aggregatedComponentSets, data.componentSets); - if (data.styles) { - extraStyles = data.styles; - } - nodesToParse = data.document.children; - } +/** Shallow-merge a list of dictionaries; `undefined` sources are skipped. */ +function mergeRecords(records: Array | undefined>): Record { + return Object.assign({}, ...records); +} - const { name } = data; +/** + * Parse the raw Figma API response into a flat, shape-agnostic bag of roots and + * their associated dictionaries. The two API shapes differ only in how they + * package roots; normalizing them up front (see normalizeResponse) lets the + * aggregation below treat the full-file fetch and a multi-node fetch identically. + */ +function parseAPIResponse(data: GetFileResponse | GetFileNodesResponse): ParsedAPIResponse { + const { slices, missingNodeIds } = normalizeResponse(data); return { - metadata: { - name, - }, - rawNodes: nodesToParse, - extraStyles, - components: aggregatedComponents, - componentSets: aggregatedComponentSets, + name: data.name, + rawNodes: slices.flatMap((slice) => slice.roots), + components: mergeRecords(slices.map((slice) => slice.components)), + componentSets: mergeRecords(slices.map((slice) => slice.componentSets)), + extraStyles: mergeRecords(slices.map((slice) => slice.styles)), + missingNodeIds, }; } + +/** + * Collapse either API response shape into a list of {@link RawSlice}s. The only + * branch the rest of the pipeline can't avoid lives here: + * - GetFileResponse: one slice whose roots are the document's children. + * - GetFileNodesResponse: one slice per resolved node (the caller may have + * passed comma-separated ids). A null entry is a node the API couldn't + * resolve and is recorded in missingNodeIds, not turned into a slice. Only + * when NOTHING resolves do we raise the "not found" error — the case the + * single-node path used to handle, and the one that previously crashed with a + * raw TypeError on an empty `nodes` object. + */ +function normalizeResponse(data: GetFileResponse | GetFileNodesResponse): { + slices: RawSlice[]; + missingNodeIds: string[]; +} { + if ("document" in data) { + return { + slices: [ + { + roots: data.document.children, + components: data.components, + componentSets: data.componentSets, + styles: data.styles, + }, + ], + missingNodeIds: [], + }; + } + + const entries = Object.entries(data.nodes); + const missingNodeIds = entries.flatMap(([id, node]) => (node === null ? [id] : [])); + const slices: RawSlice[] = entries.flatMap(([, node]) => + node === null + ? [] + : [ + { + roots: [node.document], + components: node.components, + componentSets: node.componentSets, + styles: node.styles, + }, + ], + ); + + if (slices.length === 0) { + const requested = entries.map(([id]) => id); + const idList = (requested.length ? requested : ["(none returned)"]).join(", "); + tagError( + new Error( + `No requested nodes were found in the Figma file (${idList}). Likely causes: ` + + `(1) The source URL was a /proto/, /figjam/, /slides/, /board/, or /deck/ link — ` + + `only /design/ and /file/ URLs are supported by the Figma REST API. ` + + `(2) The node is inside a Figma branch — branches have their own fileKey ` + + `(the value after /branch/ in the URL), use that instead of the parent file's key. ` + + `(3) The link is stale or the node was deleted. ` + + `Ask the user for a fresh /design/ URL pointing to the specific frame.`, + ), + { category: "not_found" }, + ); + } + + return { slices, missingNodeIds }; +} diff --git a/src/mcp/tools/get-figma-data-tool.ts b/src/mcp/tools/get-figma-data-tool.ts index a42a7bae..7e6abf1f 100644 --- a/src/mcp/tools/get-figma-data-tool.ts +++ b/src/mcp/tools/get-figma-data-tool.ts @@ -5,6 +5,13 @@ import { sendProgress, startProgressHeartbeat, type ToolExtra } from "~/mcp/prog import { getFigmaData as runGetFigmaData } from "~/services/get-figma-data.js"; import type { OutputFormat } from "~/utils/serialize.js"; +// One Figma node id: the API colon form "1234:5678", the URL dash form +// "1234-5678", or a semicolon-joined instance-override path +// "I5666:180910;1:10515;1:10336" (still a SINGLE node). Built from a single-id +// sub-pattern so the comma-separated list grammar below stays readable. +const SINGLE_NODE_ID = String.raw`I?\d+(?::|-)\d+(?:;\d+(?::|-)\d+)*`; +const NODE_ID_LIST = new RegExp(String.raw`^${SINGLE_NODE_ID}(?:,${SINGLE_NODE_ID})*$`); + const parameters = { fileKey: z .string() @@ -15,7 +22,7 @@ const parameters = { nodeId: z .string() .regex( - /^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*(?:,I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*)*$/, + NODE_ID_LIST, "Node ID must be like '1234:5678', a semicolon-joined instance path, or a comma-separated list of these", ) .optional() diff --git a/src/services/get-figma-data-metrics.ts b/src/services/get-figma-data-metrics.ts index 2295fc90..ca4441bb 100644 --- a/src/services/get-figma-data-metrics.ts +++ b/src/services/get-figma-data-metrics.ts @@ -156,6 +156,9 @@ export function countNamedStyles(raw: GetFileResponse | GetFileNodesResponse): n } const seen = new Set(); for (const entry of Object.values(raw.nodes)) { + // A null entry is a requested node the API couldn't resolve (partial miss); + // it carries no styles. parseAPIResponse skips these, so metrics must too. + if (entry === null) continue; for (const id of Object.keys(entry.styles ?? {})) seen.add(id); } return seen.size; @@ -169,8 +172,12 @@ export function countNamedStyles(raw: GetFileResponse | GetFileNodesResponse): n * presence signal. Walking inline Paint/effect structs would be redundant. */ export function detectVariables(raw: GetFileResponse | GetFileNodesResponse): boolean { + // Null entries are requested nodes the API couldn't resolve (partial miss); + // skip them rather than dereferencing .document on null. const roots: Node[] = - "document" in raw ? [raw.document] : Object.values(raw.nodes).map((entry) => entry.document); + "document" in raw + ? [raw.document] + : Object.values(raw.nodes).flatMap((entry) => (entry === null ? [] : [entry.document])); const visit = (node: Node): boolean => { if ( diff --git a/src/tests/multi-node.test.ts b/src/tests/multi-node.test.ts index eb49bd2e..0ff51103 100644 --- a/src/tests/multi-node.test.ts +++ b/src/tests/multi-node.test.ts @@ -2,8 +2,9 @@ import { describe, expect, it } from "vitest"; import { simplifyRawFigmaObject } from "~/extractors/design-extractor.js"; import { allExtractors } from "~/extractors/built-in.js"; import { getFigmaDataTool } from "~/mcp/tools/get-figma-data-tool.js"; +import { countNamedStyles, detectVariables } from "~/services/get-figma-data-metrics.js"; import { getErrorMeta } from "~/utils/error-meta.js"; -import type { GetFileNodesResponse, Node as FigmaNode } from "@figma/rest-api-spec"; +import type { GetFileNodesResponse, Node as FigmaNode, Style } from "@figma/rest-api-spec"; // Same casting strategy as tree-walker.test.ts: the walker only reads a small // subset of the deeply-discriminated Figma node union, so build fixtures loosely @@ -12,21 +13,28 @@ function makeNode(overrides: Record): FigmaNode { return { visible: true, ...overrides } as unknown as FigmaNode; } +type NodeEntry = { document: FigmaNode; styles?: Record } | null; + // A GetFileNodesResponse entry wraps each requested node's document plus its // associated components/styles. A null entry means the API couldn't resolve it. -function makeNodesResponse( - nodes: Record, -): GetFileNodesResponse { +function makeNodesResponse(nodes: Record): GetFileNodesResponse { const wrapped: Record = {}; for (const [id, value] of Object.entries(nodes)) { wrapped[id] = value === null ? null - : { document: value.document, components: {}, componentSets: {}, styles: {} }; + : { + document: value.document, + components: {}, + componentSets: {}, + styles: value.styles ?? {}, + }; } return { name: "Test File", nodes: wrapped } as unknown as GetFileNodesResponse; } +const RED_FILL = [{ type: "SOLID", color: { r: 1, g: 0, b: 0, a: 1 }, visible: true }]; + describe("multi-node GetFileNodesResponse handling", () => { it("aggregates every returned node into the top-level nodes array", async () => { const response = makeNodesResponse({ @@ -76,6 +84,98 @@ describe("multi-node GetFileNodesResponse handling", () => { }); }); +// The whole point of fetching multiple roots in one call is that the clever +// passes (style hoisting, element templating) still see the combined forest. +// These assert dedup spans node boundaries, not just within a single root. +describe("cross-node deduplication", () => { + it("hoists a style shared across two separate top-level nodes", async () => { + // Distinct node types so their bodies differ — this isolates STYLE dedup from + // ELEMENT dedup (identical bodies would template away the `fills` field). + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME", fills: RED_FILL }) }, + "3:4": { + document: makeNode({ id: "3:4", name: "Box B", type: "RECTANGLE", fills: RED_FILL }), + }, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + // Same fill in either root → same content-addressed ref → counted twice → + // kept hoisted (not inlined). Both nodes point at the one shared entry. + const fillsA = result.nodes[0].fills; + const fillsB = result.nodes[1].fills; + expect(typeof fillsA).toBe("string"); + expect(fillsA).toBe(fillsB); + expect(result.globalVars.styles[fillsA as string]).toBeDefined(); + + const fillEntries = Object.keys(result.globalVars.styles).filter((k) => k.startsWith("fill")); + expect(fillEntries).toHaveLength(1); + }); + + it("inlines a style used by only one node, even when other nodes are present", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME", fills: RED_FILL }) }, + "3:4": { document: makeNode({ id: "3:4", name: "Frame B", type: "FRAME" }) }, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + // Single use across the whole forest → inlined back onto the node, nothing + // left hoisted. + expect(Array.isArray(result.nodes[0].fills)).toBe(true); + expect(Object.keys(result.globalVars.styles)).toHaveLength(0); + }); + + it("templates structurally identical subtrees that live under different roots", async () => { + const child = () => makeNode({ id: "c", name: "Box", type: "RECTANGLE", fills: RED_FILL }); + const response = makeNodesResponse({ + "1:2": { + document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME", children: [child()] }), + }, + "3:4": { + document: makeNode({ id: "3:4", name: "Frame B", type: "FRAME", children: [child()] }), + }, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + // The identical rectangle appears once under each root → one shared element + // template, each occurrence reduced to a `template` ref. + expect(Object.keys(result.elements)).toHaveLength(1); + const [templateId] = Object.keys(result.elements); + expect(result.nodes[0].children![0].template).toBe(templateId); + expect(result.nodes[1].children![0].template).toBe(templateId); + }); +}); + +// Regression: a partial miss (some ids resolve, some are null) used to crash the +// metrics pass — which runs on the raw response after simplify — because it +// dereferenced every node entry as non-null. +describe("metrics tolerate null node entries (partial miss)", () => { + const response = makeNodesResponse({ + "1:2": { + document: makeNode({ + id: "1:2", + name: "Frame A", + type: "FRAME", + boundVariables: { fills: [{ type: "VARIABLE_ALIAS", id: "VariableID:1:1" }] }, + }), + styles: { "S:1": { name: "Brand/Primary" } as Style }, + }, + "9:9": null, + }); + + it("countNamedStyles ignores the null entry", () => { + expect(() => countNamedStyles(response)).not.toThrow(); + expect(countNamedStyles(response)).toBe(1); + }); + + it("detectVariables ignores the null entry", () => { + expect(() => detectVariables(response)).not.toThrow(); + expect(detectVariables(response)).toBe(true); + }); +}); + describe("get_figma_data nodeId schema", () => { it("accepts a comma-separated list of node ids", () => { const result = getFigmaDataTool.parametersSchema.safeParse({ From 7daaf88f6c3bdbfe48b9956dafeddddef85fc82c Mon Sep 17 00:00:00 2001 From: Graham Lipsman Date: Wed, 24 Jun 2026 10:08:46 -0700 Subject: [PATCH 11/19] feat: surface unresolved node ids to the caller on a partial miss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A multi-node fetch where some ids resolve and others don't previously only logged the gap server-side, so the LLM could act on an incomplete design as if it were complete. Carry missingNodeIds onto SimplifiedDesign (present only when non-empty, so the common case costs no tokens) and render a MISSING_NODES line in the tree format; YAML/JSON pick it up via metadata. (cherry picked from commit 5637d60d3d49d5154e1e891b528b51cdec7a0407) 🤖 Generated with BLOCKS! --- src/extractors/design-extractor.ts | 7 +++-- src/extractors/types.ts | 7 +++++ src/tests/multi-node.test.ts | 44 +++++++++++++++++++++++++++++- src/utils/serialize-tree.ts | 7 +++++ 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/extractors/design-extractor.ts b/src/extractors/design-extractor.ts index 24ca5bbf..d26725d0 100644 --- a/src/extractors/design-extractor.ts +++ b/src/extractors/design-extractor.ts @@ -26,8 +26,9 @@ export async function simplifyRawFigmaObject( parseAPIResponse(apiResponse); // Partial miss: some requested ids didn't resolve but others did. We proceed - // with what we have (see parseAPIResponse) and surface the gap here rather than - // failing the whole call — the caller asked for several roots and most came back. + // with what we have (see parseAPIResponse) rather than failing the whole call — + // the caller asked for several roots and most came back. The gap is logged for + // operators and carried into the result below so the LLM caller sees it too. if (missingNodeIds.length > 0) { Logger.log( `Skipped ${missingNodeIds.length} unresolved node id(s): ${missingNodeIds.join(", ")}`, @@ -60,6 +61,8 @@ export async function simplifyRawFigmaObject( componentSets, traversalState.componentPropertyDefinitions, ), + // Only present on a partial miss, so the common case pays no tokens for it. + ...(missingNodeIds.length > 0 ? { missingNodeIds } : {}), globalVars, elements, }; diff --git a/src/extractors/types.ts b/src/extractors/types.ts index c74350cb..18e6585f 100644 --- a/src/extractors/types.ts +++ b/src/extractors/types.ts @@ -107,6 +107,13 @@ export interface SimplifiedDesign { nodes: SimplifiedNode[]; components: Record; componentSets: Record; + /** + * Requested node ids the Figma API returned as null (deleted/inaccessible/ + * wrong file) on a multi-node fetch where at least one other node resolved. + * Surfaced so the LLM caller knows the result is partial rather than silently + * acting on an incomplete design. Omitted entirely when nothing was missing. + */ + missingNodeIds?: string[]; globalVars: GlobalVars; /** * Deduplicated element bodies, keyed by content hash (`EL-xxxxxxxx`). Populated diff --git a/src/tests/multi-node.test.ts b/src/tests/multi-node.test.ts index 0ff51103..d947544f 100644 --- a/src/tests/multi-node.test.ts +++ b/src/tests/multi-node.test.ts @@ -3,6 +3,8 @@ import { simplifyRawFigmaObject } from "~/extractors/design-extractor.js"; import { allExtractors } from "~/extractors/built-in.js"; import { getFigmaDataTool } from "~/mcp/tools/get-figma-data-tool.js"; import { countNamedStyles, detectVariables } from "~/services/get-figma-data-metrics.js"; +import { wrapForSerialization } from "~/utils/serializable-design.js"; +import { serializeAsTree } from "~/utils/serialize-tree.js"; import { getErrorMeta } from "~/utils/error-meta.js"; import type { GetFileNodesResponse, Node as FigmaNode, Style } from "@figma/rest-api-spec"; @@ -49,7 +51,7 @@ describe("multi-node GetFileNodesResponse handling", () => { expect(result.nodes.map((n) => n.id)).toEqual(["1:2", "3:4"]); }); - it("skips null entries and resolves with just the found nodes", async () => { + it("skips null entries and surfaces the missing ids on the result", async () => { const response = makeNodesResponse({ "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, "9:9": null, @@ -59,6 +61,19 @@ describe("multi-node GetFileNodesResponse handling", () => { expect(result.nodes).toHaveLength(1); expect(result.nodes[0].name).toBe("Frame A"); + // Partial miss is reported back, not swallowed — the LLM must know the + // result is incomplete. + expect(result.missingNodeIds).toEqual(["9:9"]); + }); + + it("omits missingNodeIds entirely when every requested node resolved", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, + }); + + const result = await simplifyRawFigmaObject(response, allExtractors); + + expect(result).not.toHaveProperty("missingNodeIds"); }); it("rejects with a not_found error when every requested node is null", async () => { @@ -176,6 +191,33 @@ describe("metrics tolerate null node entries (partial miss)", () => { }); }); +describe("partial-miss warning reaches serialized output", () => { + it("renders a MISSING_NODES line in the tree format on a partial miss", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, + "9:9": null, + }); + + const tree = serializeAsTree( + wrapForSerialization(await simplifyRawFigmaObject(response, allExtractors)), + ); + + expect(tree).toContain("MISSING_NODES: 9:9"); + }); + + it("emits no MISSING_NODES line when the fetch is complete", async () => { + const response = makeNodesResponse({ + "1:2": { document: makeNode({ id: "1:2", name: "Frame A", type: "FRAME" }) }, + }); + + const tree = serializeAsTree( + wrapForSerialization(await simplifyRawFigmaObject(response, allExtractors)), + ); + + expect(tree).not.toContain("MISSING_NODES"); + }); +}); + describe("get_figma_data nodeId schema", () => { it("accepts a comma-separated list of node ids", () => { const result = getFigmaDataTool.parametersSchema.safeParse({ diff --git a/src/utils/serialize-tree.ts b/src/utils/serialize-tree.ts index 15c6821c..c7af1701 100644 --- a/src/utils/serialize-tree.ts +++ b/src/utils/serialize-tree.ts @@ -23,6 +23,13 @@ export function serializeAsTree(design: SerializableDesign): string { // whitespace, which would otherwise produce a malformed `NAME: foo: bar` line. sections.push(`NAME: ${quote(design.metadata.name)}`); + // Partial-miss warning: requested nodes the API couldn't resolve. Present only + // on a multi-node fetch where some ids resolved and some didn't, so the LLM + // doesn't treat a partial result as complete. + if (design.metadata.missingNodeIds && design.metadata.missingNodeIds.length > 0) { + sections.push(`MISSING_NODES: ${design.metadata.missingNodeIds.join(", ")}`); + } + if (Object.keys(design.globalVars.styles).length > 0) { sections.push(`\nGLOBAL_VARS:\n${dumpYaml(design.globalVars.styles)}`); } From 8b22087dd62b333d250558d670aaab25fe9a837b Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:37:42 +0000 Subject: [PATCH 12/19] fix(figma-api): type component properties against rest-api-spec 0.47 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spec now types ComponentProperty.value / ComponentPropertyDefinition .defaultValue as boolean | string | SlotContentId (new SLOT kind). The two casts in built-in.ts had been hiding the union; the simplifiers now take the spec types and narrow on the property kind, so a SLOT guid can never reach the flat name -> scalar output. VariableValue's new VariableComposedColor needs nothing: no code narrows VariableValue. Also reconciles the endpoint assertions from upstream #404 with the geometry=paths query upstream #420 added (the two PRs never met upstream). 🤖 Generated with BLOCKS! --- src/extractors/built-in.ts | 13 ++------ src/tests/component-properties.test.ts | 38 +++++++++++++++++++++ src/tests/figma-service.test.ts | 8 ++--- src/transformers/component.ts | 46 ++++++++++++++++++++------ 4 files changed, 81 insertions(+), 24 deletions(-) create mode 100644 src/tests/component-properties.test.ts diff --git a/src/extractors/built-in.ts b/src/extractors/built-in.ts index fb835b87..e67de58c 100644 --- a/src/extractors/built-in.ts +++ b/src/extractors/built-in.ts @@ -234,10 +234,8 @@ export const componentExtractor: ExtractorFn = (node, result, context) => { if (hasValue("componentId", node)) { result.componentId = node.componentId; } - if (hasValue("componentProperties", node)) { - const props = simplifyComponentProperties( - node.componentProperties as Record, - ); + if (node.componentProperties) { + const props = simplifyComponentProperties(node.componentProperties); if (Object.keys(props).length > 0) { result.componentProperties = props; } @@ -265,12 +263,7 @@ export const componentExtractor: ExtractorFn = (node, result, context) => { node.componentPropertyDefinitions && typeof node.componentPropertyDefinitions === "object" ) { - const defs = simplifyPropertyDefinitions( - node.componentPropertyDefinitions as Record< - string, - { type: string; defaultValue: boolean | string } - >, - ); + const defs = simplifyPropertyDefinitions(node.componentPropertyDefinitions); if (Object.keys(defs).length > 0) { context.traversalState.componentPropertyDefinitions[node.id] = defs; } diff --git a/src/tests/component-properties.test.ts b/src/tests/component-properties.test.ts new file mode 100644 index 00000000..c015ec48 --- /dev/null +++ b/src/tests/component-properties.test.ts @@ -0,0 +1,38 @@ +import type { ComponentProperty, ComponentPropertyDefinition } from "@figma/rest-api-spec"; +import { describe, expect, it } from "vitest"; +import { + simplifyComponentProperties, + simplifyPropertyDefinitions, +} from "~/transformers/component.js"; + +// @figma/rest-api-spec 0.47 added the SLOT property kind, whose value is a +// SlotContentId object rather than a scalar. The simplified output must stay +// a flat name -> boolean | string map. +const slotContent = { guid: { sessionID: 1, localID: 2 } }; + +describe("component properties with SLOT kind", () => { + it("keeps BOOLEAN/TEXT instance values and drops SLOT without leaking the guid", () => { + const properties: Record = { + "Show icon#1:0": { type: "BOOLEAN", value: true }, + "Label#1:1": { type: "TEXT", value: "Buy" }, + "Content#1:2": { type: "SLOT", value: slotContent }, + Size: { type: "VARIANT", value: "Large" }, + }; + + expect(simplifyComponentProperties(properties)).toEqual({ + "Show icon": true, + Label: "Buy", + }); + }); + + it("drops SLOT property definitions the same way", () => { + const definitions: Record = { + "Label#1:1": { type: "TEXT", defaultValue: "Buy" }, + "Content#1:2": { type: "SLOT", defaultValue: slotContent }, + }; + + expect(simplifyPropertyDefinitions(definitions)).toEqual({ + Label: { type: "text", defaultValue: "Buy" }, + }); + }); +}); diff --git a/src/tests/figma-service.test.ts b/src/tests/figma-service.test.ts index d208e3ba..44c1f58d 100644 --- a/src/tests/figma-service.test.ts +++ b/src/tests/figma-service.test.ts @@ -77,7 +77,7 @@ describe("FigmaService request/error path", () => { await service.getRawNode("ABC", "1:2"); - expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2"); + expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2&geometry=paths"); }); it("appends depth to the nodes endpoint when provided", async () => { @@ -89,7 +89,7 @@ describe("FigmaService request/error path", () => { await service.getRawNode("ABC", "1:2", 3); - expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2&depth=3"); + expect(firstRequestUrl()).toContain("/files/ABC/nodes?ids=1:2&geometry=paths&depth=3"); }); it("builds the file endpoint for getRawFile", async () => { @@ -101,7 +101,7 @@ describe("FigmaService request/error path", () => { await service.getRawFile("ABC"); - expect(firstRequestUrl()).toMatch(/\/files\/ABC$/); + expect(firstRequestUrl()).toMatch(/\/files\/ABC\?geometry=paths$/); }); it("appends depth to the file endpoint when provided", async () => { @@ -113,7 +113,7 @@ describe("FigmaService request/error path", () => { await service.getRawFile("ABC", 2); - expect(firstRequestUrl()).toContain("/files/ABC?depth=2"); + expect(firstRequestUrl()).toContain("/files/ABC?geometry=paths&depth=2"); }); }); diff --git a/src/transformers/component.ts b/src/transformers/component.ts index faa53887..62290df5 100644 --- a/src/transformers/component.ts +++ b/src/transformers/component.ts @@ -1,4 +1,9 @@ -import type { Component, ComponentSet } from "@figma/rest-api-spec"; +import type { + Component, + ComponentProperty, + ComponentPropertyDefinition, + ComponentSet, +} from "@figma/rest-api-spec"; export interface SimplifiedPropertyDefinition { type: string; @@ -30,20 +35,39 @@ export function stripPropertyNameSuffix(name: string): string { return hashIndex === -1 ? name : name.substring(0, hashIndex); } +/** + * Only BOOLEAN and TEXT properties carry a value an LLM can act on. VARIANT and + * INSTANCE_SWAP values are component keys / variant names already visible on + * the instance, and a SLOT value is a `SlotContentId` — an internal node guid + * whose content is the instance's own children in the simplified tree — so + * emitting it would spend tokens on something unresolvable. Narrowing on the + * type (rather than on `typeof value`) is what keeps the guid object out of the + * output: the spec types `value` / `defaultValue` as + * `boolean | string | SlotContentId` across all kinds. + */ +function scalarValue( + prop: ComponentProperty | ComponentPropertyDefinition, +): boolean | string | undefined { + if (prop.type !== "BOOLEAN" && prop.type !== "TEXT") return undefined; + const value = "value" in prop ? prop.value : prop.defaultValue; + return typeof value === "boolean" || typeof value === "string" ? value : undefined; +} + /** * Simplify componentPropertyDefinitions from the raw Figma format to a flat - * Record of property name → default value. Only extracts BOOLEAN and TEXT - * properties for Phase 1. + * Record of property name → default value. Only BOOLEAN and TEXT properties + * are kept (see `scalarValue`). */ export function simplifyPropertyDefinitions( - definitions: Record, + definitions: Record, ): Record { const result: Record = {}; for (const [name, def] of Object.entries(definitions)) { - if (def.type === "BOOLEAN" || def.type === "TEXT") { + const defaultValue = scalarValue(def); + if (defaultValue !== undefined) { result[stripPropertyNameSuffix(name)] = { type: def.type.toLowerCase(), - defaultValue: def.defaultValue, + defaultValue, }; } } @@ -71,15 +95,17 @@ export function simplifyPropertyReferences( /** * Simplify instance componentProperties from the verbose Figma format to a flat - * Record of property name → value. Only extracts BOOLEAN and TEXT properties for Phase 1. + * Record of property name → value. Only BOOLEAN and TEXT properties are kept + * (see `scalarValue`). */ export function simplifyComponentProperties( - properties: Record, + properties: Record, ): Record { const result: Record = {}; for (const [name, prop] of Object.entries(properties)) { - if (prop.type === "BOOLEAN" || prop.type === "TEXT") { - result[stripPropertyNameSuffix(name)] = prop.value; + const value = scalarValue(prop); + if (value !== undefined) { + result[stripPropertyNameSuffix(name)] = value; } } return result; From 18bcfb124386420ddd9b091c7f04adde8d8f719f Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:42:25 +0000 Subject: [PATCH 13/19] feat(auth): resolve the Figma credential on every request, retry once on 401 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Figma keeps one live access token per app per user, so a refresh by the issuer (the Blocks OAuth monitor) kills the token a long-running server read at startup. FigmaService now takes a CredentialSource evaluated per request: token file (--figma-oauth-token-file / FIGMA_OAUTH_TOKEN_FILE, default ~/.config/figma/.oauth_token) -> --figma-oauth-token / FIGMA_OAUTH_TOKEN -> --figma-api-key / FIGMA_API_KEY. On a 401 it re-resolves and retries once only if the token changed; otherwise (or on a second 401) it throws a message that names get_new_figma_token and the one-token rule. HTTP per-request header auth is unchanged (fixed for that request). The static FigmaAuthOptions triple is still accepted everywhere, wrapped as a constant source, so existing callers and tests are untouched. The 403 and 429 messages are as before. 🤖 Generated with BLOCKS! --- README.md | 16 +++ src/bin.ts | 5 + src/commands/fetch.ts | 15 ++- src/config.ts | 100 ++++++++++++----- src/mcp-server.ts | 6 +- src/mcp/index.ts | 4 +- src/server.ts | 39 ++++--- src/services/errors/index.ts | 1 + src/services/errors/unauthorized.ts | 39 +++++++ src/services/figma.ts | 143 ++++++++++++++++++------ src/tests/credential-resolution.test.ts | 140 +++++++++++++++++++++++ 11 files changed, 425 insertions(+), 83 deletions(-) create mode 100644 src/services/errors/unauthorized.ts create mode 100644 src/tests/credential-resolution.test.ts diff --git a/README.md b/README.md index 9cdbf3d3..0732aa4a 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,22 @@ Or you can set `FIGMA_API_KEY` and `PORT` in the `env` field. If you need more information on how to configure the Framelink MCP for Figma, see the [Framelink docs](https://www.framelink.ai/docs/quickstart?utm_source=github&utm_medium=referral&utm_campaign=readme). +## Authentication + +The server resolves its Figma credential **on every request**, in this order: + +| Priority | Source | Sent as | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- | +| 1 | Token file: `--figma-oauth-token-file` / `FIGMA_OAUTH_TOKEN_FILE`, default `~/.config/figma/.oauth_token` (trimmed; a missing or empty file is skipped; set the variable to an empty string to disable the lookup) | `Authorization: Bearer` | +| 2 | `--figma-oauth-token` / `FIGMA_OAUTH_TOKEN` | `Authorization: Bearer` | +| 3 | `--figma-api-key` / `FIGMA_API_KEY` (personal access token) | `X-Figma-Token` | + +In HTTP mode a per-request `Authorization: Bearer …` or `X-Figma-Token` header overrides all of the above for that request. + +Why per request: Figma keeps **one live access token per app per user**, so whenever an OAuth token is refreshed the previous one stops working. A platform that refreshes tokens for you (Blocks does, writing the current token to the token file) therefore invalidates whatever a long-running server read at startup. Re-reading the file per request means a rotated token is used without a restart, and on a `401` the server re-resolves the credential once more and retries once if it changed. If the token is unchanged, or the retry is rejected too, the tool returns an error that says so and tells the agent to fetch the current token (the `get_new_figma_token` tool inside Blocks) or wait up to a minute for the refreshed one to land. + +In stdio mode the server does not read a `.env` file from its working directory (an MCP client spawns it with an arbitrary cwd); pass `--env ` to load one explicitly. HTTP mode and the `fetch` subcommand still load `./.env`. + ## Star History Star History Chart diff --git a/src/bin.ts b/src/bin.ts index 4bac32df..c666743c 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -17,6 +17,11 @@ const argv = cli({ type: String, description: "Figma OAuth Bearer token", }, + figmaOauthTokenFile: { + type: String, + description: + "File holding a Figma OAuth token, re-read on every request so a rotated token is picked up without a restart. Defaults to ~/.config/figma/.oauth_token; pass an empty string to disable.", + }, env: { type: String, description: "Path to custom .env file to load environment variables from", diff --git a/src/commands/fetch.ts b/src/commands/fetch.ts index b3838027..2d6a46c1 100644 --- a/src/commands/fetch.ts +++ b/src/commands/fetch.ts @@ -1,8 +1,8 @@ import { type Command, command } from "cleye"; import { + createCredentialSource, loadEnvFile, parseOutputFormat, - resolveAuth, requireGlobalCredentials, UsageError, } from "~/config.js"; @@ -45,6 +45,10 @@ export const fetchCommand: Command = command( type: String, description: "Figma OAuth token", }, + figmaOauthTokenFile: { + type: String, + description: "File holding a Figma OAuth token (default ~/.config/figma/.oauth_token)", + }, env: { type: String, description: "Path to .env file", @@ -68,6 +72,7 @@ async function run( format?: string; figmaApiKey?: string; figmaOauthToken?: string; + figmaOauthTokenFile?: string; env?: string; }, positionals: string[], @@ -92,11 +97,11 @@ async function run( } loadEnvFile(flags.env); - const auth = resolveAuth(flags); + const credentials = createCredentialSource(flags); // The fetch CLI has no per-request credential channel (unlike HTTP mode). // Fail fast so the user gets an actionable error instead of an HTTP-shaped - // one from `getAuthHeaders`. - requireGlobalCredentials(auth); + // one from the request path. + requireGlobalCredentials(credentials); // The fetch CLI stays yaml-by-default (unlike the MCP server, which defaults // to tree): its output is piped into standard tooling (`> out.yaml`, `| jq`), @@ -106,7 +111,7 @@ async function run( parseOutputFormat(flags.format, "--format") ?? (flags.json ? "json" : "yaml"); const result = await getFigmaData( - new FigmaService(auth), + new FigmaService(credentials), { fileKey, nodeId, depth: flags.depth }, outputFormat, ); diff --git a/src/config.ts b/src/config.ts index 34b2e32b..01a7af67 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,6 +1,8 @@ import { config as loadEnv } from "dotenv"; +import { readFileSync } from "fs"; +import { homedir } from "os"; import { resolve as resolvePath } from "path"; -import type { FigmaAuthOptions } from "./services/figma.js"; +import type { CredentialSource, FigmaCredential } from "./services/figma.js"; import { VALID_OUTPUT_FORMATS, isOutputFormat, type OutputFormat } from "./utils/serialize.js"; export type Source = "cli" | "env" | "default"; @@ -13,6 +15,7 @@ export interface Resolved { export interface ServerFlags { figmaApiKey?: string; figmaOauthToken?: string; + figmaOauthTokenFile?: string; env?: string; port?: number; host?: string; @@ -25,7 +28,7 @@ export interface ServerFlags { } export interface ServerConfig { - auth: FigmaAuthOptions; + auth: CredentialSource; port: number; host: string; proxy: string | undefined; @@ -100,21 +103,61 @@ export function loadEnvFile(envPath: string | undefined, { implicit = true } = { return envFilePath; } -export function resolveAuth(flags: { +export const DEFAULT_OAUTH_TOKEN_FILE = "~/.config/figma/.oauth_token"; + +export type AuthFlags = { figmaApiKey?: string; figmaOauthToken?: string; -}): FigmaAuthOptions { - const figmaApiKey = resolve(flags.figmaApiKey, envStr("FIGMA_API_KEY"), ""); - const figmaOauthToken = resolve(flags.figmaOauthToken, envStr("FIGMA_OAUTH_TOKEN"), ""); + figmaOauthTokenFile?: string; +}; - const useOAuth = Boolean(figmaOauthToken.value); - const auth: FigmaAuthOptions = { - figmaApiKey: figmaApiKey.value, - figmaOAuthToken: figmaOauthToken.value, - useOAuth, - }; +/** + * Where the token file lives. The flag wins, then `FIGMA_OAUTH_TOKEN_FILE`, + * then the default path. Setting either to an empty string disables the file + * lookup entirely (for hosts that want env-only credentials). + */ +function resolveTokenFilePath(flag: string | undefined): string | undefined { + const raw = resolve(flag, process.env.FIGMA_OAUTH_TOKEN_FILE, DEFAULT_OAUTH_TOKEN_FILE).value; + if (raw === "") return undefined; + return raw.startsWith("~/") ? resolvePath(homedir(), raw.slice(2)) : resolvePath(raw); +} - return auth; +function readTokenFile(path: string): string | undefined { + try { + return readFileSync(path, "utf8").trim() || undefined; + } catch { + // Missing or unreadable is the normal case outside a Blocks sandbox. + return undefined; + } +} + +/** + * The server-default credential chain, evaluated on EVERY call (see + * `CredentialSource`): token file → OAuth token (flag, then env) → personal + * access token (flag, then env). The file comes first because it is the one + * slot an external refresher keeps current; flags and env vars are the + * startup snapshot and cannot change under a running process. + */ +export function createCredentialSource(flags: AuthFlags): CredentialSource { + return (): FigmaCredential | undefined => { + const filePath = resolveTokenFilePath(flags.figmaOauthTokenFile); + const fileToken = filePath ? readTokenFile(filePath) : undefined; + if (fileToken) return { kind: "oauth", token: fileToken, source: filePath! }; + + if (flags.figmaOauthToken) { + return { kind: "oauth", token: flags.figmaOauthToken, source: "--figma-oauth-token" }; + } + const envOauth = envStr("FIGMA_OAUTH_TOKEN"); + if (envOauth) return { kind: "oauth", token: envOauth, source: "FIGMA_OAUTH_TOKEN" }; + + if (flags.figmaApiKey) { + return { kind: "pat", token: flags.figmaApiKey, source: "--figma-api-key" }; + } + const envKey = envStr("FIGMA_API_KEY"); + if (envKey) return { kind: "pat", token: envKey, source: "FIGMA_API_KEY" }; + + return undefined; + }; } /** @@ -138,10 +181,10 @@ export class UsageError extends Error { * something resolvable at startup or they'd just defer the failure to the * first tool call with a misleading "send X-Figma-Token" message. */ -export function requireGlobalCredentials(auth: FigmaAuthOptions): void { - if (auth.figmaApiKey || auth.figmaOAuthToken) return; +export function requireGlobalCredentials(credentials: CredentialSource): void { + if (credentials()) return; throw new UsageError( - "Either FIGMA_API_KEY or FIGMA_OAUTH_TOKEN is required (via CLI argument or .env file)", + `Either FIGMA_API_KEY or FIGMA_OAUTH_TOKEN is required (via CLI argument, environment variable, .env file, or a token file at ${DEFAULT_OAUTH_TOKEN_FILE})`, ); } @@ -153,11 +196,16 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { const envFileSource: Source = flags.env !== undefined ? "cli" : "default"; // Auth - const auth = resolveAuth(flags); + const auth = createCredentialSource(flags); // Resolve config values: CLI flag → env var → default const figmaApiKey = resolve(flags.figmaApiKey, envStr("FIGMA_API_KEY"), ""); const figmaOauthToken = resolve(flags.figmaOauthToken, envStr("FIGMA_OAUTH_TOKEN"), ""); + const figmaOauthTokenFile = resolve( + flags.figmaOauthTokenFile, + envStr("FIGMA_OAUTH_TOKEN_FILE"), + DEFAULT_OAUTH_TOKEN_FILE, + ); const port = resolve(flags.port, envInt("FRAMELINK_PORT", "PORT"), 3333); const host = resolve(flags.host, envStr("FRAMELINK_HOST"), "127.0.0.1"); const skipImageDownloads = resolve( @@ -188,6 +236,7 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { envFile: envFileSource, figmaApiKey: figmaApiKey.source, figmaOauthToken: figmaOauthToken.source, + figmaOauthTokenFile: figmaOauthTokenFile.source, port: port.source, host: host.source, proxy: proxy.source, @@ -199,15 +248,16 @@ export function getServerConfig(flags: ServerFlags): ServerConfig { if (!isStdioMode) { console.log("\nConfiguration:"); console.log(`- ENV_FILE: ${envFilePath} (source: ${configSources.envFile})`); - if (auth.useOAuth) { - console.log( - `- FIGMA_OAUTH_TOKEN: ${maskApiKey(auth.figmaOAuthToken)} (source: ${configSources.figmaOauthToken})`, - ); + // Startup snapshot only — the chain is re-evaluated on every request. + const credential = auth(); + console.log( + `- FIGMA_OAUTH_TOKEN_FILE: ${figmaOauthTokenFile.value || "(disabled)"} (source: ${configSources.figmaOauthTokenFile})`, + ); + if (credential?.kind === "oauth") { + console.log(`- OAuth token: ${maskApiKey(credential.token)} (source: ${credential.source})`); console.log("- Authentication Method: OAuth Bearer Token"); - } else if (auth.figmaApiKey) { - console.log( - `- FIGMA_API_KEY: ${maskApiKey(auth.figmaApiKey)} (source: ${configSources.figmaApiKey})`, - ); + } else if (credential) { + console.log(`- API key: ${maskApiKey(credential.token)} (source: ${credential.source})`); console.log("- Authentication Method: Personal Access Token (X-Figma-Token)"); } else { console.log("- Authentication Method: Per-request X-Figma-Token header"); diff --git a/src/mcp-server.ts b/src/mcp-server.ts index cd2c97b7..244f5931 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -1,6 +1,8 @@ // Re-export server-related functionality for users who want MCP server capabilities export { createServer } from "./mcp/index.js"; export type { FigmaService } from "./services/figma.js"; -export { getServerConfig, UsageError } from "./config.js"; -export type { ServerConfig } from "./config.js"; +export { staticCredentials } from "./services/figma.js"; +export type { CredentialSource, FigmaAuthOptions, FigmaCredential } from "./services/figma.js"; +export { createCredentialSource, getServerConfig, UsageError } from "./config.js"; +export type { AuthFlags, ServerConfig } from "./config.js"; export { startServer, startHttpServer, stopHttpServer } from "./server.js"; diff --git a/src/mcp/index.ts b/src/mcp/index.ts index 1e796d12..04162389 100644 --- a/src/mcp/index.ts +++ b/src/mcp/index.ts @@ -1,5 +1,5 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { FigmaService, type FigmaAuthOptions } from "../services/figma.js"; +import { FigmaService, type CredentialSource, type FigmaAuthOptions } from "../services/figma.js"; import { Logger } from "../utils/logger.js"; import type { OutputFormat } from "~/utils/serialize.js"; import { installFriendlyValidationErrors } from "./validation-errors.js"; @@ -28,7 +28,7 @@ export type CreateServerOptions = { }; function createServer( - authOptions: FigmaAuthOptions, + authOptions: FigmaAuthOptions | CredentialSource, { transport, outputFormat = "tree", skipImageDownloads = false, imageDir }: CreateServerOptions, ) { const server = new McpServer(serverInfo); diff --git a/src/server.ts b/src/server.ts index 2e2e318f..6aedc96d 100644 --- a/src/server.ts +++ b/src/server.ts @@ -8,7 +8,12 @@ import { Logger } from "./utils/logger.js"; import { hasProxyEnv, setProxyMode } from "./utils/proxy-env.js"; import { createServer, type CreateServerOptions } from "./mcp/index.js"; import { requireGlobalCredentials, type ServerConfig } from "./config.js"; -import type { FigmaAuthOptions } from "./services/figma.js"; +import { + staticCredentials, + toCredentialSource, + type CredentialSource, + type FigmaAuthOptions, +} from "./services/figma.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { ErrorCode } from "@modelcontextprotocol/sdk/types.js"; @@ -111,12 +116,13 @@ function registerShutdownHandlers(onShutdown: () => Promise): void { export async function startHttpServer( host: string, port: number, - baseAuth: FigmaAuthOptions, + baseAuth: FigmaAuthOptions | CredentialSource, serverOptions: Omit, ): Promise { if (httpServer) { throw new Error("HTTP server is already running"); } + const baseCredentials = toCredentialSource(baseAuth); const app = createMcpExpressApp({ host }); @@ -124,7 +130,7 @@ export async function startHttpServer( Logger.log("Received StreamableHTTP request"); const requestKey = getRequestApiKey(req); const requestBearerToken = getRequestBearerToken(req); - const auth = resolveRequestAuth(baseAuth, requestKey, requestBearerToken); + const auth = resolveRequestAuth(baseCredentials, requestKey, requestBearerToken); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); const mcpServer = createServer(auth, { ...serverOptions, transport: "http" }); @@ -183,25 +189,28 @@ export async function startHttpServer( }); } +/** + * Per-request header credentials are fixed for the life of that request (a + * 401 cannot be retried with anything fresher); without them the server + * default chain applies. + */ function resolveRequestAuth( - baseAuth: FigmaAuthOptions, + baseAuth: CredentialSource, requestKey: string | undefined, requestBearerToken: string | undefined, -): FigmaAuthOptions { +): CredentialSource { if (requestKey) { - return { - figmaApiKey: requestKey, - figmaOAuthToken: "", - useOAuth: false, - }; + return staticCredentials( + { figmaApiKey: requestKey, figmaOAuthToken: "", useOAuth: false }, + "the X-Figma-Token request header", + ); } if (requestBearerToken) { - return { - figmaApiKey: "", - figmaOAuthToken: requestBearerToken, - useOAuth: true, - }; + return staticCredentials( + { figmaApiKey: "", figmaOAuthToken: requestBearerToken, useOAuth: true }, + "the Authorization request header", + ); } return baseAuth; diff --git a/src/services/errors/index.ts b/src/services/errors/index.ts index 0634327e..61ee0ab0 100644 --- a/src/services/errors/index.ts +++ b/src/services/errors/index.ts @@ -1,2 +1,3 @@ export { buildForbiddenMessage } from "./forbidden.js"; export { buildRateLimitMessage } from "./rate-limit.js"; +export { buildUnauthorizedMessage } from "./unauthorized.js"; diff --git a/src/services/errors/unauthorized.ts b/src/services/errors/unauthorized.ts new file mode 100644 index 00000000..abb9fe52 --- /dev/null +++ b/src/services/errors/unauthorized.ts @@ -0,0 +1,39 @@ +import type { FigmaCredential } from "~/services/figma.js"; +import { HttpError } from "~/utils/fetch-json.js"; + +const CREDENTIAL_LABEL: Record = { + oauth: "OAuth access token", + pat: "personal access token", +}; + +/** + * Build a user-facing 401 message. Figma answers 401 for an invalid or revoked + * token (403 is permissions/scopes, handled separately). The caller has + * already re-resolved the credential and either found it unchanged or retried + * once with the new one, so by the time this renders there is nothing more + * the server can do by itself — the message tells the agent what can. + */ +export function buildUnauthorizedMessage( + endpoint: string, + credential: FigmaCredential, + error: unknown, + { retried = false }: { retried?: boolean } = {}, +): string { + const body = error instanceof HttpError ? error.responseBody : undefined; + const sections: string[][] = [ + [ + `Request to Figma API endpoint '${endpoint}' returned 401 Unauthorized: Figma rejected the ${CREDENTIAL_LABEL[credential.kind]} read from ${credential.source}.`, + ...(body ? [`Response body: ${body}`] : []), + ], + [ + "The token was rotated or revoked. Figma keeps only ONE live access token per app per user, so refreshing a token anywhere (including a scheduled refresh by the platform that issued it) invalidates every copy still in use.", + ...(retried + ? ["The token was re-read after the first 401 and the new value was rejected as well."] + : []), + ], + [ + "What to do: if this server runs inside a Blocks sandbox, call the `get_new_figma_token` tool to fetch the current token, or wait up to a minute for the refreshed token to land, then retry. Otherwise issue a new token in Figma and restart the server with it.", + ], + ]; + return sections.map((section) => section.join("\n")).join("\n\n"); +} diff --git a/src/services/figma.ts b/src/services/figma.ts index 4a19fdd8..684a30a3 100644 --- a/src/services/figma.ts +++ b/src/services/figma.ts @@ -9,14 +9,58 @@ import { downloadAndProcessImage, type ImageProcessingResult } from "~/utils/ima import { Logger, writeLogs } from "~/utils/logger.js"; import { fetchJSON } from "~/utils/fetch-json.js"; import { getErrorMeta } from "~/utils/error-meta.js"; -import { buildForbiddenMessage, buildRateLimitMessage } from "./errors/index.js"; +import { + buildForbiddenMessage, + buildRateLimitMessage, + buildUnauthorizedMessage, +} from "./errors/index.js"; + +/** + * A credential as used for one request. `source` names where it came from + * (a file path, an env var, a flag, "HTTP request header") for logs and error + * messages — never the token itself. + */ +export type FigmaCredential = { + kind: "oauth" | "pat"; + token: string; + source: string; +}; +/** + * Credentials are resolved per request, not per server: Figma keeps a single + * live access token per app per user, so when the platform that issued an + * OAuth token refreshes it, the copy this process read at startup dies. A + * source is re-evaluated on every call (and again after a 401) so a rotated + * token is picked up without a restart. Returning `undefined` means "nothing + * configured" and fails the request before it is sent. + */ +export type CredentialSource = () => FigmaCredential | undefined; + +/** + * Fixed credentials: HTTP per-request headers, the test suite, and library + * callers that already hold a token. `useOAuth` decides which header carries + * `figmaOAuthToken`; an empty token falls through to the API key. + */ export type FigmaAuthOptions = { figmaApiKey: string; figmaOAuthToken: string; useOAuth: boolean; }; +export function staticCredentials(auth: FigmaAuthOptions, source = "static"): CredentialSource { + const credential: FigmaCredential | undefined = + auth.useOAuth && auth.figmaOAuthToken + ? { kind: "oauth", token: auth.figmaOAuthToken, source } + : auth.figmaApiKey + ? { kind: "pat", token: auth.figmaApiKey, source } + : undefined; + return () => credential; +} + +export function toCredentialSource(auth: FigmaAuthOptions | CredentialSource): CredentialSource { + return typeof auth === "function" ? auth : staticCredentials(auth); +} + type SvgOptions = { outlineText: boolean; includeId: boolean; @@ -24,31 +68,27 @@ type SvgOptions = { }; export class FigmaService { - private readonly apiKey: string; - private readonly oauthToken: string; - private readonly useOAuth: boolean; + private readonly credentials: CredentialSource; private readonly baseUrl = "https://api.figma.com/v1"; - constructor({ figmaApiKey, figmaOAuthToken, useOAuth }: FigmaAuthOptions) { - this.apiKey = figmaApiKey || ""; - this.oauthToken = figmaOAuthToken || ""; - this.useOAuth = !!useOAuth && !!this.oauthToken; + constructor(auth: FigmaAuthOptions | CredentialSource) { + this.credentials = toCredentialSource(auth); } - private getAuthHeaders(): Record { - if (this.useOAuth) { - Logger.log("Using OAuth Bearer token for authentication"); - return { Authorization: `Bearer ${this.oauthToken}` }; - } - - if (!this.apiKey) { + private requireCredential(): FigmaCredential { + const credential = this.credentials(); + if (!credential) { throw new Error( "Figma API authentication is required. Configure FIGMA_API_KEY or FIGMA_OAUTH_TOKEN on the server, or send X-Figma-Token / Authorization: Bearer on the HTTP request.", ); } + return credential; + } - Logger.log("Using Personal Access Token for authentication"); - return { "X-Figma-Token": this.apiKey }; + private authHeaders(credential: FigmaCredential): Record { + return credential.kind === "oauth" + ? { Authorization: `Bearer ${credential.token}` } + : { "X-Figma-Token": credential.token }; } /** @@ -76,28 +116,63 @@ export class FigmaService { * continue to use `request` unchanged. */ private async requestWithSize(endpoint: string): Promise<{ data: T; rawSize: number }> { + const credential = this.requireCredential(); try { - Logger.log(`Calling ${this.baseUrl}${endpoint}`); - const headers = this.getAuthHeaders(); - - return await fetchJSON(`${this.baseUrl}${endpoint}`, { - headers, - redactFromResponseBody: [this.apiKey, this.oauthToken], - }); + return await this.send(endpoint, credential); } catch (error) { - const meta = getErrorMeta(error); - if (meta.http_status === 429) { - throw new Error(buildRateLimitMessage(error), { cause: error }); + if (getErrorMeta(error).http_status !== 401) { + throw this.describeFailure(endpoint, error); } - if (meta.http_status === 403) { - throw new Error(buildForbiddenMessage(endpoint, error), { cause: error }); + // A 401 is "this token is dead", and the usual reason is that it was + // rotated: the issuer refreshed it (killing the old one — Figma keeps one + // live token per app per user) and the new value has since landed in the + // token file. Re-resolve; a changed token means exactly that race, so + // retry once with it. An unchanged token is genuinely revoked — no retry. + const fresh = this.credentials(); + if (!fresh || fresh.token === credential.token) { + throw new Error(buildUnauthorizedMessage(endpoint, credential, error), { cause: error }); } - const errorMessage = error instanceof Error ? error.message : String(error); - throw new Error( - `Failed to make request to Figma API endpoint '${endpoint}': ${errorMessage}`, - { cause: error }, - ); + Logger.log(`Figma token from ${fresh.source} changed since the 401; retrying once`); + try { + return await this.send(endpoint, fresh); + } catch (retryError) { + if (getErrorMeta(retryError).http_status === 401) { + throw new Error( + buildUnauthorizedMessage(endpoint, fresh, retryError, { retried: true }), + { + cause: retryError, + }, + ); + } + throw this.describeFailure(endpoint, retryError); + } + } + } + + private send( + endpoint: string, + credential: FigmaCredential, + ): Promise<{ data: T; rawSize: number }> { + Logger.log(`Calling ${this.baseUrl}${endpoint} (${credential.kind} from ${credential.source})`); + return fetchJSON(`${this.baseUrl}${endpoint}`, { + headers: this.authHeaders(credential), + redactFromResponseBody: [credential.token], + }); + } + + private describeFailure(endpoint: string, error: unknown): Error { + const meta = getErrorMeta(error); + if (meta.http_status === 429) { + return new Error(buildRateLimitMessage(error), { cause: error }); } + if (meta.http_status === 403) { + return new Error(buildForbiddenMessage(endpoint, error), { cause: error }); + } + const errorMessage = error instanceof Error ? error.message : String(error); + return new Error( + `Failed to make request to Figma API endpoint '${endpoint}': ${errorMessage}`, + { cause: error }, + ); } /** diff --git a/src/tests/credential-resolution.test.ts b/src/tests/credential-resolution.test.ts new file mode 100644 index 00000000..9bf810f4 --- /dev/null +++ b/src/tests/credential-resolution.test.ts @@ -0,0 +1,140 @@ +import { mkdtempSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createCredentialSource } from "~/config.js"; +import { FigmaService } from "~/services/figma.js"; + +/** + * The server-default credential chain is re-evaluated on every request so an + * externally refreshed OAuth token (Figma keeps one live token per app per + * user) is picked up without a restart. These tests drive the real + * FigmaService request path with `fetch` mocked at the network boundary. + */ + +const figmaFileResponse = { + name: "Test File", + lastModified: "2026-01-01T00:00:00Z", + thumbnailUrl: "", + version: "1", + document: { id: "0:0", name: "Document", type: "DOCUMENT", children: [] }, + components: {}, + componentSets: {}, + schemaVersion: 0, + styles: {}, +}; + +const unauthorized = () => + Response.json({ status: 401, err: "Invalid token" }, { status: 401, statusText: "Unauthorized" }); + +describe("per-request credential resolution", () => { + let tokenFile: string; + let fetchMock: ReturnType; + + function stubFetch(respond: (headers: Record) => Response) { + fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => + respond((init?.headers as Record) ?? {}), + ); + vi.stubGlobal("fetch", fetchMock); + } + + function authHeaderOfCall(index: number): string | undefined { + const init = fetchMock.mock.calls[index][1] as RequestInit & { + headers?: Record; + }; + return init.headers?.Authorization ?? init.headers?.["X-Figma-Token"]; + } + + beforeEach(() => { + tokenFile = join(mkdtempSync(join(tmpdir(), "figma-mcp-token-")), ".oauth_token"); + vi.stubEnv("FIGMA_OAUTH_TOKEN_FILE", tokenFile); + vi.stubEnv("FIGMA_OAUTH_TOKEN", "env-oauth-token"); + vi.stubEnv("FIGMA_API_KEY", "env-api-key"); + stubFetch(() => Response.json(figmaFileResponse)); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + }); + + it("prefers the token file over FIGMA_OAUTH_TOKEN and FIGMA_API_KEY", async () => { + writeFileSync(tokenFile, "file-token\n"); + + await new FigmaService(createCredentialSource({})).getRawFile("abc"); + + expect(authHeaderOfCall(0)).toBe("Bearer file-token"); + }); + + it("falls through to the env OAuth token when the file is missing or blank", async () => { + writeFileSync(tokenFile, " \n"); + + await new FigmaService(createCredentialSource({})).getRawFile("abc"); + + expect(authHeaderOfCall(0)).toBe("Bearer env-oauth-token"); + }); + + it("picks up a rewritten token file between two calls without a restart", async () => { + const service = new FigmaService(createCredentialSource({})); + + writeFileSync(tokenFile, "token-one"); + await service.getRawFile("abc"); + writeFileSync(tokenFile, "token-two"); + await service.getRawFile("abc"); + + expect(authHeaderOfCall(0)).toBe("Bearer token-one"); + expect(authHeaderOfCall(1)).toBe("Bearer token-two"); + }); + + it("retries once with the re-read token when a 401 coincides with a rotation", async () => { + writeFileSync(tokenFile, "stale-token"); + stubFetch((headers) => { + if (headers.Authorization === "Bearer stale-token") { + // The refresher lands the new token while the stale request is in flight. + writeFileSync(tokenFile, "rotated-token"); + return unauthorized(); + } + return Response.json(figmaFileResponse); + }); + + const result = await new FigmaService(createCredentialSource({})).getRawFile("abc"); + + expect(result.data.name).toBe("Test File"); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(authHeaderOfCall(1)).toBe("Bearer rotated-token"); + }); + + it("does not retry an unchanged token and explains what the agent can do", async () => { + writeFileSync(tokenFile, "revoked-token"); + stubFetch(() => unauthorized()); + + const error = await new FigmaService(createCredentialSource({})) + .getRawFile("abc") + .catch((e: Error) => e); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain("401"); + expect(message).toContain("rotated or revoked"); + expect(message).toContain("get_new_figma_token"); + expect(message).toContain("live access token per app per user"); + expect(message).toContain(tokenFile); + expect(message).not.toContain("revoked-token"); + }); + + it("gives up after a second 401 on the rotated token", async () => { + writeFileSync(tokenFile, "stale-token"); + stubFetch((headers) => { + if (headers.Authorization === "Bearer stale-token") writeFileSync(tokenFile, "also-bad"); + return unauthorized(); + }); + + const error = await new FigmaService(createCredentialSource({})) + .getRawFile("abc") + .catch((e: Error) => e); + + expect(fetchMock).toHaveBeenCalledTimes(2); + expect((error as Error).message).toContain("re-read after the first 401"); + }); +}); From 7060eac35fc4927cbf6990669b926c6b78db1cde Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:44:21 +0000 Subject: [PATCH 14/19] chore: rename to @blocksuser/figma-mcp and document the Blocks fork MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit package name / bin (figma-mcp) / repository / homepage / mcpName and server.json now point at BlocksOrg; the release workflow's owner gate follows, pnpm publish gets --access public (scoped first publish), and the MCP registry steps are non-fatal (the registry listing is optional for the fork). README gains a Blocks fork section (why it exists, how to merge upstream) and the install snippets use the new package; FUNDING.yml (upstream's sponsor button) is removed. 🤖 Generated with BLOCKS! --- .claude/commands/release.md | 6 ++--- .github/FUNDING.yml | 3 --- .github/ISSUE_TEMPLATE/bug_report.md | 8 +++---- .github/workflows/release.yml | 9 +++++-- CONTRIBUTING.md | 2 +- README.md | 35 +++++++++++++++++++--------- SECURITY.md | 6 ++--- package.json | 18 ++++++++------ server.json | 8 +++---- src/bin.ts | 2 +- 10 files changed, 58 insertions(+), 39 deletions(-) delete mode 100644 .github/FUNDING.yml diff --git a/.claude/commands/release.md b/.claude/commands/release.md index f251f464..66c3c244 100644 --- a/.claude/commands/release.md +++ b/.claude/commands/release.md @@ -5,7 +5,7 @@ Review and publish a new release. ## Steps 1. **Check for a release-please PR:** - Run `gh pr list --repo GLips/Figma-Context-MCP --label "autorelease: pending" --json number,title,url` to find the open release PR. + Run `gh pr list --repo BlocksOrg/Figma-Context-MCP --label "autorelease: pending" --json number,title,url` to find the open release PR. If no release PR exists, inform the user: "No pending release PR. Release-please creates one automatically when conventional commits (`fix:`, `feat:`) land on `main`." @@ -24,7 +24,7 @@ Review and publish a new release. - **Cancel** — Stop without merging 4. **Merge the release PR:** - Run `gh pr merge --rebase --repo GLips/Figma-Context-MCP` (or merge via the GitHub UI). + Run `gh pr merge --rebase --repo BlocksOrg/Figma-Context-MCP` (or merge via the GitHub UI). **Use rebase, not squash.** Feature PRs are squash-merged (so each conventional-commit title, with its `(#NNN)`, feeds the changelog), but the release PR is the single `chore(main): release @@ -34,7 +34,7 @@ X.Y.Z` commit release-please authored. Rebase replays it onto `main` verbatim no PR suffix). Merging through the UI does the same thing. 5. **Verify:** - Run `gh run list --repo GLips/Figma-Context-MCP --limit 1` to confirm the Release workflow triggered. + Run `gh run list --repo BlocksOrg/Figma-Context-MCP --limit 1` to confirm the Release workflow triggered. Report the workflow run URL so the user can monitor npm publish. The Release workflow also bumps `server.json` and publishes to npm (OIDC) and the MCP registry — diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index df5a1060..00000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,3 +0,0 @@ -# These are supported funding model platforms - -github: GLips diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 49c24a30..580b6fd1 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -36,10 +36,10 @@ If applicable, add screenshots to help explain your problem. Often a screenshot Provide your MCP JSON configuration, if applicable. E.g. ``` - "figma-developer-mcp": { + "@blocksuser/figma-mcp": { "command": "npx", "args": [ - "figma-developer-mcp", + "@blocksuser/figma-mcp", "--figma-api-key=REDACTED", "--stdio" ] @@ -50,7 +50,7 @@ Provide your MCP JSON configuration, if applicable. E.g. If you're running the MCP locally on the command line, include all the logs for those like so: ``` -> npx figma-developer-mcp --figma-api-key=REDACTED +> npx @blocksuser/figma-mcp --figma-api-key=REDACTED Configuration: - FIGMA_API_KEY: ****8pXg (source: cli) @@ -68,7 +68,7 @@ If you're running the MCP in a code editor like Cursor, there are MCP-specific l ``` 2025-03-18 11:36:22.251 [info] pnpx: Handling CreateClient action 2025-03-18 11:36:22.251 [info] pnpx: getOrCreateClient for stdio server. process.platform: darwin isElectron: true -2025-03-18 11:36:22.251 [info] pnpx: Starting new stdio process with command: pnpx figma-developer-mcp --figma-api-key=REDACTED --stdio +2025-03-18 11:36:22.251 [info] pnpx: Starting new stdio process with command: pnpx @blocksuser/figma-mcp --figma-api-key=REDACTED --stdio 2025-03-18 11:36:23.987 [info] pnpx: Successfully connected to stdio server 2025-03-18 11:36:23.987 [info] pnpx: Storing stdio client 2025-03-18 11:36:23.988 [info] MCP: Handling ListOfferings action diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e40f82c7..762400ca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,7 +12,7 @@ permissions: jobs: release-please: - if: ${{ github.repository_owner == 'GLips' }} + if: ${{ github.repository_owner == 'BlocksOrg' }} runs-on: ubuntu-latest env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true @@ -46,8 +46,9 @@ jobs: run: pnpm build if: ${{ steps.release.outputs.release_created }} + # --access public: scoped packages default to restricted on first publish. - name: Publish to npm - run: pnpm publish --no-git-checks + run: pnpm publish --no-git-checks --access public env: NODE_ENV: production if: ${{ steps.release.outputs.release_created }} @@ -58,13 +59,17 @@ jobs: jq --arg v "$VERSION" '.version = $v | .packages[0].version = $v' server.json > server.tmp && mv server.tmp server.json if: ${{ steps.release.outputs.release_created }} + # The registry listing is a nice-to-have for the fork (Blocks consumes the + # npm package directly); never let it fail a release that already published. - name: Install mcp-publisher run: | curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_linux_amd64.tar.gz" | tar xz mcp-publisher if: ${{ steps.release.outputs.release_created }} + continue-on-error: true - name: Publish to MCP Registry run: | ./mcp-publisher login github-oidc ./mcp-publisher publish if: ${{ steps.release.outputs.release_created }} + continue-on-error: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 05a7bd17..a6808f5e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,7 @@ This focused approach ensures: 1. **Clone the repository:** ```bash - git clone https://github.com/GLips/Figma-Context-MCP.git + git clone https://github.com/BlocksOrg/Figma-Context-MCP.git cd Figma-Context-MCP ``` diff --git a/README.md b/README.md index 0732aa4a..aa39c078 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@

Framelink MCP for Figma

Give your coding agent access to your Figma data.
Implement designs in any framework in one-shot.

- - weekly downloads + + npm - - MIT License + + MIT License Discord @@ -25,6 +25,23 @@
+## Blocks fork + +This is the [Blocks](https://blocks.team) fork of [GLips/Figma-Context-MCP](https://github.com/GLips/Figma-Context-MCP) (Framelink MCP for Figma), published as [`@blocksuser/figma-mcp`](https://www.npmjs.com/package/@blocksuser/figma-mcp). Blocks runs this server inside agent sandboxes, which needs three things upstream does not provide: + +- **Hardened dependency tree.** `pnpm audit --prod --audit-level=high` is a CI gate (111 advisories at fork time, 0 now) and dependabot keeps it that way. A tombstone test keeps `child_process` out of `src/` (CVE-2025-53967 / CVE-2025-15061). +- **No telemetry.** This fork sends no telemetry; the PostHog client and its opt-out variables are gone. +- **Per-request credential resolution.** The Figma token is re-read from a file on every request and a `401` is retried once with a rotated token, so a platform-refreshed OAuth token works without restarting the server (see [Authentication](#authentication)). The stdio server also no longer reads `.env` from its working directory. + +Everything else — the tools, the simplified design format, the CLI — is upstream's, and upstream fixes are merged in periodically: + +```bash +git remote add upstream https://github.com/GLips/Figma-Context-MCP.git +git fetch upstream && git merge upstream/main +``` + +Install for an MCP client: `npx -y @blocksuser/figma-mcp --stdio`. Issues with the fork go to [BlocksOrg/Figma-Context-MCP](https://github.com/BlocksOrg/Figma-Context-MCP/issues); upstream's docs at [framelink.ai](https://www.framelink.ai/docs) still describe the tools. + Give [Cursor](https://cursor.sh/) and other AI-powered coding tools access to your Figma files with this [Model Context Protocol](https://modelcontextprotocol.io/introduction) server. When Cursor has access to Figma design data, it's **way** better at one-shotting designs accurately than alternative approaches like pasting screenshots. @@ -52,7 +69,7 @@ Reducing the amount of context provided to the model helps make the AI more accu Many code editors and other AI clients use a configuration file to manage MCP servers. -The `figma-developer-mcp` server can be configured by adding the following to your configuration file. +The `@blocksuser/figma-mcp` server can be configured by adding the following to your configuration file. > NOTE: You will need to create a Figma access token to use this server. Instructions on how to create a Figma API access token can be found [here](https://help.figma.com/hc/en-us/articles/8085703771159-Manage-personal-access-tokens). @@ -63,7 +80,7 @@ The `figma-developer-mcp` server can be configured by adding the following to yo "mcpServers": { "Framelink MCP for Figma": { "command": "npx", - "args": ["-y", "figma-developer-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] + "args": ["-y", "@blocksuser/figma-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] } } } @@ -76,7 +93,7 @@ The `figma-developer-mcp` server can be configured by adding the following to yo "mcpServers": { "Framelink MCP for Figma": { "command": "cmd", - "args": ["/c", "npx", "-y", "figma-developer-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] + "args": ["/c", "npx", "-y", "@blocksuser/figma-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] } } } @@ -102,10 +119,6 @@ Why per request: Figma keeps **one live access token per app per user**, so when In stdio mode the server does not read a `.env` file from its working directory (an MCP client spawns it with an arbitrary cwd); pass `--env ` to load one explicitly. HTTP mode and the `fetch` subcommand still load `./.env`. -## Star History - -
Star History Chart - ## Learn More The Framelink MCP for Figma is simple but powerful. Get the most out of it by learning more at the [Framelink](https://framelink.ai?utm_source=github&utm_medium=referral&utm_campaign=readme) site. diff --git a/SECURITY.md b/SECURITY.md index 6c79a4a6..9c1cd94f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,7 +8,7 @@ Please report security vulnerabilities responsibly. ### How to Report -1. **GitHub Security Advisories**: [Report privately](https://github.com/GLips/Figma-Context-MCP/security/advisories/new) +1. **GitHub Security Advisories**: [Report privately](https://github.com/BlocksOrg/Figma-Context-MCP/security/advisories/new) 2. **Email**: Contact the maintainers directly ### Response Timeline @@ -20,8 +20,8 @@ Please report security vulnerabilities responsibly. ## Supported Versions | Version | Supported | -|---------|:---------:| -| Latest | ✅ | +| ------- | :-------: | +| Latest | ✅ | ## MCP Security Best Practices diff --git a/package.json b/package.json index 842216cb..472e4fa6 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { - "name": "figma-developer-mcp", + "name": "@blocksuser/figma-mcp", "version": "0.13.2", - "mcpName": "io.github.GLips/Figma-Context-MCP", - "description": "Give your coding agent access to your Figma data. Implement designs in any framework in one-shot.", + "mcpName": "io.github.BlocksOrg/Figma-Context-MCP", + "description": "Blocks fork of Framelink's Figma MCP server: hardened dependencies, no telemetry, per-request token resolution.", "type": "module", "main": "dist/index.js", "bin": { - "figma-developer-mcp": "dist/bin.js" + "figma-mcp": "dist/bin.js" }, "files": [ "dist", @@ -51,13 +51,17 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/GLips/Figma-Context-MCP.git" + "url": "git+https://github.com/BlocksOrg/Figma-Context-MCP.git" + }, + "homepage": "https://github.com/BlocksOrg/Figma-Context-MCP#readme", + "bugs": { + "url": "https://github.com/BlocksOrg/Figma-Context-MCP/issues" }, - "homepage": "https://www.framelink.ai", "keywords": [ "figma", "mcp", - "typescript" + "typescript", + "blocks" ], "author": "", "license": "MIT", diff --git a/server.json b/server.json index ed0269cd..3b1ed73e 100644 --- a/server.json +++ b/server.json @@ -1,16 +1,16 @@ { "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", - "name": "io.github.GLips/Figma-Context-MCP", - "description": "Give your coding agent access to your Figma data. Implement designs in any framework in one-shot.", + "name": "io.github.BlocksOrg/Figma-Context-MCP", + "description": "Blocks fork of Framelink's Figma MCP server: hardened dependencies, no telemetry, per-request token resolution.", "repository": { - "url": "https://github.com/GLips/Figma-Context-MCP", + "url": "https://github.com/BlocksOrg/Figma-Context-MCP", "source": "github" }, "version": "0.6.4", "packages": [ { "registryType": "npm", - "identifier": "figma-developer-mcp", + "identifier": "@blocksuser/figma-mcp", "version": "0.6.4", "transport": { "type": "stdio" diff --git a/src/bin.ts b/src/bin.ts index c666743c..6aafe9fc 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -6,7 +6,7 @@ import { startServer } from "./server.js"; import { fetchCommand } from "./commands/fetch.js"; const argv = cli({ - name: "figma-developer-mcp", + name: "figma-mcp", version: process.env.NPM_PACKAGE_VERSION ?? "unknown", flags: { figmaApiKey: { From 96cdaf21b6f99f554aac0cf84acda839aef42b59 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Thu, 19 Nov 2026 17:47:30 +0000 Subject: [PATCH 15/19] feat(tools): add read-only REST tools for parity with the official Figma MCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit whoami (GET /v1/me), get_figma_comments, get_figma_file_versions, get_figma_dev_resources and get_figma_components_and_styles, each a lean YAML projection of the Figma response (author handle instead of the user object, pinned node id, reply threading; empty/null fields dropped). They share one SimpleTool contract so registration is a loop, and all carry readOnlyHint. No write tools. 🤖 Generated with BLOCKS! --- README.md | 2 + src/mcp/index.ts | 14 ++ src/mcp/tools/get-figma-comments-tool.ts | 30 +++ .../get-figma-components-and-styles-tool.ts | 39 ++++ src/mcp/tools/get-figma-dev-resources-tool.ts | 30 +++ src/mcp/tools/get-figma-file-versions-tool.ts | 28 +++ src/mcp/tools/index.ts | 17 ++ src/mcp/tools/simple-tool.ts | 59 ++++++ src/mcp/tools/whoami-tool.ts | 17 ++ src/services/figma.ts | 36 +++- src/tests/rest-tools.test.ts | 196 ++++++++++++++++++ 11 files changed, 466 insertions(+), 2 deletions(-) create mode 100644 src/mcp/tools/get-figma-comments-tool.ts create mode 100644 src/mcp/tools/get-figma-components-and-styles-tool.ts create mode 100644 src/mcp/tools/get-figma-dev-resources-tool.ts create mode 100644 src/mcp/tools/get-figma-file-versions-tool.ts create mode 100644 src/mcp/tools/simple-tool.ts create mode 100644 src/mcp/tools/whoami-tool.ts create mode 100644 src/tests/rest-tools.test.ts diff --git a/README.md b/README.md index aa39c078..1fab5400 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ git remote add upstream https://github.com/GLips/Figma-Context-MCP.git git fetch upstream && git merge upstream/main ``` +The fork also adds five small read-only tools over the Figma REST API, next to upstream's `get_figma_data` and `download_figma_images`: `whoami`, `get_figma_comments`, `get_figma_file_versions`, `get_figma_dev_resources` and `get_figma_components_and_styles`. Each returns a lean YAML projection of the response; there are no write tools. + Install for an MCP client: `npx -y @blocksuser/figma-mcp --stdio`. Issues with the fork go to [BlocksOrg/Figma-Context-MCP](https://github.com/BlocksOrg/Figma-Context-MCP/issues); upstream's docs at [framelink.ai](https://www.framelink.ai/docs) still describe the tools. Give [Cursor](https://cursor.sh/) and other AI-powered coding tools access to your Figma files with this [Model Context Protocol](https://modelcontextprotocol.io/introduction) server. diff --git a/src/mcp/index.ts b/src/mcp/index.ts index 04162389..899defd9 100644 --- a/src/mcp/index.ts +++ b/src/mcp/index.ts @@ -7,6 +7,7 @@ import type { ToolExtra } from "./progress.js"; import { downloadFigmaImagesTool, getFigmaDataTool, + simpleTools, type DownloadImagesParams, type GetFigmaDataParams, } from "./tools/index.js"; @@ -78,6 +79,19 @@ function registerTools( downloadFigmaImagesTool.handler(params, figmaService, options.imageDir, extra), ); } + + for (const tool of simpleTools) { + server.registerTool( + tool.name, + { + title: tool.title, + description: tool.description, + inputSchema: tool.parametersSchema, + annotations: { readOnlyHint: true }, + }, + (params) => tool.handler(params, figmaService), + ); + } } export { createServer }; diff --git a/src/mcp/tools/get-figma-comments-tool.ts b/src/mcp/tools/get-figma-comments-tool.ts new file mode 100644 index 00000000..92b96bb4 --- /dev/null +++ b/src/mcp/tools/get-figma-comments-tool.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; +import { compact, fileKeyParam, runSimpleTool, type SimpleTool } from "./simple-tool.js"; + +const parametersSchema = z.object({ fileKey: fileKeyParam }); + +export const getFigmaCommentsTool: SimpleTool> = { + name: "get_figma_comments", + title: "Get Figma Comments", + description: + "List the comments on a Figma file: author, text, the node they are pinned to, and reply threading (parent_id). Resolved comments are marked.", + parametersSchema, + handler: ({ fileKey }, figmaService) => + runSimpleTool("get_figma_comments", async () => { + const { comments } = await figmaService.getComments(fileKey); + return { + comments: comments.map((comment) => + compact({ + id: comment.id, + parent_id: comment.parent_id, + // Only pinned comments carry a node; region-only pins have none. + node_id: "node_id" in comment.client_meta ? comment.client_meta.node_id : undefined, + author: comment.user.handle, + created_at: comment.created_at, + resolved: comment.resolved_at ? true : undefined, + message: comment.message, + }), + ), + }; + }), +}; diff --git a/src/mcp/tools/get-figma-components-and-styles-tool.ts b/src/mcp/tools/get-figma-components-and-styles-tool.ts new file mode 100644 index 00000000..7ee47e85 --- /dev/null +++ b/src/mcp/tools/get-figma-components-and-styles-tool.ts @@ -0,0 +1,39 @@ +import { z } from "zod"; +import { compact, fileKeyParam, runSimpleTool, type SimpleTool } from "./simple-tool.js"; + +const parametersSchema = z.object({ fileKey: fileKeyParam }); + +export const getFigmaComponentsAndStylesTool: SimpleTool> = { + name: "get_figma_components_and_styles", + title: "Get Figma Components and Styles", + description: + "List the components and styles a Figma file publishes to its team library: keys, names, node IDs and descriptions. Use it to map a design onto an existing design system before fetching nodes.", + parametersSchema, + handler: ({ fileKey }, figmaService) => + runSimpleTool("get_figma_components_and_styles", async () => { + const [components, styles] = await Promise.all([ + figmaService.getPublishedComponents(fileKey), + figmaService.getPublishedStyles(fileKey), + ]); + return { + components: components.meta.components.map((component) => + compact({ + key: component.key, + name: component.name, + node_id: component.node_id, + page: component.containing_frame?.pageName, + description: component.description, + }), + ), + styles: styles.meta.styles.map((style) => + compact({ + key: style.key, + name: style.name, + type: style.style_type, + node_id: style.node_id, + description: style.description, + }), + ), + }; + }), +}; diff --git a/src/mcp/tools/get-figma-dev-resources-tool.ts b/src/mcp/tools/get-figma-dev-resources-tool.ts new file mode 100644 index 00000000..ce5e32f7 --- /dev/null +++ b/src/mcp/tools/get-figma-dev-resources-tool.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; +import { fileKeyParam, nodeIdParam, runSimpleTool, type SimpleTool } from "./simple-tool.js"; + +const parametersSchema = z.object({ + fileKey: fileKeyParam, + nodeIds: z + .array(nodeIdParam) + .optional() + .describe("Restrict to these node IDs. Omit to list every dev resource in the file."), +}); + +export const getFigmaDevResourcesTool: SimpleTool> = { + name: "get_figma_dev_resources", + title: "Get Figma Dev Resources", + description: + "List the dev resources (links to code, docs, tickets) attached to nodes in a Figma file.", + parametersSchema, + handler: ({ fileKey, nodeIds }, figmaService) => + runSimpleTool("get_figma_dev_resources", async () => { + const { dev_resources } = await figmaService.getDevResources(fileKey, nodeIds); + return { + dev_resources: dev_resources.map(({ id, name, url, node_id }) => ({ + id, + node_id, + name, + url, + })), + }; + }), +}; diff --git a/src/mcp/tools/get-figma-file-versions-tool.ts b/src/mcp/tools/get-figma-file-versions-tool.ts new file mode 100644 index 00000000..33edbfe6 --- /dev/null +++ b/src/mcp/tools/get-figma-file-versions-tool.ts @@ -0,0 +1,28 @@ +import { z } from "zod"; +import { compact, fileKeyParam, runSimpleTool, type SimpleTool } from "./simple-tool.js"; + +const parametersSchema = z.object({ fileKey: fileKeyParam }); + +export const getFigmaFileVersionsTool: SimpleTool> = { + name: "get_figma_file_versions", + title: "Get Figma File Versions", + description: + "List a Figma file's version history (newest first): version id, when and by whom it was saved, and its label/description when it was named.", + parametersSchema, + handler: ({ fileKey }, figmaService) => + runSimpleTool("get_figma_file_versions", async () => { + const { versions, pagination } = await figmaService.getFileVersions(fileKey); + return compact({ + versions: versions.map((version) => + compact({ + id: version.id, + created_at: version.created_at, + author: version.user.handle, + label: version.label, + description: version.description, + }), + ), + has_more: pagination?.next_page ? true : undefined, + }); + }), +}; diff --git a/src/mcp/tools/index.ts b/src/mcp/tools/index.ts index a312b24a..f6719fc6 100644 --- a/src/mcp/tools/index.ts +++ b/src/mcp/tools/index.ts @@ -2,3 +2,20 @@ export { getFigmaDataTool } from "./get-figma-data-tool.js"; export { downloadFigmaImagesTool } from "./download-figma-images-tool.js"; export type { DownloadImagesParams } from "./download-figma-images-tool.js"; export type { GetFigmaDataParams } from "./get-figma-data-tool.js"; + +import { getFigmaCommentsTool } from "./get-figma-comments-tool.js"; +import { getFigmaComponentsAndStylesTool } from "./get-figma-components-and-styles-tool.js"; +import { getFigmaDevResourcesTool } from "./get-figma-dev-resources-tool.js"; +import { getFigmaFileVersionsTool } from "./get-figma-file-versions-tool.js"; +import type { SimpleTool } from "./simple-tool.js"; +import { whoamiTool } from "./whoami-tool.js"; + +/** Read-only REST tools with the uniform `SimpleTool` contract, mounted in a loop. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const simpleTools: ReadonlyArray> = [ + whoamiTool, + getFigmaCommentsTool, + getFigmaFileVersionsTool, + getFigmaDevResourcesTool, + getFigmaComponentsAndStylesTool, +]; diff --git a/src/mcp/tools/simple-tool.ts b/src/mcp/tools/simple-tool.ts new file mode 100644 index 00000000..06353a0b --- /dev/null +++ b/src/mcp/tools/simple-tool.ts @@ -0,0 +1,59 @@ +import { z } from "zod"; +import type { FigmaService } from "~/services/figma.js"; +import { Logger } from "~/utils/logger.js"; +import { dumpYaml } from "~/utils/yaml-dump.js"; + +/** + * The small read-only REST tools (whoami, comments, versions, dev resources, + * published components/styles) share one shape: a few parameters, one or two + * Figma calls, and a lean YAML projection of the response. Keeping them to + * this contract lets `registerTools` mount them in a loop and keeps each tool + * file to the part that is actually different — the projection. + */ +export type SimpleTool = { + name: string; + title: string; + description: string; + parametersSchema: z.ZodObject; + handler: (params: Params, figmaService: FigmaService) => Promise; +}; + +export type ToolResult = { + content: Array<{ type: "text"; text: string }>; + isError?: true; +}; + +export const fileKeyParam = z + .string() + .regex(/^[a-zA-Z0-9]+$/, "File key must be alphanumeric") + .describe("The key of the Figma file, found in a URL like figma.com/(file|design)//..."); + +/** Node IDs as the API spells them (`12:34`); the `-` URL spelling is accepted too. */ +export const nodeIdParam = z + .string() + .regex(/^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*$/, "Node ID must be like '1234:5678'") + .transform((id) => id.replace(/-/g, ":")); + +/** Run a projection, rendering the result as YAML or the failure as a tool error. */ +export async function runSimpleTool( + label: string, + project: () => Promise, +): Promise { + try { + const result = await project(); + return { content: [{ type: "text", text: dumpYaml(result) }] }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + Logger.error(`Error in ${label}:`, message); + return { isError: true, content: [{ type: "text", text: `${label} failed: ${message}` }] }; + } +} + +/** Drop `undefined`, `null` and empty-string values so the YAML carries only what is set. */ +export function compact>(record: T): Partial { + return Object.fromEntries( + Object.entries(record).filter( + ([, value]) => value !== undefined && value !== null && value !== "", + ), + ) as Partial; +} diff --git a/src/mcp/tools/whoami-tool.ts b/src/mcp/tools/whoami-tool.ts new file mode 100644 index 00000000..67df19ac --- /dev/null +++ b/src/mcp/tools/whoami-tool.ts @@ -0,0 +1,17 @@ +import { z } from "zod"; +import { compact, runSimpleTool, type SimpleTool } from "./simple-tool.js"; + +const parametersSchema = z.object({}); + +export const whoamiTool: SimpleTool> = { + name: "whoami", + title: "Who am I", + description: + "Identify the Figma account the server is authenticated as (id, handle, email). Use it to check which account's files are reachable before fetching.", + parametersSchema, + handler: (_params, figmaService) => + runSimpleTool("whoami", async () => { + const me = await figmaService.getMe(); + return compact({ id: me.id, handle: me.handle, email: me.email }); + }), +}; diff --git a/src/services/figma.ts b/src/services/figma.ts index 684a30a3..b976357a 100644 --- a/src/services/figma.ts +++ b/src/services/figma.ts @@ -1,8 +1,14 @@ import type { - GetImagesResponse, - GetFileResponse, + GetCommentsResponse, + GetDevResourcesResponse, + GetFileComponentsResponse, GetFileNodesResponse, + GetFileResponse, + GetFileStylesResponse, + GetFileVersionsResponse, GetImageFillsResponse, + GetImagesResponse, + GetMeResponse, Transform, } from "@figma/rest-api-spec"; import { downloadAndProcessImage, type ImageProcessingResult } from "~/utils/image-processing.js"; @@ -175,6 +181,32 @@ export class FigmaService { ); } + /** The account behind the current credential (`GET /v1/me`). */ + getMe(): Promise { + return this.request("/me"); + } + + getComments(fileKey: string): Promise { + return this.request(`/files/${fileKey}/comments`); + } + + getFileVersions(fileKey: string): Promise { + return this.request(`/files/${fileKey}/versions`); + } + + getDevResources(fileKey: string, nodeIds: string[] = []): Promise { + const query = nodeIds.length ? `?node_ids=${encodeURIComponent(nodeIds.join(","))}` : ""; + return this.request(`/files/${fileKey}/dev_resources${query}`); + } + + getPublishedComponents(fileKey: string): Promise { + return this.request(`/files/${fileKey}/components`); + } + + getPublishedStyles(fileKey: string): Promise { + return this.request(`/files/${fileKey}/styles`); + } + /** * Builds URL query parameters for SVG image requests. */ diff --git a/src/tests/rest-tools.test.ts b/src/tests/rest-tools.test.ts new file mode 100644 index 00000000..b5a022e5 --- /dev/null +++ b/src/tests/rest-tools.test.ts @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import yaml from "js-yaml"; +import { createServer } from "~/mcp/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; + +/** + * The small REST tools exist to hand the model a lean projection of Figma's + * verbose responses. These tests pin that projection end-to-end through the + * MCP layer with `fetch` mocked at the network boundary. + */ +const user = { id: "u1", handle: "ada", img_url: "https://img/ada.png" }; + +const responses: Record = { + "/v1/me": { ...user, email: "ada@example.com" }, + "/v1/files/abc/comments": { + comments: [ + { + id: "c1", + file_key: "abc", + client_meta: { node_id: "1:2", node_offset: { x: 0, y: 0 } }, + user, + created_at: "2026-01-01T00:00:00Z", + resolved_at: "2026-01-02T00:00:00Z", + message: "Make it pop", + order_id: "1", + reactions: [{ user, emoji: ":+1:", created_at: "2026-01-01T00:00:00Z" }], + }, + { + id: "c2", + parent_id: "c1", + file_key: "abc", + client_meta: { x: 1, y: 2 }, + user, + created_at: "2026-01-03T00:00:00Z", + resolved_at: null, + message: "Done", + order_id: null, + reactions: [], + }, + ], + }, + "/v1/files/abc/components": { + status: 200, + error: false, + meta: { + components: [ + { + key: "k1", + file_key: "abc", + node_id: "3:4", + name: "Button", + description: "", + created_at: "", + updated_at: "", + user, + containing_frame: { pageId: "0:1", pageName: "Components" }, + }, + ], + }, + }, + "/v1/files/abc/styles": { + status: 200, + error: false, + meta: { + styles: [ + { + key: "s1", + file_key: "abc", + node_id: "5:6", + style_type: "FILL", + name: "Brand/Primary", + description: "Main brand color", + created_at: "", + updated_at: "", + user, + }, + ], + }, + }, +}; + +describe("read-only REST tools", () => { + let client: Client; + let server: McpServer; + let fetchMock: ReturnType; + + beforeEach(async () => { + fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const path = new URL(String(input)).pathname; + const body = responses[path]; + return body ? Response.json(body) : new Response("not found", { status: 404 }); + }); + vi.stubGlobal("fetch", fetchMock); + + server = createServer( + { figmaApiKey: "test-key", figmaOAuthToken: "", useOAuth: false }, + { transport: "stdio" }, + ); + client = new Client({ name: "rest-tools-test", version: "1.0.0" }); + const [clientT, serverT] = InMemoryTransport.createLinkedPair(); + await Promise.all([client.connect(clientT), server.connect(serverT)]); + }); + + afterEach(async () => { + await client.close(); + await server.close(); + vi.unstubAllGlobals(); + }); + + async function call(name: string, args: Record = {}) { + const result = await client.request( + { method: "tools/call", params: { name, arguments: args } }, + CallToolResultSchema, + ); + const first = result.content[0]; + const text = first?.type === "text" ? first.text : ""; + // Successful results are YAML dumped with JSON_SCHEMA (timestamps stay strings). + const data = result.isError ? undefined : yaml.load(text, { schema: yaml.JSON_SCHEMA }); + return { isError: result.isError, text, data: data as Record }; + } + + it("registers the five tools as read-only", async () => { + const { tools } = await client.listTools(); + const byName = Object.fromEntries(tools.map((t) => [t.name, t])); + for (const name of [ + "whoami", + "get_figma_comments", + "get_figma_file_versions", + "get_figma_dev_resources", + "get_figma_components_and_styles", + ]) { + expect(byName[name]?.annotations?.readOnlyHint).toBe(true); + } + }); + + it("whoami answers with the account identity only", async () => { + const { isError, data } = await call("whoami"); + + expect(isError).toBeUndefined(); + expect(data).toEqual({ id: "u1", handle: "ada", email: "ada@example.com" }); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ headers: { "X-Figma-Token": "test-key" } }); + }); + + it("projects comments to author, pin, threading and text", async () => { + const { data } = await call("get_figma_comments", { fileKey: "abc" }); + + expect(data).toEqual({ + comments: [ + { + id: "c1", + node_id: "1:2", + author: "ada", + created_at: "2026-01-01T00:00:00Z", + resolved: true, + message: "Make it pop", + }, + { + id: "c2", + parent_id: "c1", + author: "ada", + created_at: "2026-01-03T00:00:00Z", + message: "Done", + }, + ], + }); + }); + + it("merges published components and styles from both endpoints", async () => { + const { data } = await call("get_figma_components_and_styles", { fileKey: "abc" }); + + expect(data).toEqual({ + components: [{ key: "k1", name: "Button", node_id: "3:4", page: "Components" }], + styles: [ + { + key: "s1", + name: "Brand/Primary", + type: "FILL", + node_id: "5:6", + description: "Main brand color", + }, + ], + }); + const paths = fetchMock.mock.calls.map(([input]) => new URL(String(input)).pathname).sort(); + expect(paths).toEqual(["/v1/files/abc/components", "/v1/files/abc/styles"]); + }); + + it("returns a tool error, not a crash, when Figma rejects the request", async () => { + const { isError, text } = await call("get_figma_file_versions", { fileKey: "nope" }); + + expect(isError).toBe(true); + expect(text).toContain("get_figma_file_versions failed"); + }); +}); From 77aaf1de6e3aca6bea45c952bf2445414017180f Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Tue, 24 Nov 2026 17:14:50 +0000 Subject: [PATCH 16/19] ci: publish to npm with a manual workflow like mcp-linear (drop release-please) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `publish.yml` (workflow_dispatch, bump = patch|minor|major) type-checks, tests, builds, bumps package.json + server.json, commits and tags `vX.Y.Z`, creates the GitHub Release with generated notes and runs `pnpm publish --access public` with the org `NPM_TOKEN` secret — the same one-button flow BlocksOrg/mcp-linear uses. Release-please config, the OIDC trusted-publishing job and the MCP-registry publish step are removed; CLAUDE.md, CONTRIBUTING.md and the /release command describe the new flow. 🤖 Generated with BLOCKS! --- .claude/commands/release.md | 57 ++++++++---------------- .github/workflows/publish.yml | 84 +++++++++++++++++++++++++++++++++++ .github/workflows/release.yml | 75 ------------------------------- .release-please-manifest.json | 3 -- CLAUDE.md | 4 +- CONTRIBUTING.md | 12 ++--- release-please-config.json | 10 ----- 7 files changed, 111 insertions(+), 134 deletions(-) create mode 100644 .github/workflows/publish.yml delete mode 100644 .github/workflows/release.yml delete mode 100644 .release-please-manifest.json delete mode 100644 release-please-config.json diff --git a/.claude/commands/release.md b/.claude/commands/release.md index 66c3c244..1700a592 100644 --- a/.claude/commands/release.md +++ b/.claude/commands/release.md @@ -1,47 +1,28 @@ # Release -Review and publish a new release. +Publish a new `@blocksuser/figma-mcp` release to npm. ## Steps -1. **Check for a release-please PR:** - Run `gh pr list --repo BlocksOrg/Figma-Context-MCP --label "autorelease: pending" --json number,title,url` to find the open release PR. +1. **Decide the bump** from what landed on `main` since the last tag: + `git log $(git describe --tags --abbrev=0)..origin/main --oneline` (or + `gh release view --repo BlocksOrg/Figma-Context-MCP` for the previous release). Conventional + prefixes map to the bump: `fix:` → patch, `feat:` → minor, breaking change → major. - If no release PR exists, inform the user: "No pending release PR. Release-please creates one automatically when conventional commits (`fix:`, `feat:`) land on `main`." +2. **Confirm with the user** via AskUserQuestion: "Run the Publish workflow with bump `` + (v → v)?" Never dispatch without confirmation — it publishes to the public + registry and cannot be unpublished after 72 h. -2. **Show what's in the release:** - Run `gh pr view --json body` to display the pending changelog and version bump. Summarize: +3. **Dispatch the workflow:** + `gh workflow run publish.yml --repo BlocksOrg/Figma-Context-MCP -f version=` + then `gh run list --repo BlocksOrg/Figma-Context-MCP --workflow publish.yml --limit 1` and + `gh run watch `. The job type-checks, tests, builds, bumps `package.json` + `server.json`, + pushes `chore: release vX.Y.Z` + tag, creates the GitHub Release (generated notes) and runs + `pnpm publish --access public` with the `NPM_TOKEN` secret. - - New version number - - Number of features, fixes, and other changes - - List of included commits +4. **Verify:** `npm view @blocksuser/figma-mcp version` shows the new version and + `gh release view vX.Y.Z --repo BlocksOrg/Figma-Context-MCP` exists. -3. **Ask for confirmation:** - Use AskUserQuestion: "Merge this release PR to publish v to npm?" - - - **Merge and publish** — Proceed with merge - - **Review diff first** — Show `gh pr diff ` - - **Cancel** — Stop without merging - -4. **Merge the release PR:** - Run `gh pr merge --rebase --repo BlocksOrg/Figma-Context-MCP` (or merge via the GitHub UI). - - **Use rebase, not squash.** Feature PRs are squash-merged (so each conventional-commit title, - with its `(#NNN)`, feeds the changelog), but the release PR is the single `chore(main): release -X.Y.Z` commit release-please authored. Rebase replays it onto `main` verbatim — bot authorship, - clean subject, no `(#NNN)`. Squash would rewrite all three and diverge from every prior release - (check `git log` for `chore(main): release` commits — they're all single-parent, bot-authored, - no PR suffix). Merging through the UI does the same thing. - -5. **Verify:** - Run `gh run list --repo BlocksOrg/Figma-Context-MCP --limit 1` to confirm the Release workflow triggered. - Report the workflow run URL so the user can monitor npm publish. - - The Release workflow also bumps `server.json` and publishes to npm (OIDC) and the MCP registry — - all hands-off. No manual steps beyond merging the PR. - -6. **Write the curated release notes:** - Once the workflow has published the GitHub Release (the tag exists), run `/release-notes` to - replace the mechanical, auto-generated Release body with brand-voice highlights. release-please - only produces a terse commit-title list; `/release-notes` turns it into something worth reading. - `CHANGELOG.md` is left as-is — release-please owns it. +5. **Downstream:** the sandbox images install the package from `dependencies/*.package.json` in + BlocksOrg/agents (`"@blocksuser/figma-mcp": "^X.Y"`) — a major bump needs that range widened + and a new agents revision deployed; minor/patch are picked up on the next image build. diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..6f6520fb --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,84 @@ +name: Publish to npm + +# Same shape as BlocksOrg/mcp-linear's publish workflow: a maintainer picks the +# bump, the job bumps package.json (+ server.json), tags, creates the GitHub +# Release and publishes to npm with the org's NPM_TOKEN. No release-please, no +# OIDC trusted publishing — one secret, one button, like the Linear server. +on: + workflow_dispatch: + inputs: + version: + description: 'Version bump type (patch, minor, major)' + required: true + default: 'patch' + type: choice + options: + - patch + - minor + - major + +jobs: + publish: + if: ${{ github.repository_owner == 'BlocksOrg' }} + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: pnpm/action-setup@v4 + with: + version: 10.10.0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: 'https://registry.npmjs.org/' + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Type check + run: pnpm type-check + + - name: Run tests + run: pnpm test + + - name: Build + run: pnpm build + + - name: Version bump + id: version + run: | + git config --global user.name 'GitHub Action' + git config --global user.email 'action@github.com' + npm version ${{ github.event.inputs.version }} --no-git-tag-version + VERSION=$(node -p "require('./package.json').version") + # server.json (MCP registry manifest) carries the same version twice; keep it in step. + jq --arg v "$VERSION" '.version = $v | .packages[0].version = $v' server.json > server.tmp && mv server.tmp server.json + git add package.json server.json + git commit -m "chore: release v${VERSION} [skip ci]" + git tag "v${VERSION}" + echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" + + - name: Push changes + run: git push --follow-tags + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ steps.version.outputs.VERSION }} + generate_release_notes: true + + # --access public: scoped packages default to restricted on first publish. + # --no-git-checks: the bump commit was just pushed; pnpm's branch/clean + # checks are not meaningful on a CI checkout. + - name: Publish to npm + run: pnpm publish --no-git-checks --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 762400ca..00000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: Release - -on: - push: - branches: - - main - -permissions: - contents: write - pull-requests: write - id-token: write # Required for npm OIDC trusted publishing - -jobs: - release-please: - if: ${{ github.repository_owner == 'BlocksOrg' }} - runs-on: ubuntu-latest - env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true - steps: - - uses: googleapis/release-please-action@v4 - id: release - - - uses: actions/checkout@v4 - if: ${{ steps.release.outputs.release_created }} - - - uses: pnpm/action-setup@v4 - with: - version: 10.10.0 - if: ${{ steps.release.outputs.release_created }} - - - uses: actions/setup-node@v4 - with: - node-version: 24 - registry-url: "https://registry.npmjs.org" - if: ${{ steps.release.outputs.release_created }} - - - name: Install dependencies - run: pnpm install - if: ${{ steps.release.outputs.release_created }} - - - name: Type check - run: pnpm type-check - if: ${{ steps.release.outputs.release_created }} - - - name: Build - run: pnpm build - if: ${{ steps.release.outputs.release_created }} - - # --access public: scoped packages default to restricted on first publish. - - name: Publish to npm - run: pnpm publish --no-git-checks --access public - env: - NODE_ENV: production - if: ${{ steps.release.outputs.release_created }} - - - name: Update server.json version - run: | - VERSION="${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }}" - jq --arg v "$VERSION" '.version = $v | .packages[0].version = $v' server.json > server.tmp && mv server.tmp server.json - if: ${{ steps.release.outputs.release_created }} - - # The registry listing is a nice-to-have for the fork (Blocks consumes the - # npm package directly); never let it fail a release that already published. - - name: Install mcp-publisher - run: | - curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_linux_amd64.tar.gz" | tar xz mcp-publisher - if: ${{ steps.release.outputs.release_created }} - continue-on-error: true - - - name: Publish to MCP Registry - run: | - ./mcp-publisher login github-oidc - ./mcp-publisher publish - if: ${{ steps.release.outputs.release_created }} - continue-on-error: true diff --git a/.release-please-manifest.json b/.release-please-manifest.json deleted file mode 100644 index 794cd279..00000000 --- a/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "0.13.2" -} diff --git a/CLAUDE.md b/CLAUDE.md index 04ed2012..6131822f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,11 +32,11 @@ pnpm test -- --testNamePattern="pattern" ### Releasing -Releases are automated via [release-please](https://github.com/googleapis/release-please). On merge to `main`, release-please reads conventional commit prefixes (`fix:`, `feat:`, `feat!:`) and maintains a release PR. Merging the release PR publishes to npm via OIDC trusted publishing. +Releases are manual and mirror BlocksOrg/mcp-linear: run the **Publish to npm** workflow (`.github/workflows/publish.yml`, Actions tab → "Run workflow", or `gh workflow run publish.yml -f version=patch|minor|major`). It type-checks, tests, builds, bumps `package.json` + `server.json`, commits `chore: release vX.Y.Z`, tags `vX.Y.Z`, creates the GitHub Release with generated notes, and runs `pnpm publish --access public` to `@blocksuser/figma-mcp` using the `NPM_TOKEN` repository secret (the same org token mcp-linear publishes with). Nothing publishes on merge to `main`. ### PR Title Convention -PRs are squash-merged, so the PR title becomes the commit message that release-please parses. Always use [Conventional Commit](https://www.conventionalcommits.org/) prefixes in PR titles. +PRs are squash-merged, so the PR title becomes the commit message on `main` and feeds the generated release notes. Use [Conventional Commit](https://www.conventionalcommits.org/) prefixes in PR titles; pick the bump type (`fix:` → patch, `feat:` → minor, breaking → major) when you run the publish workflow. ## Architecture diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a6808f5e..1face271 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -148,14 +148,14 @@ src/ ### Commit Messages -This project uses [Conventional Commits](https://www.conventionalcommits.org/) to automate versioning and changelog generation. The maintainer applies the correct prefix when squash-merging your PR — you don't need to worry about this in your individual commits. +This project uses [Conventional Commits](https://www.conventionalcommits.org/). The maintainer applies the correct prefix when squash-merging your PR — you don't need to worry about this in your individual commits. -For reference, these prefixes determine version bumps: +Releases are cut by hand with the **Publish to npm** workflow (see `CLAUDE.md` → Releasing); the prefixes tell the maintainer which bump to pick: -- `fix: ` — patch release (0.6.4 → 0.6.5) -- `feat: ` — minor release (0.6.4 → 0.7.0) -- `feat!: ` or `BREAKING CHANGE:` footer — major release (0.6.4 → 1.0.0) -- `chore:`, `docs:`, `test:`, `refactor:` — no release triggered +- `fix: ` — patch release (0.14.0 → 0.14.1) +- `feat: ` — minor release (0.14.0 → 0.15.0) +- `feat!: ` or `BREAKING CHANGE:` footer — major release (0.14.0 → 1.0.0) +- `chore:`, `docs:`, `test:`, `refactor:` — no release needed on their own ### What We're Looking For diff --git a/release-please-config.json b/release-please-config.json deleted file mode 100644 index 69437f50..00000000 --- a/release-please-config.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "packages": { - ".": { - "release-type": "node", - "changelog-path": "CHANGELOG.md", - "bump-minor-pre-major": true, - "include-component-in-tag": false - } - } -} From e39e60d578b4207af731715e7d11120a59230674 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Tue, 24 Nov 2026 17:33:26 +0000 Subject: [PATCH 17/19] chore: add scripts/publish.sh, mcp-linear's local publish script on pnpm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same arguments and behaviour as BlocksOrg/mcp-linear/scripts/publish.sh (` [--rc]`, rc dist-tag, rc-number bump when already an rc), plus `--dry-run` and the server.json version sync. Force-added: the upstream .gitignore ignores scripts/ wholesale while tracking the files in it. 🤖 Generated with BLOCKS! --- .claude/commands/release.md | 2 +- CLAUDE.md | 7 ++- scripts/publish.sh | 117 ++++++++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 2 deletions(-) create mode 100755 scripts/publish.sh diff --git a/.claude/commands/release.md b/.claude/commands/release.md index 1700a592..f7ba5ae8 100644 --- a/.claude/commands/release.md +++ b/.claude/commands/release.md @@ -13,7 +13,7 @@ Publish a new `@blocksuser/figma-mcp` release to npm. (v → v)?" Never dispatch without confirmation — it publishes to the public registry and cannot be unpublished after 72 h. -3. **Dispatch the workflow:** +3. **Publish** — either run `./scripts/publish.sh ` locally (then `git commit -am "chore: release vX.Y.Z" && git tag vX.Y.Z && git push --follow-tags && gh release create vX.Y.Z --generate-notes`), or dispatch the workflow: `gh workflow run publish.yml --repo BlocksOrg/Figma-Context-MCP -f version=` then `gh run list --repo BlocksOrg/Figma-Context-MCP --workflow publish.yml --limit 1` and `gh run watch `. The job type-checks, tests, builds, bumps `package.json` + `server.json`, diff --git a/CLAUDE.md b/CLAUDE.md index 6131822f..d283d4ba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,12 @@ pnpm test -- --testNamePattern="pattern" ### Releasing -Releases are manual and mirror BlocksOrg/mcp-linear: run the **Publish to npm** workflow (`.github/workflows/publish.yml`, Actions tab → "Run workflow", or `gh workflow run publish.yml -f version=patch|minor|major`). It type-checks, tests, builds, bumps `package.json` + `server.json`, commits `chore: release vX.Y.Z`, tags `vX.Y.Z`, creates the GitHub Release with generated notes, and runs `pnpm publish --access public` to `@blocksuser/figma-mcp` using the `NPM_TOKEN` repository secret (the same org token mcp-linear publishes with). Nothing publishes on merge to `main`. +Releases are manual and mirror BlocksOrg/mcp-linear. Two equivalent paths: + +- **Locally:** `./scripts/publish.sh [--rc] [--dry-run]` (the same script mcp-linear ships) — bumps `package.json` + `server.json`, `pnpm build`, `pnpm publish --access public --tag latest|rc` with your own npm login. Then commit the bump and tag it: `git commit -am "chore: release vX.Y.Z" && git tag vX.Y.Z && git push --follow-tags`. +- **From GitHub:** the **Publish to npm** workflow (`.github/workflows/publish.yml`, Actions tab → "Run workflow", or `gh workflow run publish.yml -f version=patch|minor|major`) does the same plus the commit, tag and GitHub Release, using the `NPM_TOKEN` repository secret (the same org token mcp-linear publishes with). + +Nothing publishes on merge to `main`. ### PR Title Convention diff --git a/scripts/publish.sh b/scripts/publish.sh new file mode 100755 index 00000000..d72a8d99 --- /dev/null +++ b/scripts/publish.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Publish @blocksuser/figma-mcp to npm — the same script BlocksOrg/mcp-linear +# ships as scripts/publish.sh, on pnpm. Run it from a clean checkout of the +# commit you want to ship, logged in to npm as a member of the @blocksuser org +# (`npm login`, or NODE_AUTH_TOKEN / an ~/.npmrc authToken). +# Usage: ./scripts/publish.sh [--rc] [--dry-run] + +PACKAGE="@blocksuser/figma-mcp" + +usage() { + cat < [--rc] [--dry-run] + $0 --help + +Arguments: + patch|minor|major Which part of the version to bump (required) + +Options: + --rc Publish a release candidate (x.y.z-rc.N) under the "rc" dist-tag + instead of "latest". If the current version is already an rc, + only the rc number is bumped (1.2.3-rc.0 -> 1.2.3-rc.1). + --dry-run Bump and build, but pass --dry-run to pnpm publish (nothing is + uploaded; package.json / server.json are still bumped locally). + -h, --help Show this help + +Examples: + $0 patch 1.2.3 -> 1.2.4 (latest) + $0 minor --rc 1.2.3 -> 1.3.0-rc.0 (rc) + $0 minor --rc 1.3.0-rc.0 -> 1.3.0-rc.1 (rc) + $0 minor 1.3.0-rc.1 -> 1.3.0 (latest) + +After a real publish, commit the bump and tag it: + git add package.json server.json && git commit -m "chore: release v" && git tag v && git push --follow-tags +USAGE +} + +BUMP="" +RC=false +DRY_RUN=false + +for arg in "$@"; do + case "$arg" in + -h|--help) + usage + exit 0 + ;; + --rc) + RC=true + ;; + --dry-run) + DRY_RUN=true + ;; + patch|minor|major) + if [[ -n "$BUMP" ]]; then + echo "Error: bump type given more than once ('$BUMP' and '$arg')" >&2 + exit 1 + fi + BUMP="$arg" + ;; + *) + echo "Error: unknown argument '$arg'" >&2 + usage >&2 + exit 1 + ;; + esac +done + +if [[ -z "$BUMP" ]]; then + echo "Error: bump type is required (patch, minor or major)" >&2 + usage >&2 + exit 1 +fi + +cd "$(dirname "$0")/.." + +CURRENT=$(node -p "require('./package.json').version") +TAG="latest" + +if $RC; then + TAG="rc" + if [[ "$CURRENT" == *-rc.* ]]; then + echo "Bumping rc number ($CURRENT is already an rc; '$BUMP' not applied)..." + npm version prerelease --preid rc --no-git-tag-version + else + echo "Bumping version (pre$BUMP, rc)..." + npm version "pre$BUMP" --preid rc --no-git-tag-version + fi +else + echo "Bumping version ($BUMP)..." + npm version "$BUMP" --no-git-tag-version +fi + +VERSION=$(node -p "require('./package.json').version") + +# server.json (the MCP registry manifest) carries the version twice; keep it in step. +jq --arg v "$VERSION" '.version = $v | .packages[0].version = $v' server.json > server.json.tmp && mv server.json.tmp server.json + +echo "Publishing $PACKAGE@$VERSION (tag: $TAG)..." + +pnpm build + +# --no-git-checks: the bump is intentionally uncommitted at this point (commit + tag after). +PUBLISH_ARGS=(--access public --tag "$TAG" --no-git-checks) +if $DRY_RUN; then + PUBLISH_ARGS+=(--dry-run) +fi +pnpm publish "${PUBLISH_ARGS[@]}" + +if $DRY_RUN; then + echo "Dry run complete for $PACKAGE@$VERSION (tag: $TAG) — nothing uploaded. package.json / server.json were bumped locally; git checkout them to undo." +else + echo "Published $PACKAGE@$VERSION (tag: $TAG)" +fi From a67846efb65749197b58c29b0d1719a94938e54f Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Tue, 24 Nov 2026 17:48:50 +0000 Subject: [PATCH 18/19] fix(publish): fall back to npx pnpm and install deps when pnpm is not on PATH MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mcp-linear is an npm project, so its publish.sh never needed pnpm; this fork is pnpm-only (lockfile, packageManager pin, overrides, prepack). The script now uses the pinned pnpm through npx when none is installed and runs install when node_modules is missing, so a machine with only Node + npm can publish. 🤖 Generated with BLOCKS! --- scripts/publish.sh | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/scripts/publish.sh b/scripts/publish.sh index d72a8d99..fbe9bf9c 100755 --- a/scripts/publish.sh +++ b/scripts/publish.sh @@ -77,6 +77,21 @@ fi cd "$(dirname "$0")/.." +# This repo is a pnpm project (pnpm-lock.yaml, `packageManager` pin, pnpm.overrides, +# `prepack: pnpm build`), unlike mcp-linear's npm one. Use the pnpm on PATH, else the +# pinned version through npx so a machine with only Node + npm can still publish. +PNPM_VERSION=$(node -p "(require('./package.json').packageManager || 'pnpm@10').split('@')[1]") +if command -v pnpm >/dev/null 2>&1; then + PNPM=(pnpm) +else + echo "pnpm not found on PATH; using npx pnpm@$PNPM_VERSION" + PNPM=(npx -y "pnpm@$PNPM_VERSION") +fi +if [[ ! -d node_modules ]]; then + echo "Installing dependencies..." + "${PNPM[@]}" install --frozen-lockfile +fi + CURRENT=$(node -p "require('./package.json').version") TAG="latest" @@ -101,14 +116,14 @@ jq --arg v "$VERSION" '.version = $v | .packages[0].version = $v' server.json > echo "Publishing $PACKAGE@$VERSION (tag: $TAG)..." -pnpm build +"${PNPM[@]}" build # --no-git-checks: the bump is intentionally uncommitted at this point (commit + tag after). PUBLISH_ARGS=(--access public --tag "$TAG" --no-git-checks) if $DRY_RUN; then PUBLISH_ARGS+=(--dry-run) fi -pnpm publish "${PUBLISH_ARGS[@]}" +"${PNPM[@]}" publish "${PUBLISH_ARGS[@]}" if $DRY_RUN; then echo "Dry run complete for $PACKAGE@$VERSION (tag: $TAG) — nothing uploaded. package.json / server.json were bumped locally; git checkout them to undo." From e9ee9f1b5073cab80768b64079a4bcaeb39d15c3 Mon Sep 17 00:00:00 2001 From: Blocks Task Runner Date: Tue, 24 Nov 2026 17:55:05 +0000 Subject: [PATCH 19/19] chore: rename the package to @blocksuser/mcp-figma (matches @blocksuser/mcp-linear) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Published as @blocksuser/mcp-figma@0.14.0-rc.2; package.json / server.json now carry that name and version, and every reference (bin, README, publish script, issue template, tests) follows. 🤖 Generated with BLOCKS! --- .claude/commands/release.md | 6 +++--- .github/ISSUE_TEMPLATE/bug_report.md | 8 ++++---- README.md | 14 +++++++------- package.json | 6 +++--- scripts/publish.sh | 4 ++-- server.json | 6 +++--- src/bin.ts | 2 +- src/extractors/README.md | 4 ++-- src/tests/config.test.ts | 2 +- src/tests/credential-resolution.test.ts | 2 +- 10 files changed, 27 insertions(+), 27 deletions(-) diff --git a/.claude/commands/release.md b/.claude/commands/release.md index f7ba5ae8..6f10e3d7 100644 --- a/.claude/commands/release.md +++ b/.claude/commands/release.md @@ -1,6 +1,6 @@ # Release -Publish a new `@blocksuser/figma-mcp` release to npm. +Publish a new `@blocksuser/mcp-figma` release to npm. ## Steps @@ -20,9 +20,9 @@ Publish a new `@blocksuser/figma-mcp` release to npm. pushes `chore: release vX.Y.Z` + tag, creates the GitHub Release (generated notes) and runs `pnpm publish --access public` with the `NPM_TOKEN` secret. -4. **Verify:** `npm view @blocksuser/figma-mcp version` shows the new version and +4. **Verify:** `npm view @blocksuser/mcp-figma version` shows the new version and `gh release view vX.Y.Z --repo BlocksOrg/Figma-Context-MCP` exists. 5. **Downstream:** the sandbox images install the package from `dependencies/*.package.json` in - BlocksOrg/agents (`"@blocksuser/figma-mcp": "^X.Y"`) — a major bump needs that range widened + BlocksOrg/agents (`"@blocksuser/mcp-figma": "^X.Y"`) — a major bump needs that range widened and a new agents revision deployed; minor/patch are picked up on the next image build. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 580b6fd1..80b77533 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -36,10 +36,10 @@ If applicable, add screenshots to help explain your problem. Often a screenshot Provide your MCP JSON configuration, if applicable. E.g. ``` - "@blocksuser/figma-mcp": { + "@blocksuser/mcp-figma": { "command": "npx", "args": [ - "@blocksuser/figma-mcp", + "@blocksuser/mcp-figma", "--figma-api-key=REDACTED", "--stdio" ] @@ -50,7 +50,7 @@ Provide your MCP JSON configuration, if applicable. E.g. If you're running the MCP locally on the command line, include all the logs for those like so: ``` -> npx @blocksuser/figma-mcp --figma-api-key=REDACTED +> npx @blocksuser/mcp-figma --figma-api-key=REDACTED Configuration: - FIGMA_API_KEY: ****8pXg (source: cli) @@ -68,7 +68,7 @@ If you're running the MCP in a code editor like Cursor, there are MCP-specific l ``` 2025-03-18 11:36:22.251 [info] pnpx: Handling CreateClient action 2025-03-18 11:36:22.251 [info] pnpx: getOrCreateClient for stdio server. process.platform: darwin isElectron: true -2025-03-18 11:36:22.251 [info] pnpx: Starting new stdio process with command: pnpx @blocksuser/figma-mcp --figma-api-key=REDACTED --stdio +2025-03-18 11:36:22.251 [info] pnpx: Starting new stdio process with command: pnpx @blocksuser/mcp-figma --figma-api-key=REDACTED --stdio 2025-03-18 11:36:23.987 [info] pnpx: Successfully connected to stdio server 2025-03-18 11:36:23.987 [info] pnpx: Storing stdio client 2025-03-18 11:36:23.988 [info] MCP: Handling ListOfferings action diff --git a/README.md b/README.md index 1fab5400..3599fe6e 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@

Framelink MCP for Figma

Give your coding agent access to your Figma data.
Implement designs in any framework in one-shot.

- - npm + + npm MIT License @@ -27,7 +27,7 @@ ## Blocks fork -This is the [Blocks](https://blocks.team) fork of [GLips/Figma-Context-MCP](https://github.com/GLips/Figma-Context-MCP) (Framelink MCP for Figma), published as [`@blocksuser/figma-mcp`](https://www.npmjs.com/package/@blocksuser/figma-mcp). Blocks runs this server inside agent sandboxes, which needs three things upstream does not provide: +This is the [Blocks](https://blocks.team) fork of [GLips/Figma-Context-MCP](https://github.com/GLips/Figma-Context-MCP) (Framelink MCP for Figma), published as [`@blocksuser/mcp-figma`](https://www.npmjs.com/package/@blocksuser/mcp-figma). Blocks runs this server inside agent sandboxes, which needs three things upstream does not provide: - **Hardened dependency tree.** `pnpm audit --prod --audit-level=high` is a CI gate (111 advisories at fork time, 0 now) and dependabot keeps it that way. A tombstone test keeps `child_process` out of `src/` (CVE-2025-53967 / CVE-2025-15061). - **No telemetry.** This fork sends no telemetry; the PostHog client and its opt-out variables are gone. @@ -42,7 +42,7 @@ git fetch upstream && git merge upstream/main The fork also adds five small read-only tools over the Figma REST API, next to upstream's `get_figma_data` and `download_figma_images`: `whoami`, `get_figma_comments`, `get_figma_file_versions`, `get_figma_dev_resources` and `get_figma_components_and_styles`. Each returns a lean YAML projection of the response; there are no write tools. -Install for an MCP client: `npx -y @blocksuser/figma-mcp --stdio`. Issues with the fork go to [BlocksOrg/Figma-Context-MCP](https://github.com/BlocksOrg/Figma-Context-MCP/issues); upstream's docs at [framelink.ai](https://www.framelink.ai/docs) still describe the tools. +Install for an MCP client: `npx -y @blocksuser/mcp-figma --stdio`. Issues with the fork go to [BlocksOrg/Figma-Context-MCP](https://github.com/BlocksOrg/Figma-Context-MCP/issues); upstream's docs at [framelink.ai](https://www.framelink.ai/docs) still describe the tools. Give [Cursor](https://cursor.sh/) and other AI-powered coding tools access to your Figma files with this [Model Context Protocol](https://modelcontextprotocol.io/introduction) server. @@ -71,7 +71,7 @@ Reducing the amount of context provided to the model helps make the AI more accu Many code editors and other AI clients use a configuration file to manage MCP servers. -The `@blocksuser/figma-mcp` server can be configured by adding the following to your configuration file. +The `@blocksuser/mcp-figma` server can be configured by adding the following to your configuration file. > NOTE: You will need to create a Figma access token to use this server. Instructions on how to create a Figma API access token can be found [here](https://help.figma.com/hc/en-us/articles/8085703771159-Manage-personal-access-tokens). @@ -82,7 +82,7 @@ The `@blocksuser/figma-mcp` server can be configured by adding the following to "mcpServers": { "Framelink MCP for Figma": { "command": "npx", - "args": ["-y", "@blocksuser/figma-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] + "args": ["-y", "@blocksuser/mcp-figma", "--figma-api-key=YOUR-KEY", "--stdio"] } } } @@ -95,7 +95,7 @@ The `@blocksuser/figma-mcp` server can be configured by adding the following to "mcpServers": { "Framelink MCP for Figma": { "command": "cmd", - "args": ["/c", "npx", "-y", "@blocksuser/figma-mcp", "--figma-api-key=YOUR-KEY", "--stdio"] + "args": ["/c", "npx", "-y", "@blocksuser/mcp-figma", "--figma-api-key=YOUR-KEY", "--stdio"] } } } diff --git a/package.json b/package.json index 472e4fa6..98cad4b2 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { - "name": "@blocksuser/figma-mcp", - "version": "0.13.2", + "name": "@blocksuser/mcp-figma", + "version": "0.14.0-rc.2", "mcpName": "io.github.BlocksOrg/Figma-Context-MCP", "description": "Blocks fork of Framelink's Figma MCP server: hardened dependencies, no telemetry, per-request token resolution.", "type": "module", "main": "dist/index.js", "bin": { - "figma-mcp": "dist/bin.js" + "mcp-figma": "dist/bin.js" }, "files": [ "dist", diff --git a/scripts/publish.sh b/scripts/publish.sh index fbe9bf9c..a4cfc0d8 100755 --- a/scripts/publish.sh +++ b/scripts/publish.sh @@ -1,13 +1,13 @@ #!/usr/bin/env bash set -euo pipefail -# Publish @blocksuser/figma-mcp to npm — the same script BlocksOrg/mcp-linear +# Publish @blocksuser/mcp-figma to npm — the same script BlocksOrg/mcp-linear # ships as scripts/publish.sh, on pnpm. Run it from a clean checkout of the # commit you want to ship, logged in to npm as a member of the @blocksuser org # (`npm login`, or NODE_AUTH_TOKEN / an ~/.npmrc authToken). # Usage: ./scripts/publish.sh [--rc] [--dry-run] -PACKAGE="@blocksuser/figma-mcp" +PACKAGE="@blocksuser/mcp-figma" usage() { cat < { diff --git a/src/tests/config.test.ts b/src/tests/config.test.ts index a04d72bd..d653f758 100644 --- a/src/tests/config.test.ts +++ b/src/tests/config.test.ts @@ -100,7 +100,7 @@ describe("loadEnvFile", () => { }); function projectWithDotEnv(): string { - const dir = mkdtempSync(join(tmpdir(), "figma-mcp-env-")); + const dir = mkdtempSync(join(tmpdir(), "mcp-figma-env-")); writeFileSync(join(dir, ".env"), "FIGMA_API_KEY=from-repo-dotenv\n"); return dir; } diff --git a/src/tests/credential-resolution.test.ts b/src/tests/credential-resolution.test.ts index 9bf810f4..b1dd4b3c 100644 --- a/src/tests/credential-resolution.test.ts +++ b/src/tests/credential-resolution.test.ts @@ -46,7 +46,7 @@ describe("per-request credential resolution", () => { } beforeEach(() => { - tokenFile = join(mkdtempSync(join(tmpdir(), "figma-mcp-token-")), ".oauth_token"); + tokenFile = join(mkdtempSync(join(tmpdir(), "mcp-figma-token-")), ".oauth_token"); vi.stubEnv("FIGMA_OAUTH_TOKEN_FILE", tokenFile); vi.stubEnv("FIGMA_OAUTH_TOKEN", "env-oauth-token"); vi.stubEnv("FIGMA_API_KEY", "env-api-key");