### Clone Figma Copilot Repository and Install Dependencies Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/OVERVIEW.md These commands first clone the Figma Copilot project from its GitHub repository. After navigating into the new directory, 'bun install' is used to download and set up all required project dependencies. ```bash git clone https://github.com/xlzuvekas/figma-copilot.git cd figma-copilot bun install ``` -------------------------------- ### Figma Copilot: Development Setup and Run Commands (Bun) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CLAUDE.md This section provides a comprehensive list of `bun` commands essential for setting up, building, running, and publishing the Figma Copilot project. These commands facilitate initial dependency installation, starting the WebSocket server, compiling TypeScript code, and executing the MCP server for development and deployment. ```bash # Initial setup - installs dependencies and configures MCP bun setup # Start WebSocket server (required for communication) bun socket # Build the TypeScript server bun run build # Build in watch mode for development bun run dev # Run the MCP server bun start # Or use the published version bunx figma-copilot # Publish to npm (maintainers only) bun pub:release ``` -------------------------------- ### Install Bun Runtime Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/OVERVIEW.md This command downloads and executes the official Bun installation script, making the Bun JavaScript runtime available on your system. Bun is essential for running the Figma Copilot components. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Run Automated Environment Setup Scripts Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/OVERVIEW.md These shell scripts provide automated ways to set up the Figma Copilot environment. 'scripts/setup.sh' installs dependencies and configures Cursor, while 'scripts/setup-claude-desktop.sh' builds the project and configures Claude Desktop with the local MCP server path. ```bash scripts/setup.sh ``` ```bash scripts/setup-claude-desktop.sh ``` -------------------------------- ### Start Figma Copilot WebSocket Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/OVERVIEW.md This command initiates the lightweight WebSocket server, which is built with Bun. This server acts as a crucial relay, facilitating communication between the MCP server and the Figma plugin. ```bash bun socket ``` -------------------------------- ### Clone and Setup Figma Copilot Repository Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md Commands to clone the Figma Copilot repository from GitHub, navigate into it, and install project dependencies using Bun. ```bash git clone https://github.com/xlzuvekas/figma-copilot.git cd figma-copilot bun install ``` -------------------------------- ### Start Figma Copilot WebSocket Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md Command to start the WebSocket server for the Figma Copilot, enabling communication between Claude Desktop and Figma. ```bash cd figma-copilot bun socket ``` -------------------------------- ### Install Bun JavaScript Runtime Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md Commands to install the Bun JavaScript runtime on different operating systems, essential for running the WebSocket server. ```bash curl -fsSL https://bun.sh/install | bash ``` ```powershell powershell -c "irm bun.sh/install.ps1|iex" ``` -------------------------------- ### Configure Figma Copilot MCP Setup Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Executes the Bun setup command to configure the Model Context Protocol (MCP) for Figma Copilot. This step prepares the server for seamless integration with various MCP clients. ```bash bun setup ``` -------------------------------- ### Start WebSocket Server on Windows WSL Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Command to start the WebSocket server specifically within a Windows Subsystem for Linux (WSL) environment. This command should be executed after configuring the hostname in `src/socket.ts` for WSL compatibility. ```bash bun socket ``` -------------------------------- ### Install Bun Package Manager Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Installs the Bun JavaScript runtime and package manager on your system using a curl command. Bun is a prerequisite for running the Figma Copilot server and its related components. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Example Claude Desktop Commands for Figma Interaction Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md Demonstrates various commands to interact with Figma through Claude Desktop, including connecting to a channel, retrieving document information, reading selections, and creating new elements. ```text Use the join_channel tool to connect to channel "figma-design" ``` ```text Get information about the current Figma document ``` ```text Read the current selection in Figma ``` ```text Create a red rectangle at position (100, 100) with size 200x150 ``` -------------------------------- ### Install Bun on Windows via PowerShell Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Installs the Bun JavaScript runtime and package manager on Windows using a PowerShell command. This method is specifically recommended for environments utilizing Windows Subsystem for Linux (WSL). ```powershell powershell -c "irm bun.sh/install.ps1|iex" ``` -------------------------------- ### Start Figma Copilot MCP Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Launches the core Figma Copilot Model Context Protocol (MCP) server. This server is responsible for enabling AI assistants to programmatically interact with and manipulate Figma designs. ```bash bunx figma-copilot ``` -------------------------------- ### Start Figma Copilot WebSocket Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Initiates the WebSocket server, which serves as the crucial communication bridge. It connects the Figma Copilot MCP server with the Figma plugin, enabling real-time interactions. ```bash bun socket ``` -------------------------------- ### Configure Claude Desktop for Figma Copilot MCP Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/OVERVIEW.md This JSON snippet is used to configure Claude Desktop, adding a new Model Context Protocol (MCP) server entry for 'talk-to-figma'. It specifies the command and arguments required to launch the Figma Copilot MCP server using Bun. ```json { "mcpServers": { "talk-to-figma": { "command": "bunx", "args": ["figma-copilot@latest"], "env": {} } } } ``` -------------------------------- ### Component Description and Markdown API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/TEXT_STYLING.md API functions for setting and retrieving markdown-based component descriptions and for normalizing common Markdown to Figma's subset. ```APIDOC set_component_description get_component_description normalize_markdown ``` -------------------------------- ### Figma Copilot: Batch Operations API (v0.3.2) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for performing multiple operations efficiently in a single request, significantly improving performance for tasks like cloning, getting node info, and setting properties. Refer to the Batch Operations Guide for best practices. ```APIDOC clone_multiple_nodes(node_id: string, positions: object[]) description: Clone a node to multiple positions in one operation (50-90% faster than individual clones) ``` ```APIDOC get_multiple_nodes_info(node_ids: string[]) description: Get information for multiple nodes in a single request ``` ```APIDOC set_multiple_nodes_property(node_ids: string[], property_name: string, value: any) description: Set the same property value on multiple nodes at once ``` ```APIDOC execute_batch(commands: object[]) description: Execute multiple different commands in sequence with a single round-trip ``` ```APIDOC get_connection_status() description: Get current connection status and statistics ``` -------------------------------- ### Figma Copilot Related Documentation Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Links to additional documentation guides for advanced operations, enhanced text handling, text styling, font management, and the latest changelog. ```APIDOC - [Batch Operations Guide](docs/BATCH_OPERATIONS.md) - Learn how to use batch operations for massive performance gains - [Enhanced Text Operations Guide](docs/ENHANCED_TEXT_OPERATIONS.md) - Preserve formatting while updating text - [Text Styling Guide](docs/TEXT_STYLING.md) - Apply and manage text styles - [Font Handling Documentation](docs/FONT_HANDLING.md) - Handle mixed fonts and font loading strategies - [Changelog v0.3.2](CHANGELOG_v0.3.2.md) - Latest release notes ``` -------------------------------- ### Figma Copilot API: MCP Helper Prompts Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md A collection of helper prompts provided by the MCP server to guide users through complex design tasks and best practices within Figma. ```APIDOC design_strategy - Best practices for working with Figma designs read_design_strategy - Best practices for reading Figma designs text_replacement_strategy - Systematic approach for replacing text in Figma designs annotation_conversion_strategy - Strategy for converting manual annotations to Figma's native annotations swap_overrides_instances - Strategy for transferring overrides between component instances in Figma reaction_to_connector_strategy - Strategy for converting Figma prototype reactions to connector lines using the output of 'get_reactions', and guiding the use 'create_connections' in sequence batch_operations_guide - Best practices for efficient bulk operations in Figma (v0.3.2) error_recovery_guide - How to handle common errors and timeouts in Figma operations (v0.3.2) text_formatting_guide - Best practices for updating text while preserving formatting (v0.3.2) ``` -------------------------------- ### Text Range Styling API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/docs/TEXT_STYLING.md API functions for applying and retrieving various text styles, decorations, fonts, sizes, and colors to specific text ranges, and for extracting detailed styled segments. ```APIDOC set_text_style_range get_text_style_range set_text_decoration_range get_text_decoration_range set_range_font set_range_font_size set_range_fills get_styled_text_segments ``` -------------------------------- ### Figma Copilot: Text Styling API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for applying and retrieving detailed text styling properties to specific character ranges, including font, size, and color. Refer to the Text Styling Guide for detailed usage. ```APIDOC set_text_style_range(node_id: string, start: number, end: number, style: object) description: Apply text styling (bold, italic, underline, strikethrough) to specific character ranges ``` ```APIDOC get_text_style_range(node_id: string, start: number, end: number) description: Get text styling for a specific range ``` ```APIDOC set_text_decoration_range(node_id: string, start: number, end: number, decoration: object) description: Set advanced text decoration properties ``` ```APIDOC get_text_decoration_range(node_id: string, start: number, end: number) description: Get text decoration properties for a range ``` ```APIDOC set_range_font(node_id: string, start: number, end: number, font: object) description: Change font family and style for a text range ``` ```APIDOC set_range_font_size(node_id: string, start: number, end: number, size: number) description: Change font size for a text range ``` ```APIDOC set_range_fills(node_id: string, start: number, end: number, fills: object[]) description: Set text color for a specific range ``` ```APIDOC get_styled_text_segments(node_id: string) description: Get detailed information about text segments and their properties ``` ```APIDOC set_component_description(component_id: string, description: string) description: Set component description using Markdown ``` ```APIDOC get_component_description(component_id: string) description: Get component description in Markdown format ``` ```APIDOC normalize_markdown(markdown_text: string) description: Normalize Markdown text to Figma's supported subset ``` -------------------------------- ### Figma Copilot: Enhanced Text Operations API (v0.3.2) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for updating text while preserving character formatting, including smart find and replace, and batch updates with styles. Refer to the Enhanced Text Operations Guide for more details. ```APIDOC update_text_preserve_formatting(node_id: string, new_text: string) description: Update text while preserving all character formatting (bold, italic, colors, fonts) ``` ```APIDOC smart_text_replace(node_id: string, find_text: string, replace_text: string) description: Find and replace text while preserving formatting of unchanged portions ``` ```APIDOC set_multiple_text_contents_with_styles(updates: object[]) description: Batch update text with formatting in a single operation ``` -------------------------------- ### Figma Element Creation Coordinate Handling Example Source: https://github.com/xlzuvekas/figma-copilot/blob/main/coordinate-analysis.md Illustrates how to integrate coordinate conversion into element creation functions. It checks if the editor is in 'slides' mode and if a `slideId` is provided, then uses the `toAbsoluteCoordinates` helper to adjust the element's position. It also includes logic for auto-detecting the focused slide if no `slideId` or `parentId` is given. ```javascript // Handle coordinate conversion for slides if (figma.editorType === "slides" && slideId) { const absolute = toAbsoluteCoordinates(slideId, x, y); shapeWithText.x = absolute.x; shapeWithText.y = absolute.y; } else if (figma.editorType === "slides" && !slideId && !parentId) { // If no slide specified, try to find the focused slide const focusedSlide = figma.currentPage.focusedSlide; if (focusedSlide) { const absolute = toAbsoluteCoordinates(focusedSlide.id, x, y); shapeWithText.x = absolute.x; shapeWithText.y = absolute.y; } } ``` -------------------------------- ### Building Figma Copilot Plugin Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Instructions for navigating to the Figma plugin directory to begin development and modification of the plugin's core files. ```Shell cd src/figma_copilot_plugin ``` -------------------------------- ### Figma Copilot MCP Available Tools Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md A list of over 40 available tools provided by the Figma Copilot MCP server for interacting with Figma, including functions for document information, selection, element creation, and styling. ```APIDOC get_document_info: Get current document information get_selection: Get current selection details read_my_design: Read detailed info about selected elements create_rectangle: Create new rectangle element create_frame: Create new frame element create_text: Create new text element set_text_content: Update text content of elements set_multiple_text_contents: Update text content for multiple elements set_fill_color: Set fill color of elements set_stroke_color: Set stroke color of elements set_layout_mode: Configure auto-layout mode set_padding: Set padding for auto-layout elements set_item_spacing: Set item spacing for auto-layout elements ``` -------------------------------- ### Configure Claude Desktop for Figma Copilot MCP Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md JSON configurations for Claude Desktop to register the Figma Copilot MCP server, providing options for using the latest published version via `bunx` or a local development build. ```json { "mcpServers": { "talk-to-figma": { "command": "bunx", "args": ["figma-copilot@latest"], "env": {} } } } ``` ```json { "mcpServers": { "talk-to-figma": { "command": "bun", "args": ["run", "/path/to/figma-copilot/dist/server.js"], "env": {} } } } ``` -------------------------------- ### Figma Copilot MCP General Best Practices Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md General best practices for efficient and effective interaction with the Figma MCP, covering command sequencing, selection, and error handling. ```APIDOC 1. Always join a channel before sending commands 2. Get document overview using `get_document_info` first 3. Check current selection with `get_selection` before modifications 4. Use appropriate creation tools based on needs: - `create_frame` for containers - `create_rectangle` for basic shapes - `create_text` for text elements 5. Verify changes using `get_node_info` 6. Use component instances when possible for consistency 7. Handle errors appropriately as all commands can throw exceptions ``` -------------------------------- ### Figma Copilot MCP Best Practices: Converting Legacy Annotations Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md A step-by-step strategy for converting manual annotations to Figma's native annotations using Figma Copilot, ensuring proper linking and cleanup. ```APIDOC For converting legacy annotations: - Scan text nodes to identify numbered markers and descriptions - Use `scan_nodes_by_types` to find UI elements that annotations refer to - Match markers with their target elements using path, name, or proximity - Categorize annotations appropriately with `get_annotations` - Create native annotations with `set_multiple_annotations` in batches - Verify all annotations are properly linked to their targets - Delete legacy annotation nodes after successful conversion ``` -------------------------------- ### Figma Copilot API: Components & Styles Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for interacting with Figma components and styles, including retrieval of local styles and components, creation of component instances, and management of instance overrides. ```APIDOC get_styles - Get information about local styles get_local_components - Get information about local components create_component_instance - Create an instance of a component get_instance_overrides - Extract override properties from a selected component instance set_instance_overrides - Apply extracted overrides to target instances ``` -------------------------------- ### Figma Copilot MCP Best Practices: Visualizing Prototype Noodles Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Strategy for converting Figma prototype reactions into FigJam connectors for clear visual flow mapping, utilizing specific API calls. ```APIDOC Visualize prototype noodles as FigJam connectors: - Use `get_reactions` to extract prototype flows, - set a default connector with `set_default_connector`, - and generate connector lines with `create_connections` for clear visual flow mapping. ``` -------------------------------- ### Figma Copilot: Prototyping & Connection API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for managing prototype reactions and creating connections between nodes in FigJam. ```APIDOC get_reactions() description: Get all prototype reactions from nodes with visual highlight animation ``` ```APIDOC set_default_connector(connector_id: string) description: Set a copied FigJam connector as the default connector style for creating connections. Must be set before creating connections. ``` ```APIDOC create_connections(connections: object[]) description: Create FigJam connector lines between nodes, based on prototype flows or custom mapping ``` -------------------------------- ### Integrate Figma Copilot with MCP Clients Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Provides a JSON configuration snippet for integrating the Figma Copilot MCP server into an MCP client's configuration file, such as Cursor's `mcp.json`. This allows the client to discover and utilize the Figma Copilot server. ```json { "mcpServers": { "figma-copilot": { "command": "bunx", "args": ["figma-copilot@latest"] } } } ``` -------------------------------- ### Initialize WebSocket Connection State and UI Elements (JavaScript) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html This snippet defines the initial state for the WebSocket connection, including connection status, socket instance, and pending requests. It also identifies and references key UI elements from the HTML document that will be manipulated to reflect the connection status and progress. ```JavaScript // WebSocket connection state const state = { connected: false, socket: null, serverPort: 3055, pendingRequests: new Map(), channel: null }; // UI Elements const portInput = document.getElementById("port"); const connectButton = document.getElementById("btn-connect"); const disconnectButton = document.getElementById("btn-disconnect"); const connectionStatus = document.getElementById("connection-status"); // Tabs const tabs = document.querySelectorAll(".tab"); const tabContents = document.querySelectorAll(".tab-content"); // Add UI elements for progress tracking const progressContainer = document.getElementById("progress-container"); const progressBar = document.getElementById("progress-bar"); const progressMessage = document.getElementById("progress-message"); const progressStatus = document.getElementById("progress-status"); const progressPercentage = document.getElementById("progress-percentage"); // Initialize UI function updateConnectionStatus(isConnected, message) { state.connected = isConnected; connectionStatus.innerHTML = message || (isConnected ? "Connected to Cursor MCP server" : "Not connected to Cursor MCP server"); connectionStatus.className = `status ${ isConnected ? "connected" : "disconnected" }`; connectButton.disabled = isConnected; disconnectButton.disabled = !isConnected; portInput.disabled = isConnected; } ``` -------------------------------- ### Figma Copilot MCP Best Practices: Text Operations Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Best practices for performing text operations in Figma, focusing on using batch operations, considering structural relationships, and verifying changes. ```APIDOC For text operations: - Use batch operations when possible - Consider structural relationships - Verify changes with targeted exports ``` -------------------------------- ### Configure WebSocket Server for WSL Source: https://github.com/xlzuvekas/figma-copilot/blob/main/README_CLAUDE_DESKTOP.md Code snippet showing the modification required in `src/socket.ts` to allow the WebSocket server to listen on all network interfaces, necessary for WSL environments. ```typescript hostname: "0.0.0.0", ``` -------------------------------- ### Connect to Server Button Handler Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Attaches an event listener to a connect button. On click, it parses the port input, updates the connection status UI, and initiates a connection to the server, allowing users to establish a WebSocket link. ```javascript connectButton.addEventListener("click", () => { const port = parseInt(portInput.value, 10) || 3055; updateConnectionStatus(false, "Connecting..."); connectionStatus.className = "status info"; connectToServer(port); }); ``` -------------------------------- ### Figma Copilot API: Connection Management Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API method for establishing communication with Figma by joining a specific channel. ```APIDOC join_channel - Join a specific channel to communicate with Figma ``` -------------------------------- ### Figma Copilot MCP Best Practices: Large Designs Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Specific best practices for handling large Figma designs to optimize performance, monitor progress, and implement robust error handling. ```APIDOC For large designs: - Use chunking parameters in `scan_text_nodes` - Monitor progress through WebSocket updates - Implement appropriate error handling ``` -------------------------------- ### Figma Copilot: Build Plugin for Figma Compatibility (npm) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CLAUDE.md To ensure compatibility with the Figma environment, which typically requires ES5 JavaScript, changes made to the Figma plugin's `code.js` and `ui.html` files must be transpiled. The `npm run build:plugin` command performs this transpilation, converting modern JavaScript (ES6+) to ES5. ```bash npm run build:plugin ``` -------------------------------- ### Figma Copilot: Element Creation API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for programmatically creating basic design elements like rectangles, frames, and text nodes. ```APIDOC create_rectangle(position: object, size: object, name?: string) description: Create a new rectangle with position, size, and optional name ``` ```APIDOC create_frame(position: object, size: object, name?: string) description: Create a new frame with position, size, and optional name ``` ```APIDOC create_text(position: object, content: string, font_properties?: object) description: Create a new text node with customizable font properties ``` -------------------------------- ### Connect to WebSocket Server (JavaScript) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html This asynchronous function establishes a WebSocket connection to a specified port. It sets up event listeners for onopen, onmessage, onclose, and onerror events, handling connection status updates, message parsing, and error reporting. Upon successful connection, it joins a dynamically generated channel and notifies the parent plugin. ```JavaScript async function connectToServer(port) { try { if (state.connected && state.socket) { updateConnectionStatus(true, "Already connected to server"); return; } state.serverPort = port; state.socket = new WebSocket(`ws://localhost:${port}`); state.socket.onopen = () => { // Generate random channel name const channelName = generateChannelName(); console.log("Joining channel:", channelName); state.channel = channelName; // Join the channel using the same format as App.tsx state.socket.send( JSON.stringify({ type: "join", channel: channelName.trim() }) ); }; state.socket.onmessage = (event) => { try { const data = JSON.parse(event.data); console.log("Received message:", data); if (data.type === "system") { // Successfully joined channel if (data.message && data.message.result) { state.connected = true; const channelName = data.channel; updateConnectionStatus( true, `Connected to server on port ${port} in channel: ${channelName}` ); // Notify the plugin code parent.postMessage( { pluginMessage: { type: "notify", message: `Connected to Cursor MCP server on port ${port} in channel: ${channelName}` } }, "*" ); } } else if (data.type === "error") { console.error("Error:", data.message); updateConnectionStatus(false, `Error: ${data.message}`); state.socket.close(); } handleSocketMessage(data); } catch (error) { console.error("Error parsing message:", error); } }; state.socket.onclose = () => { state.connected = false; state.socket = null; updateConnectionStatus(false, "Disconnected from server"); }; state.socket.onerror = (error) => { console.error("WebSocket error:", error); updateConnectionStatus(false, "Connection error"); state.connected = false; state.socket = null; }; } catch (error) { console.error("Connection error:", error); updateConnectionStatus( false, `Connection error: ${error.message || "Unknown error"}` ); } } ``` -------------------------------- ### Figma Copilot Troubleshooting: Timeout Issues Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Strategies for addressing timeout issues when working with large Figma documents, recommending the use of depth limiting and partial results with `scan_nodes_with_options`. ```APIDOC For large documents that cause timeouts, use `scan_nodes_with_options` with depth limiting and partial results. See [Batch Operations Guide](docs/BATCH_OPERATIONS.md) for optimization strategies. ``` -------------------------------- ### Figma Copilot: Node Layout & Organization API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for manipulating node positions, sizes, and existence, including moving, resizing, deleting, and cloning nodes. ```APIDOC move_node(node_id: string, position: object) description: Move a node to a new position ``` ```APIDOC resize_node(node_id: string, dimensions: object) description: Resize a node with new dimensions ``` ```APIDOC delete_node(node_id: string) description: Delete a node ``` ```APIDOC delete_multiple_nodes(node_ids: string[]) description: Delete multiple nodes at once efficiently ``` ```APIDOC clone_node(node_id: string, offset?: object) description: Create a copy of an existing node with optional position offset ``` -------------------------------- ### Figma Copilot: Auto Layout & Spacing API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for configuring auto-layout properties of frames, including layout mode, padding, alignment, sizing, and item spacing. ```APIDOC set_layout_mode(frame_id: string, mode: string, wrap_behavior?: string) description: Set the layout mode and wrap behavior of a frame (NONE, HORIZONTAL, VERTICAL) ``` ```APIDOC set_padding(frame_id: string, padding: object) description: Set padding values for an auto-layout frame (top, right, bottom, left) ``` ```APIDOC set_axis_align(frame_id: string, primary_axis: string, counter_axis: string) description: Set primary and counter axis alignment for auto-layout frames ``` ```APIDOC set_layout_sizing(frame_id: string, horizontal: string, vertical: string) description: Set horizontal and vertical sizing modes for auto-layout frames (FIXED, HUG, FILL) ``` ```APIDOC set_item_spacing(frame_id: string, spacing: number) description: Set distance between children in an auto-layout frame ``` -------------------------------- ### Figma Copilot: Basic Text Operations API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for scanning and setting text content in Figma nodes. Note that `set_text_content` and `set_multiple_text_contents` do not preserve formatting. ```APIDOC scan_text_nodes() description: Scan text nodes with intelligent chunking for large designs ``` ```APIDOC scan_nodes_with_options(options: object) description: Enhanced scanning with depth control, timeout handling, and partial results ``` ```APIDOC set_text_content(node_id: string, content: string) description: Set the text content of a single text node. Note: loses formatting. ``` ```APIDOC set_multiple_text_contents(updates: object[]) description: Batch update multiple text nodes efficiently. Note: loses formatting. ``` -------------------------------- ### Figma Copilot: Node Styling API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for applying basic visual styles to nodes, such as fill color, stroke color, and corner radius. ```APIDOC set_fill_color(node_id: string, color: object) description: Set the fill color of a node (RGBA) ``` ```APIDOC set_stroke_color(node_id: string, color: object, weight: number) description: Set the stroke color and weight of a node ``` ```APIDOC set_corner_radius(node_id: string, radius: number | object) description: Set the corner radius of a node with optional per-corner control ``` -------------------------------- ### Figma Copilot: Configure WebSocket Hostname for Windows WSL (TypeScript) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CLAUDE.md When deploying the Figma Copilot project on Windows Subsystem for Linux (WSL), it is crucial to uncomment a specific hostname configuration in the `src/socket.ts` file. This adjustment ensures the WebSocket server binds correctly to '0.0.0.0', enabling proper network communication within the WSL environment. ```typescript hostname: "0.0.0.0", ``` -------------------------------- ### Enable WSL Connections for WebSocket Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Modifies the `src/socket.ts` file by uncommenting the hostname. This crucial change allows the WebSocket server to accept incoming connections from Windows Subsystem for Linux (WSL) environments, ensuring cross-platform compatibility. ```typescript // uncomment this to allow connections in windows wsl hostname: "0.0.0.0", ``` -------------------------------- ### Figma Copilot: Document & Selection API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for interacting with the current Figma document and selected nodes, including retrieving information and detailed node data. ```APIDOC get_document_info() description: Get information about the current Figma document ``` ```APIDOC get_selection() description: Get information about the current selection ``` ```APIDOC read_my_design() description: Get detailed node information about the current selection without parameters ``` ```APIDOC get_node_info(node_id: string) description: Get detailed information about a specific node ``` ```APIDOC get_nodes_info(node_ids: string[]) description: Get detailed information about multiple nodes by providing an array of node IDs ``` -------------------------------- ### Figma Copilot: Annotation Management API Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API methods for creating, updating, and retrieving annotations within a Figma document, including batch operations and scanning for annotation targets. ```APIDOC get_annotations(node_id?: string) description: Get all annotations in the current document or specific node ``` ```APIDOC set_annotation(annotation_data: object) description: Create or update an annotation with markdown support ``` ```APIDOC set_multiple_annotations(annotations: object[]) description: Batch create/update multiple annotations efficiently ``` ```APIDOC scan_nodes_by_types(types: string[]) description: Scan for nodes with specific types (useful for finding annotation targets) ``` -------------------------------- ### Figma Copilot API: Export & Advanced Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md API method for exporting a Figma node as an image in various formats (PNG, JPG, SVG, or PDF), with current limitations on image return as base64 text. ```APIDOC export_node_as_image - Export a node as an image (PNG, JPG, SVG, or PDF) - limited support on image currently returning base64 as text ``` -------------------------------- ### Figma Copilot Troubleshooting: Font Issues Source: https://github.com/xlzuvekas/figma-copilot/blob/main/readme.md Guidance on resolving "Cannot unwrap symbol" errors, which are typically caused by mixed fonts in text nodes, and refers to detailed font handling documentation. ```APIDOC If you encounter "Cannot unwrap symbol" errors when updating text, this is likely due to mixed fonts in text nodes. See [Font Handling Documentation](docs/FONT_HANDLING.md) for details on how the plugin handles mixed fonts and available strategies. ``` -------------------------------- ### Handle Messages from Figma Plugin Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Sets up a global message listener to receive communications from the Figma plugin. It processes different message types, such as connection status, auto-connect/disconnect requests, command results, errors, and progress updates, forwarding them to appropriate handlers or the WebSocket server. ```javascript window.onmessage = (event) => { const message = event.data.pluginMessage; if (!message) return; console.log("Received message from plugin:", message); switch (message.type) { case "connection-status": updateConnectionStatus(message.connected, message.message); break; case "auto-connect": connectButton.click(); break; case "auto-disconnect": disconnectButton.click(); break; case "command-result": // Forward the result from plugin code back to WebSocket sendSuccessResponse(message.id, message.result); break; case "command-error": // Forward the error from plugin code back to WebSocket sendErrorResponse(message.id, message.error); break; case "command_progress": // Update UI with progress information updateProgressUI(message); // Forward progress update to server sendProgressUpdateToServer(message); break; } }; ``` -------------------------------- ### Handle Tab Switching UI Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Implements client-side logic for tab navigation. It adds click listeners to tab elements, updating their active states and showing the corresponding content, providing a dynamic user interface. ```javascript tabs.forEach((tab) => { tab.addEventListener("click", () => { tabs.forEach((t) => t.classList.remove("active")); tabContents.forEach((c) => c.classList.remove("active")); tab.classList.add("active"); const contentId = "content-" + tab.id.split("-")[1]; document.getElementById(contentId).classList.add("active"); }); }); ``` -------------------------------- ### Smart Text Replacement with Formatting Preservation Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CHANGELOG_v0.3.2.md Shows how to use `smart_text_replace` to update template placeholders within a text node. This function intelligently replaces specified substrings while preserving the formatting of the surrounding and unchanged text. ```javascript // Update template placeholders smart_text_replace({ nodeId: "123", replacements: [ {find: "{TITLE}", replace: "Q4 Report"}, {find: "{DATE}", replace: "2024"} ] }) ``` -------------------------------- ### Handle Incoming WebSocket Messages (JavaScript) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html This function processes messages received from the WebSocket server. It distinguishes between responses to pending requests (resolving or rejecting Promises) and new commands. For new commands, it dispatches them to the parent Figma plugin using parent.postMessage for execution, and handles potential errors during command execution. ```JavaScript async function handleSocketMessage(payload) { const data = payload.message; console.log("handleSocketMessage", data); // If it's a response to a previous request if (data.id && state.pendingRequests.has(data.id)) { const { resolve, reject } = state.pendingRequests.get(data.id); state.pendingRequests.delete(data.id ``` -------------------------------- ### Figma Plugin UI Styling Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Defines the visual styles for the Cursor MCP Figma plugin's user interface, including general body styles, container layouts, typography, button appearances (default, secondary, disabled), input fields, labels, status indicators (connected, disconnected, info), sectioning, hidden elements, header layout, and tab navigation. It also includes styles for progress indicators. ```CSS Cursor MCP Plugin body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 20px; color: #e0e0e0; background-color: #1e1e1e; } .container { display: flex; flex-direction: column; height: 100%; } h1 { font-size: 16px; font-weight: 600; margin-bottom: 10px; color: #ffffff; } h2 { font-size: 14px; font-weight: 600; margin-top: 20px; margin-bottom: 8px; color: #ffffff; } button { background-color: #18a0fb; border: none; color: white; padding: 8px 12px; border-radius: 6px; margin-top: 8px; margin-bottom: 8px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; } button:hover { background-color: #0d8ee0; } button.secondary { background-color: #3d3d3d; color: #e0e0e0; } button.secondary:hover { background-color: #4d4d4d; } button:disabled { background-color: #333333; color: #666666; cursor: not-allowed; } input { border: 1px solid #444444; border-radius: 4px; padding: 8px; margin-bottom: 12px; font-size: 14px; width: 100%; box-sizing: border-box; background-color: #2d2d2d; color: #e0e0e0; } label { display: block; margin-bottom: 4px; font-size: 12px; font-weight: 500; color: #cccccc; } .status { margin-top: 16px; padding: 12px; border-radius: 6px; font-size: 14px; } .status.connected { background-color: #1a472a; color: #4ade80; } .status.disconnected { background-color: #471a1a; color: #ff9999; } .status.info { background-color: #1a3147; color: #66b3ff; } .section { margin-bottom: 24px; } .hidden { display: none; } .logo { width: 50px; height: 50px; } .header { display: flex; align-items: center; margin-bottom: 16px; } .header-text { margin-left: 12px; } .header-text h1 { margin: 0; font-size: 16px; } .header-text p { margin: 4px 0 0 0; font-size: 12px; color: #999999; } .tabs { display: flex; border-bottom: 1px solid #444444; margin-bottom: 16px; } .tab { padding: 8px 16px; cursor: pointer; font-size: 14px; font-weight: 500; color: #999999; } .tab.active { border-bottom: 2px solid #18a0fb; color: #18a0fb; } .tab-content { display: none; } .tab-content.active { display: block; } .link { color: #18a0fb; text-decoration: none; cursor: pointer; } .link:hover { text-decoration: underline; } .header-logo { padding: 16px; border-radius: 16px; background-color: #333; } .header-logo-image { width: 24px; height: 24px; object-fit: contain; } /* Progress styles */ .operation-complete { color: #4ade80; } .operation-error { color: #ff9999; } ``` -------------------------------- ### Performing Batch Node Cloning in Figma Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CHANGELOG_v0.3.2.md Illustrates the use of `clone_multiple_nodes` for efficiently cloning a source node to multiple positions in a single API call. This significantly improves performance for operations involving many node duplications. ```javascript // Clone to 20 positions at once clone_multiple_nodes({ sourceNodeId: "template", positions: [ {x: 41, y: 3267}, {x: 41, y: 3709}, // ... 18 more ] }) ``` -------------------------------- ### Send Operation Progress Update to Server Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Sends progress updates for an ongoing command back to the WebSocket server. It checks for an active connection and then serializes the progress data before sending, keeping the server informed of operation status. ```javascript function sendProgressUpdateToServer(progressData) { if (!state.connected || !state.socket) { console.error("Cannot send progress update: socket not connected"); return; } console.log("Sending progress update to server:", progressData); state.socket.send( JSON.stringify({ id: progressData.commandId, type: "progress_update", channel: state.channel, message: { id: progressData.commandId, type: "progress_update", data: progressData } }) ); } ``` -------------------------------- ### Send Success Response via WebSocket Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Sends a successful command result back to the connected WebSocket server. It checks for an active connection before stringifying the message and sending it, ensuring reliable communication. ```javascript function sendSuccessResponse(id, result) { if (!state.connected || !state.socket) { console.error("Cannot send response: socket not connected"); return; } state.socket.send( JSON.stringify({ id, type: "message", channel: state.channel, message: { id, result } }) ); } ``` -------------------------------- ### Generate Random Channel Name Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Creates an 8-character random string composed of lowercase letters and digits. This is typically used for generating unique channel identifiers for WebSocket communication or other dynamic purposes. ```javascript function generateChannelName() { const characters = "abcdefghijklmnopqrstuvwxyz0123456789"; let result = ""; for (let i = 0; i < 8; i++) { result += characters.charAt( Math.floor(Math.random() * characters.length) ); } return result; } ``` -------------------------------- ### Send Error Response via WebSocket Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Sends an error message back to the connected WebSocket server. It verifies the connection status before formatting and sending the error, providing feedback for failed operations. ```javascript function sendErrorResponse(id, errorMessage) { if (!state.connected || !state.socket) { console.error("Cannot send error response: socket not connected"); return; } state.socket.send( JSON.stringify({ id, type: "message", channel: state.channel, message: { id, error: errorMessage, result: {} } }) ); } ``` -------------------------------- ### Update Operation Progress UI Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Updates the user interface to display the progress of an ongoing operation. It shows/hides a progress container, updates the progress bar width, percentage, message, and status text based on the provided progress data, and hides the container after completion or error. ```javascript function updateProgressUI(progressData) { // Show progress container if hidden progressContainer.classList.remove("hidden"); // Update progress bar const progress = progressData.progress || 0; progressBar.style.width = `${progress}%`; progressPercentage.textContent = `${progress}%`; // Update message progressMessage.textContent = progressData.message || "Operation in progress"; // Update status text based on operation state if (progressData.status === 'started') { progressStatus.textContent = "Started"; progressStatus.className = ""; } else if (progressData.status === 'in_progress') { progressStatus.textContent = "In Progress"; progressStatus.className = ""; } else if (progressData.status === 'completed') { progressStatus.textContent = "Completed"; progressStatus.className = "operation-complete"; // Hide progress container after 5 seconds setTimeout(() => { progressContainer.classList.add("hidden"); }, 5000); } else if (progressData.status === 'error') { progressStatus.textContent = "Error"; progressStatus.className = "operation-error"; } } ``` -------------------------------- ### Figma Slide Layout Constants Source: https://github.com/xlzuvekas/figma-copilot/blob/main/coordinate-analysis.md Defines constant values for slide dimensions and spacing used in the Figma plugin, crucial for calculating slide positions and element offsets. ```javascript const SLIDE_WIDTH = 1920; const SLIDE_HEIGHT = 1080; const HORIZONTAL_SPACING = 240; const VERTICAL_SPACING = 240; const INITIAL_X = 240; const INITIAL_Y = 240; ``` -------------------------------- ### Figma Slide Coordinate Conversion Helpers Source: https://github.com/xlzuvekas/figma-copilot/blob/main/coordinate-analysis.md Helper functions to convert coordinates between local slide-relative and absolute page-relative systems. `toAbsoluteCoordinates` adjusts local coordinates to the document's origin, while `toLocalCoordinates` converts absolute document coordinates back to a slide's local frame. These are essential for correctly positioning elements on Figma slides. ```javascript // Helper function to convert local slide coordinates to absolute page coordinates function toAbsoluteCoordinates(slideId, localX, localY) { const slide = figma.getNodeById(slideId); if (!slide || slide.type !== 'SLIDE') { throw new Error(`Invalid slide ID: ${slideId}`); } return { x: slide.x + localX, y: slide.y + localY }; } // Helper function to convert absolute page coordinates to local slide coordinates function toLocalCoordinates(slideId, absoluteX, absoluteY) { const slide = figma.getNodeById(slideId); if (!slide || slide.type !== 'SLIDE') { throw new Error(`Invalid slide ID: ${slideId}`); } return { x: absoluteX - slide.x, y: absoluteY - slide.y }; } ``` -------------------------------- ### Disconnect from Server Button Handler Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Attaches an event listener to a disconnect button. On click, it updates the connection status UI and triggers the disconnection process from the server, allowing users to terminate the WebSocket link. ```javascript disconnectButton.addEventListener("click", () => { updateConnectionStatus(false, "Disconnecting..."); connectionStatus.className = "status info"; disconnectFromServer(); }); ``` -------------------------------- ### Generate Unique ID for Messages Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Generates a unique identifier string using the current timestamp and a random number. This ID can be used for message tracking or correlation across different parts of the application. ```javascript function generateId() { return ( Date.now().toString(36) + Math.random().toString(36).substr(2, 5) ); } ``` -------------------------------- ### Disconnect from WebSocket Server (JavaScript) Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html This function gracefully closes the active WebSocket connection. It checks if a socket exists, closes it, resets the connection state, and updates the UI to reflect the disconnected status. ```JavaScript function disconnectFromServer() { if (state.socket) { state.socket.close(); state.socket = null; state.connected = false; updateConnectionStatus(false, "Disconnected from server"); } } ``` -------------------------------- ### Reset Progress UI State Source: https://github.com/xlzuvekas/figma-copilot/blob/main/src/figma_copilot_plugin/ui.html Resets the progress display elements to their initial hidden and default states. This function is typically called when an operation is finished or cancelled, clearing the UI for the next task. ```javascript function resetProgressUI() { progressContainer.classList.add("hidden"); progressBar.style.width = "0%"; progressMessage.textContent = "No operation in progress"; progressStatus.textContent = "Not started"; progressStatus.className = ""; progressPercentage.textContent = "0%"; } ``` -------------------------------- ### Preserving Text Formatting in Figma Source: https://github.com/xlzuvekas/figma-copilot/blob/main/CHANGELOG_v0.3.2.md Demonstrates the new `update_text_preserve_formatting` function, which allows updating text content on a Figma node while retaining all character-level formatting (bold, italic, colors, fonts). This replaces the old method which would strip formatting. ```javascript // Old way - loses formatting set_text_content({nodeId: "123", text: "New Text"}) // New way - preserves formatting update_text_preserve_formatting({ nodeId: "123", newText: "New Text", preserveFormattingStrategy: "stretch" }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.