Skip to main content
Glama
andreasHornqvist

MCP Server Template for Cursor IDE

figma_design

Extract Figma design data including structure and images for integration into development workflows. Provide the full Figma URL to retrieve organized design information.

Instructions

Get Figma design data including structure and images

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesThe full Figma design URL

Implementation Reference

  • The handler function for the 'figma_design' tool. It calls the helper fetch_figma_data with the provided URL and handles exceptions.
    async def get_figma_design(
        url: str,
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        """Get Figma design data including structure and images."""
        try:
            return fetch_figma_data(url)
        except Exception as e:
            return [types.TextContent(
                type="text",
                text=json.dumps({"error": f"Failed to fetch Figma design: {str(e)}"})
            )]
  • Helper function that implements the core logic: parses Figma URL, fetches file structure and image data using Figma API, collects image nodes recursively, fetches image URLs, and returns JSON-structured data.
    def fetch_figma_data(figma_url: str) -> List[types.TextContent]:
        parsed = urlparse(figma_url)
        # Support both '/file/…' and '/design/…' URL formats.
        file_key = re.search(r'/(?:file|design)/([a-zA-Z0-9]+)', parsed.path).group(1)
        qs = parse_qs(parsed.query)
        node_ids = qs.get("node-id", [])
        headers = {"X-FIGMA-TOKEN": os.getenv("FIGMA_ACCESS_TOKEN")}
    
        # Get structure: use nodes endpoint if node-id is provided, else full file.
        if node_ids:
            resp = requests.get(f"https://api.figma.com/v1/files/{file_key}/nodes", headers=headers, params={"ids": ",".join(node_ids)})
            data = resp.json()
            # Structure is returned as a dict mapping each node_id to its document.
            structure = {nid: info["document"] for nid, info in data.get("nodes", {}).items()}
        else:
            resp = requests.get(f"https://api.figma.com/v1/files/{file_key}", headers=headers)
            data = resp.json()
            structure = data.get("document", {})
    
        # Recursively traverse a node to collect those with an image fill.
        def collect_image_nodes(node):
            imgs = []
            if isinstance(node, dict):
                if node.get("fills") and isinstance(node["fills"], list):
                    for fill in node["fills"]:
                        if fill.get("type") == "IMAGE" and "imageRef" in fill:
                            imgs.append({
                                "node_id": node.get("id"),
                                "image_ref": fill.get("imageRef"),
                                "bounding_box": node.get("absoluteBoundingBox", {})
                            })
                            break  # one image fill per node is enough
                for child in node.get("children", []):
                    imgs.extend(collect_image_nodes(child))
            return imgs
    
        # Get all image nodes from the structure.
        image_nodes = []
        if node_ids:
            for doc in structure.values():
                image_nodes.extend(collect_image_nodes(doc))
        else:
            image_nodes = collect_image_nodes(structure)
    
        # Fetch image URLs using the node IDs that have image fills.
        image_node_ids = list({img["node_id"] for img in image_nodes if img.get("node_id")})
        if image_node_ids:
            params = {"ids": ",".join(image_node_ids), "format": "png"}
            img_resp = requests.get(f"https://api.figma.com/v1/images/{file_key}", headers=headers, params=params)
            img_mapping = img_resp.json().get("images", {})
        else:
            img_mapping = {}
    
        # Combine the imageRef details with the fetched image URLs.
        for img in image_nodes:
            nid = img.get("node_id")
            img["image_url"] = img_mapping.get(nid)
    
        # Return both structure and images as TextContent
        result = []
        
        # Add structure data
        result.append(types.TextContent(
            type="text",
            text=json.dumps({
                "type": "structure",
                "data": structure
            }, indent=2)
        ))
        
        # Add image data
        result.append(types.TextContent(
            type="text",
            text=json.dumps({
                "type": "images",
                "data": image_nodes
            }, indent=2)
        ))
    
        return result
  • Dispatch logic in the main tool handler (@app.call_tool()) that routes calls to 'figma_design' to the get_figma_design function after input validation.
    elif name == "figma_design":
        if "url" not in arguments:
            return [types.TextContent(
                type="text",
                text="Error: Missing required argument 'url'"
            )]
        return await get_figma_design(arguments["url"])
  • Tool registration in @app.list_tools(), including name, description, and input schema.
    types.Tool(
        name="figma_design",
        description="Get Figma design data including structure and images",
        inputSchema={
            "type": "object",
            "required": ["url"],
            "properties": {
                "url": {
                    "type": "string",
                    "description": "The full Figma design URL",
                }
            },
        },
    ),
  • Input schema definition for the 'figma_design' tool, specifying required 'url' parameter.
        inputSchema={
            "type": "object",
            "required": ["url"],
            "properties": {
                "url": {
                    "type": "string",
                    "description": "The full Figma design URL",
                }
            },
        },
    ),
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool retrieves data but lacks details on permissions, rate limits, error handling, or what 'structure and images' entails (e.g., format, size). This is a significant gap for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste. It is front-loaded with the core purpose and includes essential details ('structure and images') without redundancy. Every word earns its place, making it highly concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description is incomplete. It doesn't explain what 'Figma design data' includes beyond 'structure and images', how results are returned, or behavioral aspects like authentication needs. For a data retrieval tool with rich context (Figma API), more detail is warranted.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with the single parameter 'url' fully documented in the schema as 'The full Figma design URL'. The description adds no additional meaning beyond this, such as URL format examples or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Get') and resource ('Figma design data'), specifying what data is retrieved ('structure and images'). It distinguishes from sibling tools like 'generate_image' (creation vs retrieval) and 'mcp_fetch' (generic vs Figma-specific), though it doesn't explicitly mention these distinctions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing a valid Figma URL), exclusions, or comparisons to siblings like 'mcp_fetch' for general fetching or 'generate_image' for image creation. Usage is implied only by the purpose statement.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/andreasHornqvist/MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server