Skip to main content
Glama
fig-inspector-mcp

fig-inspector-mcp

by PixelDroid19
README.md
# fig-inspector

Offline **Figma (`.fig`) inspector**, **Dev-Mode HTML viewer**, **CLI**, and **Model Context Protocol (MCP) server** for developers and AI agents — powered by [`openfig-core`](https://github.com/OpenFig-org/openfig-core) with zero Figma API tokens, zero cloud calls, and zero WASM overhead.

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D20-green.svg)](https://nodejs.org)

---

## Key Capabilities

- **Full Component Instance Expansion**: expands `INSTANCE` → `SYMBOL` hierarchies up to 30+ levels deep, including nested design-system slots.
- **Scoped `symbolOverrides` & Cross-Variant Resolution**: steps down `guidPath` respecting `overrideKey`, `componentPropAssignments` (`TEXT_DATA`, `VISIBLE`, `OVERRIDDEN_SYMBOL_ID`), outer-over-inner precedence, and cross-variant layer matching within the same `ComponentSet`.
- **True 2×3 Affine Matrix Composition**: accurately computes local and view-relative bounding boxes across flipped (`m00: -1`, `m11: -1`) and rotated layers.
- **Flow & Prototype Extraction (`flows` / `fig_get_flows`)**: groups screens into ordered horizontal flow rows (`section` + `Y`, sorted by `X`), extracts UX notes/annotations, and exposes `prototypeInteractions` (`ON_CLICK` → destination / `BACK`).
- **Configurable Component Library Matching (`match-components` / `fig_match_components`)**: maps Figma components against any local component library directory configured via `--components-dir`, `FIG_COMPONENTS_DIR`, or MCP parameters — with zero hardcoded vendor paths.
- **Internal Helper Noise Filtering**: filters private/internal design-system helper components (prefixed with `⛔️`, `⛔`, `_`, `.`) by default in view summaries (`--include-internal` / `includeInternal: true` to include them).
- **Auto Layout, Spacing, Tokens & CSS**: extracts `mode`, `gap`, `padding`, `flex-grow`, `align-self`, parent margins, visual sibling gaps, `VARIABLE_SET`/`VARIABLE` collections, bound tokens (`variableConsumptionMap`, `paint.colorVar`), independent border weights, shadows/blurs, `clipsContent`, and mixed rich-text segments.
- **Assets & Vectors**: exports embedded `images/` (PNG/JPEG/WEBP/GIF) and standalone `<svg>` icons.
- **Bounded LRU Cache**: caches parsed `.fig` documents by `(filePath, mtimeMs)` (up to 8 entries) for sub-millisecond repeat queries without unbounded memory growth.

---

## Architecture

```text
src/
├── fig-geometry.mjs        # Affine 2x3 matrix math, colors, paints, layout, typography & SVG path extraction
├── fig-overrides.mjs       # Scoped guidPath stepping, cross-variant ComponentSet matching, prop & text overrides
├── fig-loader.mjs          # Bounded LRU .fig loader, parentMap, varsByKey, variantIndex, compound ID resolution
├── fig-inspector-core.mjs  # Tree inspection, spacing, views, summaries, distance measurement, override-aware search
├── fig-flows.mjs           # Horizontal flow row grouping, UX annotation extraction, prototypeInteractions
├── fig-catalog.mjs         # Configurable local component catalog scanner and Figma-to-library matcher
├── fig-export.mjs          # Markdown spec, CSS generator, image format/data-URI helpers, standalone SVG export
├── fig-reader.mjs          # Backwards-compatible barrel re-exporting all core functions
├── html-viewer.mjs         # Self-contained interactive Dev-Mode HTML visual inspector
├── cli.mjs                 # CLI entry point (fig-inspector)
├── mcp-server.mjs          # MCP stdio server entry point (fig-inspector-mcp)
└── index.mjs               # Public package entry point
```

---

## Installation

Requires **Node.js >= 20**.

```bash
git clone https://github.com/PixelDroid19/fig-inspector.git
cd fig-inspector
npm install
```

Optional global link (exposes `fig-inspector` and `fig-inspector-mcp` on your `PATH`):

```bash
npm link
```

---

## CLI Reference

```bash
fig-inspector <command> <file.fig> [args] [options]
# or directly:
node src/cli.mjs <command> <file.fig> [args] [options]
```

| Command | Description |
| --- | --- |
| `info <file.fig> [--json]` | Document stats (size, pages, nodes, components, tokens, images) |
| `pages <file.fig> [--json]` | List all pages (`CANVAS`) and sections |
| `views <file.fig> [--page <name\|id>] [--section <name>] [--query <text>] [--json]` | List screens/views with IDs, dimensions, coordinates, and preview texts |
| `flows <file.fig> [--page <name\|id>] [--section <name>] [--row-tolerance 250] [--json]` | Group views into ordered flow rows, UX notes, and prototype interactions |
| `summary <file.fig> <viewId> [--include-internal]` | Compact AI View Brief (texts, clean components, palette, tokens, image hashes) |
| `inspect <file.fig> <nodeId> [--depth 12] [--full] [--json] [--hidden]` | Inspect node subtree (supports compound instance IDs like `parent>child`) |
| `css <file.fig> <nodeId>` | Generate copyable CSS with design-token comments |
| `measure <file.fig> <nodeIdA> <nodeIdB>` | Measure exact pixel gaps and edge alignments between two nodes |
| `search <file.fig> <query> [--page <id>] [--type <TYPE>] [--text] [--limit 30]` | Search node names, text nodes, and overridden text in `symbolOverrides` |
| `components <file.fig> [--query <text>] [--limit 50] [--exclude-internal] [--json]` | List `SYMBOL` components and instance counts |
| `match-components <file.fig> [--components-dir <dir>] [--catalog-map <map.json>] [--view <id>] [--page <name>]` | Match Figma components against your configured local component library (with metadata, abbreviation expansion, and optional alias map) |
| `variables <file.fig> [--query <text>] [--collection <name>] [--limit 100]` | List design tokens (`VARIABLE_SET` & `VARIABLE`) with resolved aliases |
| `export-image <file.fig> <hash\|--all> [--out <file>] [--out-dir <dir>]` | Export embedded image(s) with auto-detected extensions |
| `export-svg <file.fig> <nodeId> [--out <file.svg>]` | Export a vector or icon container as standalone SVG |
| `viewer <file.fig> [--page <name\|id>] [--section <name>] [--view <nodeId>] [--max 25] [--depth 30] [--out viewer.html]` | Generate an interactive Dev-Mode HTML viewer |

### Examples

```bash
# Discover pages and ordered user flows
node src/cli.mjs pages ./design.fig
node src/cli.mjs flows ./design.fig --page "Handoff Dev"

# Get a compact AI brief for a screen
node src/cli.mjs summary ./design.fig 3064:160159

# Match Figma components against your local component library
node src/cli.mjs match-components ./design.fig --components-dir ./packages --view 3064:160159

# Search inside both raw text nodes and instance symbolOverrides
node src/cli.mjs search ./design.fig "Submit" --text

# Export icons and images
node src/cli.mjs export-svg ./design.fig 19:88 --out icon.svg
node src/cli.mjs export-image ./design.fig --all --out-dir ./assets

# Generate an interactive Dev-Mode HTML viewer
node src/cli.mjs viewer ./design.fig --page "Handoff Dev" --out viewer.html
```

---

## MCP Server (for AI Agents)

`fig-inspector` provides a stdio [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server (`src/mcp-server.mjs`) compatible with **Claude Desktop**, **Cursor**, **Windsurf**, **Claude Code**, **Antigravity**, and other MCP clients.

### Configuration

```json
{
  "mcpServers": {
    "fig-inspector": {
      "command": "node",
      "args": ["/absolute/path/to/fig-inspector/src/mcp-server.mjs"],
      "env": {
        "FIG_DEFAULT_FILE": "/optional/default/design.fig",
        "FIG_COMPONENTS_DIR": "/optional/path/to/your/component-library/packages",
        "FIG_CATALOG_MAP": "/optional/path/to/component-aliases.json"
      }
    }
  }
}
```

Both environment variables are optional:
- `FIG_DEFAULT_FILE` (or passing the `.fig` path as the first CLI argument) makes `filePath` optional on every tool call.
- `FIG_COMPONENTS_DIR` sets the default local component library directory for `fig_match_components`.

### MCP Tools (14)

| Tool | Purpose |
| --- | --- |
| `fig_info` | High-level file stats (pages, node counts, components, tokens, images) |
| `fig_list_pages` | List all pages and sections |
| `fig_list_views` | List screens/views with IDs, dimensions, coordinates, and preview texts |
| `fig_get_flows` | Group views into ordered flow rows, extract UX notes, and return `prototypeInteractions` |
| `fig_summarize_view` | Compact AI View Brief (texts in reading order, public components, colors + tokens, typography, image hashes) |
| `fig_inspect_view` | Detailed node tree in `markdown` or `json` with expanded instances, overrides, spacing, and styles |
| `fig_get_css` | Generate copyable CSS with design-token comments for any plain or compound node ID |
| `fig_measure_distance` | Exact horizontal/vertical pixel gaps and edge alignments between two nodes |
| `fig_search_nodes` | Search node names, text nodes, and overridden texts inside `symbolOverrides` |
| `fig_list_components` | List `SYMBOL` components and usage counts (internal helpers filtered by default) |
| `fig_match_components` | Match Figma components against a user-configured local component library directory |
| `fig_list_variables` | List design tokens (`VARIABLE_SET` / `VARIABLE`) with resolved collections and aliases |
| `fig_export_image` | Export an embedded image asset by `imageHash` to disk |
| `fig_export_svg` | Export a vector/icon node as standalone SVG (returned directly or saved to disk) |

---

## Programmatic JavaScript API

```js
import {
  loadFig,
  listPages,
  listViews,
  getFlows,
  summarizeView,
  inspectNode,
  matchFigmaComponents,
  nodeToCss,
  measureDistance,
  exportNodeSvg,
  generateHtmlViewer,
} from 'fig-inspector';

const fig = loadFig('./design.fig');
const flows = getFlows(fig, { pageName: 'Handoff Dev' });
const brief = summarizeView(fig, flows.flows[0].steps[0].id);
const matches = matchFigmaComponents(fig, {
  componentsDir: './packages',
  viewId: brief.id,
});
```

---

## Known Limitations

- The HTML viewer renders layout, fills, gradients, embedded bitmaps, shadows, independent borders, rich text, and SVG vector paths; complex Figma boolean blends, custom shaders, and runtime variable-mode switching (Light/Dark evaluation) are not simulated in the HTML preview.

---

## Testing

```bash
npm test
```

---

## License

[MIT](LICENSE) © 2026 PixelDroid