Skip to content

AI-native design editor. Open-source Figma alternative.

Address PR #94 review feedback

Anton A S774cf6b90a45
diff --git a/docs/mcp-codegen-plan.md b/docs/mcp-codegen-plan.md
deleted file mode 100644
index 1f5043ca4..000000000
--- a/docs/mcp-codegen-plan.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# MCP Codegen Pipeline — Implementation Plan
-
-## What's Done
-
-Branch `feat/mcp-codegen` (off `57eaf87`).
-
-### New Files
-
-- `packages/core/src/tools/codegen.ts` — 3 MCP tools:
- - `design_to_tokens` — extracts Figma variables as CSS/Tailwind/JSON, resolves aliases, handles multi-mode
- - `design_to_component_map` — analyzes document for screens, components (variants, props, instance counts), dependency overview
- - `get_codegen_prompt` — returns the codegen system prompt (lazy `await import('node:fs/promises')` to avoid Vite browser externalization error)
-- `packages/core/src/tools/prompts/codegen.md` — 5-step workflow prompt (~8KB):
- 1. Survey (page tree, components, variables, colors, typography, spacing)
- 2. Decompose (clusters, describe, get_jsx → component map)
- 3. Extract tokens (stack-aware: Tailwind → only semantic color CSS vars; CSS → full vars)
- 4. Generate code (bottom-up, one file per component, interactive states)
- 5. Verify (re-check against design)
-- `packages/core/src/tools/registry.ts` — 3 tools registered in `ALL_TOOLS` (now 91 total)
-- `docs/design-to-code-overview.md` — architecture overview
-
-### Design Decisions
-
-- **No MCP server instructions** — prompt delivered via `get_codegen_prompt` tool only (no 8KB overhead per request)
-- **Lazy fs import** — `await import('node:fs/promises')` inside function body to avoid Vite `Module "node:fs" has been externalized` crash in browser bundle
-- **Tailwind token strategy** — CSS custom properties only for semantic colors; Tailwind utilities for spacing/font/radius (avoids `--font-bold`, `--text-sm` conflicts with Tailwind v4 internals)
-- **No modifications to existing tools** — `get_jsx`, `describe`, `analyze_*` used as-is
-
-### Tested
-
-- MCP HTTP server (`http://127.0.0.1:3100/mcp`) — all 3 new tools callable
-- End-to-end with `lol.fig` (Movie Card, 390×1823, Inter font, dark theme, 164 nodes):
- - Full pipeline: survey → decompose → tokens → generate → verify
- - Generated 10 Vue 3 + Tailwind components + semantic color tokens
- - Visual test in just-bun dev server
-
-## What's Left
-
-### Phase 1 — Tailwind HTML Export (high value, low effort)
-
-Add `format` parameter to `get_jsx` tool:
-- `"openpencil"` (default) — current round-trip JSX
-- `"tailwind"` — HTML with Tailwind v4 utility classes
-
-The renderer already exists (`export-jsx.ts` → `collectTailwindClasses`), just not exposed through the tool params. One change in `read.ts`.
-
-This gives the LLM ready-to-use HTML with correct Tailwind classes directly from MCP — drastically reduces hallucination in generated code.
-
-### Phase 2 — Prompt Improvements
-
-- [ ] **Multi-file output format** — prompt should specify how to structure output when generating multiple files (fenced blocks with filenames)
-- [ ] **Framework adapters** — framework-specific sections in prompt (Vue `<script setup>` boilerplate, React hooks patterns, Svelte `$props()`)
-- [ ] **Image handling** — prompt guidance on when to use `export_svg` vs `export_png`, how to reference assets in generated code
-- [ ] **Responsive** — breakpoint detection from frame widths, responsive class generation
-
-### Phase 3 — Advanced Tools
-
-- [ ] **`design_to_html`** — full page HTML + Tailwind from a frame, using the existing tailwind renderer + semantic grouping. Essentially `get_jsx format=tailwind` but with smarter HTML tag selection (nav, header, main, section, article, button)
-- [ ] **`design_to_styles`** — extract complete stylesheet (CSS custom properties for all tokens, not just Figma variables but also inferred from analyze_colors/typography)
-- [ ] **`compare_design_code`** — given generated code and node ID, produce a diff of what's missing or wrong
-
-### Phase 4 — Integration
-
-- [ ] Pi skill for open-pencil MCP (`~/.pi/agent/skills/open-pencil/SKILL.md`) — DONE, needs testing with real workflow
-- [ ] VS Code extension integration — connect open-pencil MCP to the extension's AI chat
-- [ ] Batch mode — process multiple frames/pages in one go
-
-## Architecture
-
-```
-┌─────────────────────┐
-│ AI Agent (LLM) │
-│ │
-│ reads codegen.md │
-│ calls MCP tools │
-│ generates code │
-└─────────┬───────────┘
- │ MCP (HTTP SSE)
-┌─────────▼───────────┐
-│ MCP Server │
-│ :3100/mcp │
-├─────────────────────┤
-│ Survey tools │ get_page_tree, get_components,
-│ │ list_variables, list_collections,
-│ │ analyze_colors, analyze_typography,
-│ │ analyze_spacing
-├─────────────────────┤
-│ Decompose tools │ analyze_clusters, describe, get_jsx,
-│ │ design_to_component_map
-├─────────────────────┤
-│ Token tools │ design_to_tokens, list_variables
-├─────────────────────┤
-│ Codegen tools │ get_codegen_prompt, export_svg
-├─────────────────────┤
-│ Core │ .fig parser, scene graph, renderers
-└─────────────────────┘
-```
diff --git a/lol.fig b/lol.fig
deleted file mode 100644
index fe134ee69..000000000
Binary files a/lol.fig and /dev/null differ
diff --git a/packages/core/src/tools/codegen.ts b/packages/core/src/tools/codegen.ts
index 19a882339..fb7ea2a7d 100644
--- a/packages/core/src/tools/codegen.ts
+++ b/packages/core/src/tools/codegen.ts
@@ -4,7 +4,7 @@ import { defineTool } from './schema'
import type { Color } from '../types'
import type { FigmaAPI } from '../figma-api'
-import type { Variable, VariableCollection, VariableValue, SceneNode } from '../scene-graph'
+import type { SceneGraph, Variable, VariableCollection, VariableValue, SceneNode } from '../scene-graph'
function slugify(name: string): string {
return name
@@ -267,7 +267,7 @@ function collectInstanceCounts(
return counts
}
-function detectPropCandidates(node: SceneNode, graph: import('../scene-graph').SceneGraph): string[] {
+function detectPropCandidates(node: SceneNode, graph: SceneGraph): string[] {
const props: string[] = []
for (const childId of node.childIds) {
@@ -290,7 +290,7 @@ function detectPropCandidates(node: SceneNode, graph: import('../scene-graph').S
function detectVariants(
componentNode: SceneNode,
- graph: import('../scene-graph').SceneGraph
+ graph: SceneGraph
): string[] {
if (componentNode.type !== 'COMPONENT_SET') return []
@@ -422,25 +422,4 @@ export const designToComponentMap = defineTool({
}
})
-let _codegenPrompt: string | null = null
-export async function loadCodegenPrompt(): Promise<string> {
- if (_codegenPrompt) return _codegenPrompt
- const { readFile } = await import('node:fs/promises')
- const { dirname, join } = await import('node:path')
- const { fileURLToPath } = await import('node:url')
- const __dirname = dirname(fileURLToPath(import.meta.url))
- _codegenPrompt = await readFile(join(__dirname, 'prompts', 'codegen.md'), 'utf-8')
- return _codegenPrompt
-}
-
-export const getCodegenPrompt = defineTool({
- name: 'get_codegen_prompt',
- description:
- 'Get the design-to-code generation guidelines. Call this before generating frontend code from a Figma design to understand the recommended workflow and patterns.',
- params: {},
- execute: async () => {
- const prompt = await loadCodegenPrompt()
- return { prompt }
- }
-})
diff --git a/packages/core/src/tools/prompts/codegen.md b/packages/core/src/tools/prompts/codegen.md
index fb2a4b2ae..b2f7588a2 100644
--- a/packages/core/src/tools/prompts/codegen.md
+++ b/packages/core/src/tools/prompts/codegen.md
@@ -2,6 +2,8 @@
You convert Figma designs into production frontend code. You have full access to the design document through tools. Never guess — always read the actual design data.
+> Note: Auto-layout and visual property names match the JSX props in the render system. See `describe` tool output for semantic role and layout analysis of any node.
+
## Workflow
### Step 1 — Survey
diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.ts
index 4f40973f3..bd15c911c 100644
--- a/packages/core/src/tools/registry.ts
+++ b/packages/core/src/tools/registry.ts
@@ -36,7 +36,7 @@ import {
diffCreate, diffShow, evalCode
} from './analyze'
import { describe } from './describe'
-import { designToTokens, designToComponentMap, getCodegenPrompt } from './codegen'
+import { designToTokens, designToComponentMap } from './codegen'
import { calc } from './calc'
export const ALL_TOOLS: ToolDef[] = [
@@ -144,7 +144,6 @@ export const ALL_TOOLS: ToolDef[] = [
// Codegen
designToTokens,
designToComponentMap,
- getCodegenPrompt,
// Eval
evalCode,
// Utility
diff --git a/packages/mcp/skills/open-pencil/SKILL.md b/packages/mcp/skills/open-pencil/SKILL.md
deleted file mode 100644
index c7dd4f09b..000000000
--- a/packages/mcp/skills/open-pencil/SKILL.md
+++ /dev/null
@@ -1,236 +0,0 @@
----
-name: open-pencil
-description: Design-to-code via OpenPencil MCP server. Opens .fig files, inspects design structure, extracts tokens, analyzes patterns, and generates frontend code (Vue/React/Svelte + Tailwind/CSS). Use when user asks to convert Figma designs to code, inspect .fig files, or extract design tokens.
----
-
-# OpenPencil MCP — Design to Code
-
-## Prerequisites
-
-OpenPencil MCP server must be running:
-
-```bash
-cd /mnt/f/projects/openspec/dannote/open-pencil/packages/mcp
-bun src/http.ts &
-```
-
-Health check: `curl http://127.0.0.1:3100/health`
-
-## MCP Connection
-
-HTTP transport at `http://127.0.0.1:3100/mcp`. Session-based — initialize once, reuse session for all calls.
-
-```bash
-# Initialize
-curl -s -X POST http://127.0.0.1:3100/mcp \
- -H "Content-Type: application/json" \
- -H "Accept: application/json, text/event-stream" \
- -D /tmp/mcp_headers.txt \
- -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"pi","version":"1.0"}}}'
-
-# Extract session ID
-SESSION=$(grep -i 'mcp-session-id' /tmp/mcp_headers.txt | tr -d '\r' | awk '{print $2}')
-
-# Send initialized notification
-curl -s -X POST http://127.0.0.1:3100/mcp \
- -H "Content-Type: application/json" \
- -H "Accept: application/json, text/event-stream" \
- -H "mcp-session-id: $SESSION" \
- -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
-```
-
-### Calling Tools
-
-```bash
-curl -s -X POST http://127.0.0.1:3100/mcp \
- -H "Content-Type: application/json" \
- -H "Accept: application/json, text/event-stream" \
- -H "mcp-session-id: $SESSION" \
- -d '{"jsonrpc":"2.0","id":NNN,"method":"tools/call","params":{"name":"TOOL_NAME","arguments":{...}}}'
-```
-
-Response is SSE — parse with: `sed 's/^event: message$//' | sed 's/^data: //'`
-
-Result text is in: `result.content[0].text` (JSON string — parse twice for structured data).
-
-## Pipeline: Design → Code
-
-Follow these steps in order. Never guess — always read actual design data.
-
-### Step 1 — Open File & Survey
-
-```
-open_file path=<.fig file> → opens document, returns page list
-get_page_tree → full node hierarchy
-get_components → reusable Figma components
-design_to_tokens format="css" → extract design variables
-analyze_colors limit=20 → color palette with frequencies
-analyze_typography → font stacks, sizes, weights
-analyze_spacing grid=4 → gap/padding values, grid compliance
-```
-
-After this step you know: screen count, component inventory, token system, type scale, spacing grid.
-
-### Step 2 — Decompose
-
-```
-analyze_clusters min_count=2 → repeated patterns → potential components
-describe id=<node> → semantic role, layout, visual properties
-get_jsx id=<node> → structural JSX (nesting, props, text content)
-design_to_component_map → screens, components, sections overview
-```
-
-Build component map: screens (top-level frames), components (repeated patterns or COMPONENT nodes), primitives (leaf text/icon nodes).
-
-### Step 3 — Extract Tokens
-
-For **Tailwind** stacks — only semantic colors as CSS custom properties:
-
-```css
-:root {
- --app-bg: #0F0F1A;
- --app-surface: #1A1A2E;
- --app-accent: #7C3AED;
- --app-text: #FFFFFF;
- --app-text-dim: rgba(255, 255, 255, 0.5);
-}
-```
-
-Use Tailwind utilities directly for spacing (`gap-3`, `p-4`), font sizes (`text-[13px]`), weights (`font-bold`), radius (`rounded-xl`). Do NOT create CSS variables for these — they conflict with Tailwind v4 internals.
-
-For **CSS Modules / plain CSS** — variables for all categories with a project prefix.
-
-### Step 4 — Generate Code
-
-Bottom-up: primitives → components → screens. One file per component.
-
-For each node, call `get_jsx` and `describe` to read exact structure, then translate:
-
-| Figma concept | Code |
-|---|---|
-| `layoutMode: HORIZONTAL` | `flex flex-row` |
-| `layoutMode: VERTICAL` | `flex flex-col` |
-| `itemSpacing` | `gap-N` |
-| `paddingTop/Right/Bottom/Left` | `p-N` / `px-N py-N` / `pt-N pr-N ...` |
-| `primaryAxisAlign: CENTER` | `justify-center` |
-| `counterAxisAlign: CENTER` | `items-center` |
-| `layoutGrow > 0` | `flex-1` or `grow` |
-| `cornerRadius` | `rounded-N` |
-| `clipsContent: true` | `overflow-hidden` |
-| `opacity < 1` | `opacity-N` |
-| `layoutMode: NONE` | `relative` parent + `absolute` children |
-
-Interactive states (buttons, cards): always add `cursor-pointer`, `hover:`, `active:`, `transition-*` even if Figma has no hover variants.
-
-### Step 5 — Verify
-
-Re-check generated code against design: all text present, colors match, spacing correct, hierarchy preserved.
-
-## Tool Reference (91 tools)
-
-### File & Navigation
-| Tool | Params | Description |
-|---|---|---|
-| `open_file` | `path` | Open .fig/.figjam file |
-| `get_page_tree` | — | Node tree of current page |
-| `get_node` | `id` | Detailed node properties |
-| `find_nodes` | `name?, type?` | Find by name/type |
-| `get_selection` | — | Currently selected nodes |
-| `query` | `xpath` | XPath node query |
-
-### Read & Inspect
-| Tool | Params | Description |
-|---|---|---|
-| `get_jsx` | `id` | JSX representation of node tree |
-| `diff_jsx` | `from, to` | Structural diff between nodes |
-| `describe` | `id` | Semantic description: role, layout, issues |
-
-### Analysis
-| Tool | Params | Description |
-|---|---|---|
-| `analyze_colors` | `limit?` | Color palette with frequencies |
-| `analyze_typography` | — | Font families, sizes, weights |
-| `analyze_spacing` | `grid?` | Gaps, paddings, grid compliance |
-| `analyze_clusters` | `min_count?` | Repeated visual patterns |
-
-### Variables & Tokens
-| Tool | Params | Description |
-|---|---|---|
-| `list_variables` | `collection?` | All variables with values per mode |
-| `list_collections` | — | Variable collections and modes |
-| `get_components` | — | Component definitions |
-
-### Codegen Pipeline
-| Tool | Params | Description |
-|---|---|---|
-| `design_to_tokens` | `format` (css/tailwind/json) | Extract variables as code tokens |
-| `design_to_component_map` | — | Screens, components, sections overview |
-| `get_codegen_prompt` | — | Full codegen guidelines (6.7KB) |
-
-### Export
-| Tool | Params | Description |
-|---|---|---|
-| `export_svg` | `ids` | Export nodes as SVG |
-| `export_png` | `id, scale?` | Export node as PNG |
-
-### Create & Modify
-| Tool | Params | Description |
-|---|---|---|
-| `render_jsx` | `jsx, x?, y?` | Render JSX into scene graph |
-| `set_fill` | `id, color` | Set node fill |
-| `set_text` | `id, text` | Set text content |
-| `create_frame` | `width, height, ...` | Create frame node |
-
-(Full list: call `tools/list` on MCP endpoint)
-
-## Example Session
-
-```bash
-# 1. Open file
-open_file path="/path/to/design.fig"
-
-# 2. Survey
-get_page_tree
-analyze_colors limit=20
-analyze_typography
-analyze_spacing grid=4
-
-# 3. Inspect root frame
-get_jsx id="0:171"
-describe id="0:171"
-
-# 4. Inspect sections
-describe id="0:189" # Content section
-get_jsx id="0:200" # Stats component
-
-# 5. Find patterns
-analyze_clusters min_count=2
-
-# 6. Get codegen guidelines
-get_codegen_prompt
-
-# 7. Generate code based on collected data
-# → Write Vue/React components with Tailwind classes
-# → Create tokens.css with semantic color variables
-# → Match every measurement from the design exactly
-```
-
-## Stack-Specific Notes
-
-### Vue 3 + Tailwind
-- `<script setup lang="ts">`, `defineProps`, `<template>`
-- Tailwind utility classes, no scoped styles needed
-- CSS custom properties only for semantic colors in a global `tokens.css`
-- Reference: `bg-[var(--app-accent)]`, `text-[var(--app-text)]`
-
-### React + Tailwind
-- Functional components, TypeScript, `className`
-- Same token strategy as Vue
-
-### Vue 3 + CSS
-- `<script setup lang="ts">`, scoped `<style>`
-- CSS custom properties for all token categories
-
-### HTML + CSS
-- Semantic HTML, BEM classes
-- Full CSS custom property system
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 1792b96cb..a6d6f2de1 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -1,5 +1,6 @@
import { readFile, writeFile } from 'node:fs/promises'
-import { isAbsolute, relative, resolve } from 'node:path'
+import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
@@ -194,5 +195,25 @@ export function createServer(version: string, options: CreateServerOptions = {})
registerTool(tool)
}
+ let _codegenPrompt: string | null = null
+ register(
+ 'get_codegen_prompt',
+ {
+ description: 'Get design-to-code generation guidelines. Call before generating frontend code.',
+ inputSchema: z.object({})
+ },
+ async () => {
+ try {
+ if (!_codegenPrompt) {
+ const corePath = dirname(fileURLToPath(import.meta.resolve('@open-pencil/core')))
+ _codegenPrompt = await readFile(join(corePath, 'tools', 'prompts', 'codegen.md'), 'utf-8')
+ }
+ return ok({ prompt: _codegenPrompt })
+ } catch (e) {
+ return fail(e)
+ }
+ }
+ )
+
return server
}