Skip to main content
Glama

export_diagram

Export .excalidraw diagrams to SVG or PNG images. Convert diagram files into portable image files without a browser or Excalidraw application.

Instructions

Export an .excalidraw file to SVG or PNG image.

Converts an existing .excalidraw diagram into a portable image file without requiring a browser or the Excalidraw application.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
input_pathYesPath to the source .excalidraw file.
output_pathYesDestination file path (e.g., "./arch.svg" or "./arch.png").
formatNoOutput format - "svg" (default) or "png". PNG export requires the cairosvg package (``pip install cairosvg``).svg
scaleNoResolution multiplier for PNG output (default 2.0 = 2×). Has no effect on SVG output.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The @mcp.tool handler for export_diagram — validates format, dispatches to export_to_svg or export_to_png, and returns a result string.
    @mcp.tool
    def export_diagram(
        input_path: str,
        output_path: str,
        format: str = "svg",
        scale: float = 2.0,
    ) -> str:
        """Export an .excalidraw file to SVG or PNG image.
    
        Converts an existing .excalidraw diagram into a portable image file
        without requiring a browser or the Excalidraw application.
    
        Args:
            input_path: Path to the source .excalidraw file.
            output_path: Destination file path (e.g., "./arch.svg" or "./arch.png").
            format: Output format - "svg" (default) or "png".
                    PNG export requires the cairosvg package
                    (``pip install cairosvg``).
            scale: Resolution multiplier for PNG output (default 2.0 = 2×).
                   Has no effect on SVG output.
    
        Returns:
            Path to the exported image file.
        """
        fmt = format.lower().strip()
        if fmt not in ("svg", "png"):
            return f"Error: unsupported format '{format}'. Choose 'svg' or 'png'."
    
        try:
            if fmt == "svg":
                out = export_to_svg(input_path, output_path)
                return f"Exported SVG to: {out}"
            else:
                out = export_to_png(input_path, output_path, scale=scale)
                return f"Exported PNG ({scale}× scale) to: {out}"
        except FileNotFoundError:
            return f"Error: file not found: {input_path}"
        except ImportError as exc:
            return f"Error: {exc}"
        except Exception as exc:  # noqa: BLE001
            return f"Error during export: {exc}"
  • export_to_svg — reads an .excalidraw file, converts to SVG via excalidraw_to_svg(), and writes the output file.
    def export_to_svg(input_path: str | Path, output_path: str | Path) -> Path:
        """Read an .excalidraw file and write a .svg file."""
        data = json.loads(Path(input_path).read_text(encoding="utf-8"))
        svg = excalidraw_to_svg(data)
        out = Path(output_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(svg, encoding="utf-8")
        return out
  • export_to_png — converts an .excalidraw file to PNG using cairosvg (optional dependency), writing the output file at the given scale.
    def export_to_png(input_path: str | Path, output_path: str | Path, scale: float = 2.0) -> Path:
        """Read an .excalidraw file and write a .png file.
    
        Requires the ``cairosvg`` package (``pip install cairosvg``).
        """
        try:
            import cairosvg  # type: ignore[import]
        except ImportError as exc:
            raise ImportError(
                "PNG export requires cairosvg. Install it with: pip install cairosvg"
            ) from exc
    
        data = json.loads(Path(input_path).read_text(encoding="utf-8"))
        svg = excalidraw_to_svg(data)
        out = Path(output_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        cairosvg.svg2png(bytestring=svg.encode(), write_to=str(out), scale=scale)
        return out
  • excalidraw_to_svg — core converter: computes bounding box, renders shapes (rect, ellipse, diamond), arrows, and text into an SVG string.
    def excalidraw_to_svg(data: dict[str, Any]) -> str:
        """Convert an in-memory .excalidraw document to an SVG string."""
        elements = [e for e in data.get("elements", []) if not e.get("isDeleted")]
        bg_color = data.get("appState", {}).get("viewBackgroundColor", "#ffffff")
    
        if not elements:
            return (
                '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300">'
                f'<rect width="400" height="300" fill="{_esc(bg_color)}"/>'
                "</svg>"
            )
    
        min_x, min_y, max_x, max_y = _bounds(elements)
        ox = min_x - PADDING
        oy = min_y - PADDING
        width = max_x - min_x + PADDING * 2
        height = max_y - min_y + PADDING * 2
    
        # Two-pass rendering: shapes first, then text on top
        arrow_types = {"arrow", "line"}
    
        shape_svgs: list[str] = []
        arrow_svgs: list[str] = []
        text_svgs: list[str] = []
        used_colors: set[str] = set()
    
        for el in elements:
            el_type = el.get("type", "")
            if el_type == "rectangle":
                shape_svgs.append(_render_rect(el, ox, oy))
            elif el_type == "ellipse":
                shape_svgs.append(_render_ellipse(el, ox, oy))
            elif el_type == "diamond":
                shape_svgs.append(_render_diamond(el, ox, oy))
            elif el_type in arrow_types:
                arrow_svgs.append(_render_arrow(el, ox, oy, used_colors))
            elif el_type == "text":
                text_svgs.append(_render_text(el, ox, oy))
    
        markers = "\n    ".join(_arrowhead_marker(c) for c in sorted(used_colors))
        defs = f"<defs>\n    {markers}\n  </defs>" if markers else ""
    
        parts = [
            f'<svg xmlns="http://www.w3.org/2000/svg" '
            f'width="{width:.2f}" height="{height:.2f}" '
            f'viewBox="0 0 {width:.2f} {height:.2f}">',
            defs,
            f'<rect width="{width:.2f}" height="{height:.2f}" fill="{_esc(bg_color)}"/>',
        ]
        parts.extend(shape_svgs)
        parts.extend(arrow_svgs)
        parts.extend(text_svgs)
        parts.append("</svg>")
    
        return "\n".join(p for p in parts if p)
  • FastMCP server instantiation — the @mcp.tool decorator on export_diagram registers it as an MCP tool.
    mcp = FastMCP(
        "Excalidraw Architect",
        instructions=(
            "Generate beautiful Excalidraw architecture diagrams with perfect "
            "auto-layout, stateful editing, and architecture-aware component "
            "styling. No API keys required."
        ),
    )
Behavior3/5

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

No annotations are provided, so the description carries the burden. It mentions the conversion process and that no external app is needed, but does not disclose if the input file is modified, error handling, or permission requirements. Basic but not thorough.

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?

Two concise sentences that front-load the core function. No excess words or redundancy.

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

Completeness4/5

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

With an output schema present, return values are assumed documented. The description covers the primary use case and parameters adequately. Slight missing detail about failure modes, but sufficient for a conversion tool.

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?

Input schema covers all parameters with descriptions (100% coverage). The description adds minimal new information beyond the schema, mainly restating the purpose. Baseline 3 is appropriate.

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

Purpose5/5

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

The description clearly states the action (export), the resource format (.excalidraw), and the output formats (SVG/PNG). This distinguishes it from sibling tools like create_diagram or modify_diagram.

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

Usage Guidelines3/5

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

The description implies usage for generating portable images without browser/Excalidraw, but does not explicitly compare with siblings or state when not to use (e.g., for editing). It provides implicit context but lacks clear directives.

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/BV-Venky/excalidraw-architect-mcp'

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