Skip to main content
Glama

daigram

NPM Version License

daigram (/ˈdaɪ.ɡræm/, "diagram" without the middle syllable) is a whiteboard for humans and AI agents, drawing on the same live Excalidraw canvas: each sees, comments on and refines the other's work. Your agent creates architecture diagrams and flowcharts programmatically, sees its own work via screenshots, fixes layout problems, and exports .excalidraw files you can commit next to your code; you edit, comment and chat on the same canvas.

One canvas, three ways to drive it:

  • Agent Skill + CLI — recommended for coding agents (Claude Code, Codex CLI, Cursor, OpenCode): npx -y daigram <command>. Zero config, auto-starts the canvas, composable JSON in/out.

  • MCP Server — tools over stdio for any Model Context Protocol client (Claude Desktop, Cursor, Codex CLI, Antigravity, ...). Speaks MCP 2026-07-28 (server/discover, per-request _meta envelope, tool calls without a handshake) and stays compatible with 2025-era clients that open with initialize.

  • REST API — plain HTTP for LangChain and custom frameworks.

Core drawing runs locally (Node ≥ 20, AGPL-3.0) — no API keys or accounts. Mermaid conversion runs in the local browser canvas; share is optional and uploads an encrypted scene to excalidraw.com by default (or your own instance).

What makes it different

  • Describe a diagram, don't position it. layout_diagram takes nodes, edges and groups and places, sizes and joins them with right-angled arrows (layered layout, up to 100 nodes).

  • Agents check their own work. check_layout reports labels that do not fit, overlaps, arrows through shapes and clipped frames; fit_to_text, route_arrows and the bulk tools fix them.

  • An AI chat on the canvas. Provider-agnostic, with your own key or the server's model, and it can be confined to a single frame.

  • Many canvases, frames and comments. Each canvas has its own address (/c/<id>); comments pin to elements, and the agent reads them and resolves them.

  • Usable on a phone. View, comment and chat; editing stays locked until you choose Edit.

  • Local and self-hostable. Opt-in durable state, headless rendering, MCP over stdio or HTTP, Docker.

Related MCP server: excalidraw-mcp

Demo

AI agent drawing an architecture diagram on a live Excalidraw canvas via MCP

AI agent creates a complete architecture diagram from a single prompt (4x speed).

Table of Contents

What It Is

Ask your agent to "draw the architecture of this service" and it produces a real, editable Excalidraw diagram — not a one-shot image. Because the agent can query, screenshot, and update individual elements, it iterates until labels fit, nothing overlaps, and arrows route cleanly; then it exports the result as a .excalidraw file that lives in your repo and gets updated when the code changes.

Under the hood there are two processes, one product:

  • Canvas server: Excalidraw web UI + REST API + WebSocket real-time sync (default http://127.0.0.1:3000)

  • A thin front-end of your choice: the CLI, the MCP stdio server, or raw HTTP — all drive the same canvas

The canvas server starts itself: canvas-driving CLI commands (and the MCP server on launch) auto-spawn it if nothing is listening. status only inspects the current server state. Set EXCALIDRAW_NO_AUTOSTART=1 to opt out.

How We Differ from the Official Excalidraw MCP

Excalidraw has an official MCP — a chat widget that streams a diagram inline from a single prompt (the model gets two tools: a format reference and create_view). It's great for "draw me a cat" in Claude or ChatGPT. We solve a different problem: giving coding agents a persistent canvas workbench.

Official Excalidraw MCP

This Project

Approach

Prompt in, diagram out (one-shot widget)

Programmatic element-level control (CLI + MCP tools)

State

Checkpoints inside the chat widget

Live canvas with real-time sync and optional restart-safe checkpoints

Diagrams

layout_diagram: describe nodes, edges and groups and it places, sizes and joins them with right-angled arrows (ELK layered layout; up to 100 nodes, 200 edges)

Element CRUD

Declarative re-send with delete markers

Full create / read / update / delete per element

AI sees the canvas

No

describe (structured text) + screenshot (image)

Iterative refinement

Regenerate from checkpoint

Draw → look → adjust → look again, element by element

Layout tools

No

align, distribute, group / ungroup, lock, duplicate

File I/O

No model-facing export

.excalidraw export/import — diagrams as repo artifacts

Snapshot & rollback

Widget-side checkpoints

Named server-side snapshots

Mermaid conversion

No

mermaid / create_from_mermaid

Shareable URLs

Widget-only

share / export_to_excalidraw_url

Viewport control

Camera animations

set_viewport (zoom-to-fit all or selected elements, center on one element, manual zoom)

Works without MCP

No

Yes — CLI + agent skill + REST API

Multi-agent

Single chat

Multiple agents on the same canvas concurrently

TL;DR — The official MCP shows Excalidraw diagrams in your chat. This project gives you and your coding agent a full Excalidraw workbench: a shared canvas you can both draw on, inspect, refine, and commit to your repo.

History

daigram started as a fork of mcp_excalidraw 2.2.0 and has since added the features above. Version 0.1.0 is the first release under the daigram name, so the numbering starts again here. The release notes of the original project (v1.1 to v2.2: the CLI, headless rendering, MCP 2026-07-28, durable state) are on its releases page.

Installation

The only prerequisite is Node.js ≥ 20.

Easiest: let your agent install it

Copy this into your coding agent — it installs the portable skill into the project/global skill directory that agent already knows how to use, then verifies it by drawing a test diagram:

Install the Excalidraw canvas toolkit so you can draw diagrams for me:

1. Choose the right skill directory for this agent and scope (project or global).
2. Run: npx -y daigram install-skill --dir <that-skills-directory>
3. Read the installed excalidraw-skill/SKILL.md so you know the drawing workflow.
4. Start the canvas with: npx -y daigram start
   then tell me I can open http://127.0.0.1:3000 to watch you draw (optional).
5. Draw a small test diagram — two labeled boxes connected by an arrow — take a
   screenshot, and show me the result to confirm everything works.

Manual install

You are...

Install with

Then

Modern coding agent

npx -y daigram install-skill --dir <skills-root>

Let the agent choose project/global scope and its skill root

Claude Code shortcut

npx -y daigram install-skill

Installs to ~/.claude/skills for backward compatibility

Codex shortcut

npx -y daigram install-skill --target codex

Installs to ~/.codex/skills for backward compatibility

MCP client user (Claude Desktop, Cursor, ...)

Add the npx config below

See Configure MCP Clients

CLI user / scripting

Nothing — npx -y daigram <command>

See CLI Reference

Contributor / from source

git clone + npm ci + npm run build

See Quick Start (From Source / Docker)

There is no separate server setup: any drawing command auto-starts the local canvas server on http://127.0.0.1:3000.

60-Second Quick Start (CLI)

No clone, no config:

# start the canvas (drawing commands auto-start it too) and open it
npx -y daigram start
open http://127.0.0.1:3000   # optional: watch live (only mermaid needs the tab)

# draw something
echo '[
  {"id":"api","type":"rectangle","x":100,"y":100,"width":160,"height":80,"text":"API Server","backgroundColor":"#a5d8ff"},
  {"id":"db","type":"rectangle","x":400,"y":100,"width":160,"height":80,"text":"Database","backgroundColor":"#99e9f2"},
  {"type":"arrow","x":0,"y":0,"startElementId":"api","endElementId":"db","text":"SQL"}
]' | npx -y daigram add

# let your agent see its work
npx -y daigram describe
npx -y daigram screenshot --out diagram.png

# diagrams as repo artifacts
mkdir -p docs
npx -y daigram export --out docs/architecture.excalidraw

# or straight into an Obsidian vault (.md extension → Obsidian Excalidraw plugin format)
npx -y daigram export --out ~/vault/diagrams/architecture.excalidraw.md

Give your agent the full playbook:

npx -y daigram install-skill --dir <skills-root>
npx -y daigram install-skill --print-source  # inspect bundled source path

Security note: The canvas server binds 127.0.0.1 only by default. If you expose it on a network interface (HOST=0.0.0.0), put network-level access controls in front — the API has no built-in authentication.

Cross-site protection

Any website you visit can send requests to localhost, and a WebSocket ignores CORS. The /api routes and the WebSocket therefore refuse browser requests that come from another site (Sec-Fetch-Site), carry a foreign Origin, or, on a loopback bind, use a Host name other than localhost, 127.0.0.1 or [::1] (DNS rebinding). The canvas page, the CLI and curl are unaffected. To let another web app call the API, list its origin in ALLOWED_ORIGINS. On a non-loopback bind (HOST=0.0.0.0, Docker) the Host name check is skipped, so put authentication in front. For npm run dev, no setting is needed: the Vite proxy keeps the page's own origin.

Updates from the CLI or an agent are held while you drag, draw or edit text, and applied in order when you finish. An unfinished multi-point line or an open text box holds them until you finish it, with no time limit; only queued viewport and export requests are dropped after 10 seconds.

Frames

Every top-level frame gets a tab along the bottom. A tab scrolls and zooms to its frame on click and follows the view as you pan. Drag a tab to reorder it: the order is stored on the frames and has nothing to do with where they sit, so moving a frame moves no tab and moving a tab moves no frame. + Frame adds a 1600x1000 frame after the last one, in free space; Make frame from selection wraps the selected shapes in a frame; double-click a tab to rename it; its menu fits the frame to its shapes or deletes it with its shapes after a confirmation (Excalidraw's own Delete key removes only the frame). A tab shows how many open comments are inside its frame, and Focus dims everything outside the current frame. Selecting a tab or adding a frame sets the page's #frame=<name> link, and opening a link with #frame=<name or id> scrolls to that frame once the scene has loaded. A link to a frame that was renamed or deleted is ignored.

Agents work one frame at a time: frame list, describe, add, apply, update, get and query with --frame <name>, screenshot --frame <name> and frame reorder <name> <position> (tab order only). With --frame, every position the agent reads or writes is relative to the frame's top-left corner, which is (0, 0) and never negative; add, apply and update grow the frame right and down to hold shapes you add, move or resize, because a frame clips what lies outside it. (Stored coordinates are still canvas coordinates, as in Excalidraw.) Shapes may also sit on no frame. Frames sync, undo and export like any other shape; only the tab order is stored beyond them.

Comments

Right-click the canvas to leave a comment on that point, or on the element under it; the pin follows the element when it moves. Shift+right-click keeps Excalidraw's own menu. Click a pin for its thread, where you reply, resolve, reopen or delete. The Comments button lists them all and copies a ready prompt for your agent.

The agent works through daigram comment list --open, which gives each thread with the element it is on, then comment resolve <id>... --note "<what changed>". It can also add a question and reply. Resolving several at once is one call.

Comments sit beside the scene: not in exports, snapshots or undo, and Clear Canvas leaves them. They persist with EXCALIDRAW_DATA_DIR. REST is /api/comments, and the MCP tools above do the same as the CLI (except delete, which stays in the UI and CLI); touch devices cannot add one from the canvas.

On a phone

Below 700 px wide the header is one slim row (☰ canvases, connection dot, Edit, Comments, Chat, ⋯ for Sync, Clear canvas and site links). The canvases panel slides over the canvas, and Chat and Comments rise from the bottom and leave the top of the canvas in view. On a touch screen the canvas starts locked: you can pan, zoom, read, comment and chat, and a stray touch cannot move a shape, and tapping does not select one. Edit unlocks the drawing tools and Done locks it again; the choice is kept while you switch canvases. Touch devices are locked in either orientation (a phone turned sideways gets the wide header with the same Edit/Done button), and Clear Canvas is off while locked.

Multiple canvases

One server holds several canvases, each with its own scene, comments, snapshots and tabs. The page for a canvas is /c/<id>, its API is /c/<id>/api/... and its WebSocket is /c/<id>; without the prefix you get the canvas main. GET /api/canvases lists them, POST /api/canvases {name} creates one (the id is a slug of the name), PUT /api/canvases/<id> {name} renames, POST /api/canvases/<id>/duplicate {name?} copies the scene and comments (not snapshots), and DELETE /api/canvases/<id> removes one. A removed canvas is moved to canvases/.trash/ in the data directory, not deleted; main cannot be removed. With EXCALIDRAW_DATA_DIR, main stays in the directory itself and the others sit in canvases/<id>/. In the page, Canvases in the header opens a side panel to switch (without reloading the page; Back and Forward work), create, rename, duplicate and delete canvases. The CLI and the MCP server work on one canvas at a time: --canvas <id> or CANVAS_ID. A host in front of the server can answer GET /api/nav with {links:[{label,href}]} (site-relative links); the header shows them next to the title. The server itself returns none.

Built-in AI

daigram ai ask "<message>" [--frame <name>] asks a model to edit the canvas, so no local coding agent is needed. It is off until you set the provider. The key is read from the environment of the process that calls the model, and never reaches the browser, the scene or the model; a canvas server started for you by ai ask is not given AI_* variables.

Variable

Meaning

AI_PROVIDER

anthropic or openai-compatible (OpenAI, OpenRouter, Ollama, LM Studio, vLLM)

AI_MODEL

Model name

AI_API_KEY

API key (optional for local openai-compatible endpoints)

AI_BASE_URL

Required for openai-compatible, for example https://api.openai.com/v1; optional for anthropic

AI_MAX_STEPS, AI_MAX_OUTPUT_TOKENS

Limits per run (default 12 and 8192; lower the second for a model that caps replies below that). A reasoning model spends output tokens on thinking, so raise AI_MAX_OUTPUT_TOKENS for it

AI_REQUEST_EXTRA

A JSON object added to every model request, for provider-specific fields, for example {"reasoning_effort":"low"} for GLM (its default effort is max); a field only helps if the model honours it; it cannot override the runner's own fields

The model gets canvas tools only: describe, query, create, update and delete shapes, frames and comments. It has no shell, files or network, and cannot clear the canvas, delete a frame or import and export scenes. Canvas text and comments are treated as data, not instructions. --frame holds it to one frame, in that frame's own coordinates: tool arguments are checked, so it cannot delete elements or touch comments outside the frame, and it cannot add frames or comments. Each tool call it makes is its own undo step.

In the browser, Chat in the header opens a drawer: type a request and the reply, the tool steps it runs and the changes to the canvas appear as it works, with Stop to cancel. It offers to keep the model to the frame you are looking at (on by default). The chat keeps what was said, not the tool steps (the model looks at the canvas again each message), and it is kept in the browser, per canvas, across reloads until 12 hours without a message, or New chat. Closing the drawer does not stop a run; leaving the page does.

The canvas server also exposes it over HTTP, for a chat UI or another client: GET /api/ai/status, POST /api/ai/runs {message, frame?, history?} (history is earlier {role, text} turns; 202 with a runId, 409 while another run is active, 503 when AI is not configured), GET /api/ai/runs/:id/events (server-sent events: text, tool, done, error; a late subscriber replays them) and POST /api/ai/runs/:id/stop. A request can bring its own model instead of the server's: X-AI-Provider (anthropic or openai-compatible), X-AI-Model, X-AI-Key and, for openai-compatible, X-AI-Base-Url, on GET /api/ai/status and POST /api/ai/runs (all or none; an incomplete set is a 400, never a run on the server's model; the server's AI_REQUEST_EXTRA is not applied to it). Headers, not the body, so a key is never in the saved chat. The chat's Connect panel uses this: pick the server's model or your own key (kept in this browser's storage only) and see how to connect an agent over MCP, which works alongside the chat. AI_REQUEST_HOSTS (comma-separated host names, https only; none allows no request model) limits where such a model may live. Unset, any URL is accepted, which suits a server only you reach; where others can, set it, because the server calls that URL itself. One run at a time per canvas (the routes also work under /c/<id>/api/ai/..., and a run draws on its own canvas); it keeps going if the subscriber disconnects, until it finishes or is stopped, so a UI should call stop when it is closed. These routes use your API key and, like the rest of /api, have no login of their own: on a non-loopback bind (HOST=0.0.0.0, Docker) put authentication in front before setting AI_*. These routes sit behind the same cross-site guard as the rest of /api. Runs call the canvas over HTTP, so EXPRESS_SERVER_URL must point at the server itself (the default does, on the default port); the server warns at startup when it does not.

Agent Skill

The skill at skills/excalidraw-skill/ teaches agents the full workflow — layout planning, the screenshot-verify-fix quality loop, arrow routing, anti-patterns, snapshots, and file I/O. It works through the CLI (preferred, zero setup), MCP tools (if configured), or raw REST — in that order.

npx -y daigram install-skill --dir <skills-root>

The command copies the bundled excalidraw-skill/ directory into <skills-root>/excalidraw-skill. Let your agent choose whether that root should be project-level or global. Re-running install-skill upgrades in place — it replaces the target directory, so files removed upstream don't linger.

Where the skill shines:

  • Diagrams as code artifacts: export .excalidraw files into the repo, commit them, re-import + refine when the architecture changes.

  • Obsidian vaults: export with a .excalidraw.md extension and the file opens natively in the Obsidian Excalidraw plugin — no compatibility-mode warning, block references and sync work; import reads both plain and lz-string-compressed vault files back.

  • Self-verifying diagrams: the agent screenshots its own work and fixes truncation/overlap before calling it done.

  • No-MCP environments: CI jobs, plain shells, and frameworks get the same capabilities through the CLI.

CLI Reference

npx -y daigram <command> or (after npm i -g daigram) daigram <command>.

Conventions: JSON results on stdout — except describe (plain text by design) and raw-content output when --out is omitted (export prints the scene JSON, screenshot --format svg prints SVG). Diagnostics on stderr. Exit codes: 0 ok, 1 error, 2 usage, 3 canvas unreachable, 4 browser tab required (only mermaid and screenshot --renderer browser). Canvas URL from EXPRESS_SERVER_URL or --url; --canvas <id> (or CANVAS_ID) picks the canvas, main by default. Canvas-driving commands auto-start the server; status only reports current state. Explicit start overrides the EXCALIDRAW_NO_AUTOSTART=1 opt-out (it's user intent, not auto-start).

Command

Description

start / stop / status

Manage the canvas server (detached; stop identity-checks the live server via /health before signaling)

add [file|-]

Batch-create elements from a JSON array (file or stdin); --one '{...}' for a single element

apply [file|-]

One-call multi-op patch: {"create":[...],"update":[{"id":"a","set":{...}}],"delete":["id"]}

get <id> / delete <id...>

Read / remove elements

update <id> --set '{...}'

Update an element

query

--type, --bbox x0,y0,x1,y1, --filter k=v (typed, nested keys), --filter-json '{...}'

selection

Current canvas selection: selectedElementIds and count

describe

AI-readable scene summary (plain text)

screenshot

Render the canvas headless (no browser tab): --out f.png|f.svg, --format png|svg, --scale 1-4, --dark, --padding N, --no-background, --ids a,b, --frame <id>, --no-embed-fonts, --embed-scene (editable PNG); --renderer browser uses an open tab instead

render [file|-]

Render a .excalidraw / .excalidraw.md / embedded-scene PNG file to PNG/SVG offline — no canvas server, same flags as screenshot

export [--out f.excalidraw] [--format json|obsidian] / import [file|-] [--replace]

Scene file I/O — a .md out path writes Obsidian's .excalidraw.md format; import also reads PNGs with embedded scenes

mermaid [file|-]

Mermaid → canvas (browser tab required)

canvases list|create|rename|duplicate|delete

Manage canvases (see Multiple canvases)

snapshot save|list|restore <name>

Named snapshots; Clear Canvas and a replace also keep the last three scenes they discarded as auto-… snapshots

comment list|add|reply|resolve|reopen|delete

Read and answer comments pinned on the canvas

ai ask <message> [--frame <name>]

Ask a model to edit the canvas (see Built-in AI)

frame list|add|reorder|delete

The canvas's frames. reorder <name|id> <position> changes tab order only (1 = first tab) and moves nothing. list and add report canvasX/canvasY in canvas coordinates; --frame <name|id> on add, apply, update, get, query, describe, screenshot and comment list is relative to the frame's top-left corner, which is (0, 0)

arrange align|distribute|group|ungroup|lock|unlock|duplicate

Layout ops (--ids a,b,c, --to left|horizontal|...)

share

Encrypted upload → shareable URL (excalidraw.com by default; configurable self-hosted target)

clear --yes

Wipe the canvas

install-skill [--dir <skills-root>]

Install the portable agent skill

Labels and arrow bindings use the agent-friendly format everywhere in the CLI: "text" on any shape, "startElementId"/"endElementId" on arrows — normalization is automatic. For a native frame, add a "type":"frame" element with a "name" and set "frameId" on its children.

Headless Rendering

screenshot, export_to_image and get_canvas_screenshot render without a browser. Inside the canvas server, the scene is prepared with the canvas tab's own code (label sizing, wrapping and centering, defaults) and Excalidraw's own exportToSvg draws it under Node (a small jsdom shim supplies the DOM it expects, and text is measured with the bundled fonts' real glyph widths); resvg rasterizes the SVG to PNG. The output is what the Excalidraw canvas draws — same SVG structure as a browser export, text within half a pixel — and it is deterministic: an unchanged scene renders to byte-identical SVG and PNG, so committed images stay diff-clean.

  • Fonts: Excalifont, Virgil, Cascadia Code and Liberation Sans ship as TTFs in assets/fonts (all SIL OFL 1.1; see assets/fonts/LICENSES.md). SVGs embed the faces they use, so they look right in browsers, GitHub and editors. Nunito, Lilita One and Comic Shanns render with the closest bundled face for now. Text in other scripts (CJK, emoji) falls back to the machine's fonts, with a warning.

  • Options (CLI flags / REST body / MCP params): background, dark, scale 1–4 (PNG), padding, elementIds or frameId to render a subset, embedFonts (CLI/REST only), embedScene (PNG only, default false). EXCALIDRAW_RENDER_MAX_DIM (default 8192) caps the PNG's largest side.

  • --renderer browser asks an open canvas tab to render instead (the pre-2.1 path). Useful for a second opinion; it is slower and the tab's unsynced edits are discarded first.

  • Offline: render docs/arch.excalidraw --out docs/arch.png needs no canvas server at all — a natural fit for CI jobs that keep images next to committed diagrams.

  • Still browser-bound: Mermaid conversion (mermaid, create_from_mermaid) and set_viewport.

The renderer bundle is built by npm run build:server (dist/render/excalidraw-node.mjs); npm run test:render exercises it without a browser.

Configure MCP Clients

The MCP server runs over stdio (or over HTTP at /mcp, see below). The simplest config is npx — no clone, no absolute paths, and the canvas auto-starts. If your MCP client and canvas are on different machines, start with Remote Canvas and HTTP-Only MCP Clients.

Environment Variables

Variable

Description

Default

EXPRESS_SERVER_URL

URL of the canvas server

http://127.0.0.1:3000

CANVAS_ID

Canvas the CLI and the MCP server work on (--canvas for the CLI)

main

ENABLE_CANVAS_SYNC

Enable real-time canvas sync

true

EXCALIDRAW_NO_AUTOSTART

Set 1 to disable canvas auto-start

(unset)

EXCALIDRAW_HEADERS

JSON object of extra HTTP headers sent on every request to the canvas server, e.g. {"Authorization":"Bearer <secret>"}. For a canvas behind a reverse proxy that expects a header. See Extra Request Headers

(unset)

EXCALIDRAW_EXPORT_DIR

Directory MCP file tools may read and write (symlinks resolved; .excalidraw, .json, .md, .png, .svg files only)

current working dir

EXCALIDRAW_RENDER_MAX_DIM

Largest side of a headless PNG, in pixels

8192

EXCALIDRAW_PNG_WORKER_TIMEOUT_MS

Timeout for the isolated PNG rasterizer, in milliseconds

120000

EXCALIDRAW_DATA_DIR

Optional local durable-state directory

(unset; in-memory)

EXCALIDRAW_SHARE_UPLOAD_URL

Where share uploads the encrypted scene (an excalidraw-json POST endpoint)

https://json.excalidraw.com/api/v2/post/

EXCALIDRAW_SHARE_BASE_URL

Excalidraw app that share links open in

https://excalidraw.com

PORT / HOST

Canvas server bind address

3000 / 127.0.0.1

ALLOWED_ORIGINS

Comma-separated extra origins allowed to call the canvas API from a browser

none

LOG_LEVEL

Log verbosity (error, warn, info, debug)

info

LOG_FILE_PATH

Log file location

~/Library/Logs/excalidraw-mcp.log (macOS), $XDG_STATE_HOME/excalidraw-mcp/excalidraw.log (Linux), %LOCALAPPDATA%\Excalidraw-MCP\excalidraw.log (Windows)

Extra Request Headers

If the canvas sits behind a reverse proxy that expects a header, set EXCALIDRAW_HEADERS to a JSON object. The CLI and MCP server add these headers to every canvas API request:

export EXPRESS_SERVER_URL=https://canvas.example.com
export EXCALIDRAW_HEADERS='{"Authorization":"Bearer <secret>"}'
  • The headers are not sent on the /health identity probe, so the proxy must serve /health without requiring them; otherwise the CLI reports a foreign service.

  • They are refused over plain http:// to a non-local host (set EXCALIDRAW_ALLOW_INSECURE_HEADERS=1 on a trusted network, e.g. http://host.docker.internal).

  • Redirects are not followed while they are set, so the headers cannot leak to another host. Point EXPRESS_SERVER_URL at the final URL.

  • Hop-by-hop headers (Host, Content-Length, Connection, ...) cannot be set. Invalid configuration fails at once (the MCP server exits at startup) with a message that never echoes header values.

Remote Canvas and HTTP-Only MCP Clients

There are two separate connections:

  • MCP client ↔ MCP process: an MCP client that supports local commands launches the stdio MCP process and owns its stdin/stdout.

  • MCP process ↔ canvas: EXPRESS_SERVER_URL points to the canvas server's REST API. The browser UI uses a WebSocket on that same server and port.

The canvas server also serves MCP over HTTP (stateless Streamable HTTP, no /sse), so a client that connects by URL needs no local process: /mcp works on the main canvas and /c/<id>/mcp on that canvas. For example claude mcp add --transport http excalidraw http://127.0.0.1:3000/mcp. The endpoint has the same cross-site protection as /api, and the tools call the canvas server at EXPRESS_SERVER_URL, so that must point at the server itself (the default does, on the default port).

To keep a remote canvas on its default loopback-only binding, run the MCP process on your workstation and tunnel the canvas port to that machine:

# Keep this running. The remote canvas remains bound to remote 127.0.0.1:3000.
ssh -N -L 13000:127.0.0.1:3000 user@canvas-host

Then configure the local MCP process against the local end of the tunnel. The URL port must match the first port in the SSH command:

{
  "mcpServers": {
    "excalidraw": {
      "command": "npx",
      "args": ["-y", "daigram"],
      "env": {
        "EXPRESS_SERVER_URL": "http://127.0.0.1:13000",
        "EXCALIDRAW_NO_AUTOSTART": "1"
      }
    }
  }
}

Start the tunnel before the MCP client and leave it open while tools run. In this example the MCP process and browser run on the workstation, so both can use http://127.0.0.1:13000; the WebSocket also follows the page's host and port. 127.0.0.1 always means the machine or container running that process. If the MCP process runs in a container, the workstation's loopback tunnel is not that container's loopback: run the tunnel in the same network namespace as the MCP process, or configure a canvas address that is reachable from the container and protect any listener exposed beyond loopback.

If an Open WebUI, LM Studio, or other MCP client setup accepts only HTTP-based MCP connections, it cannot use the canvas URL in place of MCP. It needs a separately configured stdio-to-HTTP MCP bridge in front of this stdio server; bridge setup and client transport support are outside this project.

As a direct-LAN alternative, run the canvas process with an explicit non-loopback bind, for example from a built source checkout: HOST=0.0.0.0 PORT=3000 node dist/server.js. Then set the MCP process's EXPRESS_SERVER_URL to http://canvas-host:3000. The canvas container already binds HOST=0.0.0.0, and Compose publishes 3000:3000; scope that port mapping or bind it to a trusted interface when possible. The CLI start command only auto-starts a loopback canvas, so it is not the way to create this LAN listener. The source default remains HOST=127.0.0.1.

Direct LAN access exposes the canvas REST and WebSocket APIs without authentication; the cross-site check does not replace it. Restrict that port to a trusted network/VPN with firewall or network-level access controls; do not expose it to the public internet.

Durable canvas state

Set EXCALIDRAW_DATA_DIR to recover elements, server-known image files, and named snapshots after a canvas-server restart. From a source checkout after npm run build:

EXCALIDRAW_DATA_DIR=/absolute/private/canvas-data \
  node dist/bin.js start

When the variable is unset, behavior and API semantics remain in-memory and no durable-state directory is created. When enabled, the directory contains a versioned canvas-state-v1.json checkpoint, a blobs/ directory, and a runtime canvas-state.lock/ ownership directory. Image payloads are stored once as immutable file-id blobs at a path-safe SHA-256 of each file ID; checkpoints record a separate content SHA-256 and contain references only. A new blob is flushed and atomically published before any checkpoint is allowed to reference it. Each accepted mutation flushes a temporary checkpoint and atomically renames it before the server broadcasts or acknowledges the mutation. Serialization recursively sorts object keys, preserves scene stacking order, and stores file and named-snapshot metadata in stable ID/name order. Invalid JSON, unsupported schemas, non-regular checkpoint paths, missing blobs, and blob-integrity failures stop startup rather than replacing recoverable state with an empty scene.

Two REST rules are stricter in durable mode, and both return 409: upload an image's file (POST /api/files) before the element that references it, and never re-upload a file ID with different content. The canvas tab and import already work this way.

If the checkpoint has already been renamed into place but the final directory flush fails, the request fails without a success broadcast and further mutations are refused until restart. The published scene stays in memory so it agrees with the file on disk; the failed request may appear in the recovered scene. On Windows, Node.js does not provide directory fsync, so the store flushes file contents and uses atomic publication without claiming the same directory durability barrier.

The data-directory lock grants one process exclusive ownership of that durable state, including when servers use different ports. It stores one token-specific owner file so stale-lock reclamation cannot delete a newer owner's evidence. The existing pidfile has a separate job: it identifies a listening process for start / stop lifecycle commands. Local filesystems and one writer are supported; network filesystems, shared multi-writer access, automatic blob garbage collection, databases, and cloud persistence are out of scope.

Privacy: durable state contains the diagram and embedded image payloads. Keep the directory outside repositories and shared folders, restrict its permissions, and mount it as a private writable volume when using containers.


Claude Desktop

Config location:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • Linux: ~/.config/Claude/claude_desktop_config.json

npx (recommended)

{
  "mcpServers": {
    "excalidraw": {
      "command": "npx",
      "args": ["-y", "daigram"]
    }
  }
}

Local (node)

{
  "mcpServers": {
    "excalidraw": {
      "command": "node",
      "args": ["/absolute/path/to/daigram/dist/index.js"],
      "env": {
        "EXPRESS_SERVER_URL": "http://127.0.0.1:3000",
        "ENABLE_CANVAS_SYNC": "true"
      }
    }
  }
}

Docker

{
  "mcpServers": {
    "excalidraw": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-e", "EXPRESS_SERVER_URL=http://host.docker.internal:3000",
        "-e", "ENABLE_CANVAS_SYNC=true",
        "daigram-mcp:latest"
      ]
    }
  }
}

Claude Code

npx (recommended)

claude mcp add excalidraw --scope user -- npx -y daigram

Tip: for coding agents, the skill + CLI often beats MCP config entirely — let the agent pick its skill root, then run npx -y daigram install-skill --dir <skills-root>.

Local (node) - User-level (available across all projects):

claude mcp add excalidraw --scope user \
  -e EXPRESS_SERVER_URL=http://127.0.0.1:3000 \
  -e ENABLE_CANVAS_SYNC=true \
  -- node /absolute/path/to/daigram/dist/index.js

Docker

claude mcp add excalidraw --scope user \
  -- docker run -i --rm \
  -e EXPRESS_SERVER_URL=http://host.docker.internal:3000 \
  -e ENABLE_CANVAS_SYNC=true \
  daigram-mcp:latest

Manage servers:

claude mcp list              # List configured servers
claude mcp remove excalidraw # Remove a server

Cursor

Config location: .cursor/mcp.json in your project root (or ~/.cursor/mcp.json for global config)

npx (recommended)

{
  "mcpServers": {
    "excalidraw": {
      "command": "npx",
      "args": ["-y", "daigram"]
    }
  }
}

Docker

{
  "mcpServers": {
    "excalidraw": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-e", "EXPRESS_SERVER_URL=http://host.docker.internal:3000",
        "-e", "ENABLE_CANVAS_SYNC=true",
        "daigram-mcp:latest"
      ]
    }
  }
}

Codex CLI

npx (recommended)

codex mcp add excalidraw -- npx -y daigram

Docker

codex mcp add excalidraw \
  -- docker run -i --rm \
  -e EXPRESS_SERVER_URL=http://host.docker.internal:3000 \
  -e ENABLE_CANVAS_SYNC=true \
  daigram-mcp:latest

Manage servers:

codex mcp list              # List configured servers
codex mcp remove excalidraw # Remove a server

OpenCode

Config location: ~/.config/opencode/opencode.json or project-level opencode.json

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "excalidraw": {
      "type": "local",
      "command": ["npx", "-y", "daigram"],
      "enabled": true
    }
  }
}

Antigravity (Google)

Config location: ~/.gemini/antigravity/mcp_config.json

{
  "mcpServers": {
    "excalidraw": {
      "command": "npx",
      "args": ["-y", "daigram"]
    }
  }
}

Notes

  • Docker networking: Use host.docker.internal to reach the canvas server running on your host machine. On Linux, you may need --add-host=host.docker.internal:host-gateway or use 172.17.0.1. The Docker MCP image sets EXCALIDRAW_NO_AUTOSTART=1 (it has no frontend build) — run the canvas as its own container.

  • Canvas persistence: By default, elements and named snapshots are held in memory and are lost on server restart. Set EXCALIDRAW_DATA_DIR for restart recovery of elements, server-known image files, and named snapshots (see Durable canvas state). Use export to save a standalone .excalidraw file; taking a snapshot alone does not provide restart recovery in the default in-memory mode.

MCP Tools

Category

Tools

Element CRUD

create_element, get_element, update_element, delete_element, delete_elements, query_elements (limit, offset, fields to page), batch_create_elements, duplicate_elements (true copy: labels, groups and links between the copies)

Layout

align_elements, distribute_elements, move_elements, reorder_elements (stacking order), fit_to_text (grow shapes to their labels), route_arrows (right-angled connectors round other shapes), group_elements, ungroup_elements, lock_elements, unlock_elements

Scene Awareness

describe_scene, check_layout (labels that do not fit, overlaps, arrows through shapes, cramped or oversized shapes, clipping), get_canvas_screenshot, get_selection

File I/O

export_scene, import_scene, export_to_image, export_to_excalidraw_url, create_from_mermaid

State Management

clear_canvas, snapshot_scene, restore_snapshot

Frames

list_frames, add_frame (around wraps existing elements), move_elements_to_frame, reorder_frame; frame on describe_scene, batch_create_elements, update_element, get_element and query_elements

Comments

list_comments, add_comment, reply_to_comment, resolve_comments, reopen_comment

Viewport

set_viewport

Design Guide

read_diagram_guide

Resources

get_resource

get_selection / CLI selection return selectedElementIds and count. Select elements in an open canvas tab first; among connected tabs, the last selection change wins. With no selection, the list is empty. Selection is not persisted, even in durable mode.

MCP file paths must stay inside EXCALIDRAW_EXPORT_DIR after symlink resolution; broken symlinks are refused. export_scene accepts .excalidraw, .json and .md; import_scene also accepts embedded-scene .png; export_to_image accepts .png or .svg matching its format. These restrictions do not apply to CLI file I/O.

Full schemas are discoverable via tools/list or in skills/excalidraw-skill/references/cheatsheet.md.

Viewport group focus can tune framing with viewportZoomFactor:

{
  "scrollToElementIds": ["id1", "id2", "id3"],
  "viewportZoomFactor": 0.85
}

scrollToElementIds zooms to fit every requested element, while scrollToElementId centers one element without changing the current zoom. Specify only one viewport mode per request. viewportZoomFactor accepts values greater than 0 and at most 1.

Quick Start (From Source / Docker)

From source (Node >= 20):

npm ci
npm run build
PORT=3000 npm run canvas          # canvas server (terminal 1)
node dist/index.js                # MCP server over stdio (terminal 2, usually launched by your MCP client)
node dist/bin.js status           # or drive the CLI straight from the build

Docker canvas server (run these from packages/core):

docker build -f Dockerfile.canvas -t daigram-canvas .
docker run -d -p 3000:3000 --name daigram-canvas daigram-canvas:latest

MCP server image: build it with docker build -t daigram-mcp ., then use daigram-mcp:latest (stdio; point EXPRESS_SERVER_URL at the canvas container).

Testing

CLI Smoke Test

npx -y daigram start
npx -y daigram status
npx -y daigram add --one '{"type":"rectangle","x":100,"y":100,"width":300,"height":200}'
npx -y daigram describe

Canvas Smoke Test (HTTP)

curl http://127.0.0.1:3000/health

Regression Checks

npm test builds the server and runs seven suites, each also available on its own:

npm test
npm run test:mcp      # MCP stdio wire protocol (see below)
npm run test:bind     # default loopback bind, duplicate-start refusal
npm run test:render   # headless renderer, export order keys, scene-prep stability
npm run test:state    # atomic import and snapshot restore, sync validation
npm run test:durable  # restart recovery, checkpoint failures, directory ownership
npm run test:share    # default and self-hosted share targets
npm run test:paths    # MCP file containment, symlinks, allowed file types

Canvas Browser Regression Tests

These Chromium tests build the app and start an isolated localhost server. They cover frame reload/reconnect, mixed scenes, failed-load sync protection, stale responses, clearing/deletion, Mermaid imports, SVG export, dropped images, and text measurement after fonts load. They refuse to reuse an existing server; set CANVAS_TEST_PORT if port 51910 is occupied.

npx playwright install chromium
npm run type-check:frontend
npm run test:canvas

MCP Stdio Wire Test

Drives dist/index.js with raw JSON-RPC frames and checks both protocol eras: server/discover, tool calls sent without any handshake, refusal of unsupported protocol revisions and malformed _meta envelopes, and the legacy initialize path.

npm run test:mcp

MCP Smoke Test (MCP Inspector)

List tools:

npx @modelcontextprotocol/inspector --cli \
  -e EXPRESS_SERVER_URL=http://127.0.0.1:3000 \
  -e ENABLE_CANVAS_SYNC=true -- \
  node dist/index.js --method tools/list

Create a rectangle:

npx @modelcontextprotocol/inspector --cli \
  -e EXPRESS_SERVER_URL=http://127.0.0.1:3000 \
  -e ENABLE_CANVAS_SYNC=true -- \
  node dist/index.js --method tools/call --tool-name create_element \
  --tool-arg type=rectangle --tool-arg x=100 --tool-arg y=100 \
  --tool-arg width=300 --tool-arg height=200

Frontend Screenshots (agent-browser)

If you use agent-browser for UI checks:

agent-browser install
agent-browser open http://127.0.0.1:3000
agent-browser wait --load networkidle
agent-browser screenshot /tmp/canvas.png

FAQ

How is this different from the official Excalidraw MCP?

The official Excalidraw MCP is a chat widget: you prompt, it streams a diagram into the conversation (the model gets two tools). This project is a workbench for you and your coding agents: a persistent local canvas with element-level create/read/update/delete, layout tools, screenshots the model can see, snapshots, and .excalidraw file I/O — driveable via CLI, MCP, or REST. See the full comparison table.

Which AI tools does it work with?

Claude Code, Claude Desktop, Cursor, Codex CLI, OpenCode, and Google Antigravity are documented below — but any agent that can run shell commands can use the CLI, any MCP client can use the MCP server, and anything else (LangChain, custom apps) can use the REST API.

Can the AI actually see the diagram it drew?

Yes — that's the core feature. describe returns a structured text summary (ids, positions, labels, connections) and screenshot returns a rendered PNG. Agents use both to catch truncated labels, overlaps, and bad arrow routing, then fix them element by element.

Do I need a browser open?

No. Screenshots and PNG/SVG exports render headless inside the canvas server (see Headless Rendering), and everything else — creating, querying, updating elements, .excalidraw files — never needed one. Only two things still need an open tab: Mermaid conversion (it lays out in the browser) and viewport control (it moves a camera). The CLI exits with code 4 and tells you when that is the case. Opening the URL is still the way for a human to watch the agent draw.

Are my diagrams persistent?

By default the canvas is in-memory (restart = blank canvas). Set EXCALIDRAW_DATA_DIR for automatic local restart recovery of elements, server-known image files, and named snapshots. Portable, reviewable artifacts should still be exported as .excalidraw files and committed to your repo when appropriate.

share encrypts the scene locally with AES-GCM before uploading; the decryption key is only in the URL fragment, which excalidraw.com's server never sees. Anyone you give the full link to can view the diagram.

Yes. Set EXCALIDRAW_SHARE_UPLOAD_URL to your storage backend's scene endpoint and EXCALIDRAW_SHARE_BASE_URL to your Excalidraw app. Any backend that speaks the excalidraw-json API works, for example alswl/excalidraw-storage-backend, whose endpoint is <storage>/api/v2/scenes/:

EXCALIDRAW_SHARE_UPLOAD_URL=https://draw.example.com/api/v2/scenes/ \
EXCALIDRAW_SHARE_BASE_URL=https://draw.example.com \
  npx -y daigram share

Your app must load #json= links from that same backend (for the alswl fork: VITE_APP_BACKEND_V2_GET_URL).

Does it need an API key or cloud service?

No API key is required. Core drawing runs locally (AGPL-3.0). Outbound traffic is limited to the optional share upload to excalidraw.com (or your own instance, see above) and, only if you use the built-in AI (chat or ai ask), requests to the model provider you configure. The CLI, MCP server and headless renderer make no other network calls.

Can I use it without configuring MCP?

Yes — that's the recommended path for coding agents: npx -y daigram install-skill --dir <skills-root> and the agent drives everything through the CLI. MCP configuration is only needed for chat clients like Claude Desktop.

Can the MCP client and canvas run on different machines?

Yes, if the MCP process can reach the canvas server. Keep the MCP process on the machine that launches it and set EXPRESS_SERVER_URL to that canvas location. The canvas HTTP/WebSocket URL is not an MCP endpoint; for an HTTP-only MCP client, configure a separate stdio-to-HTTP bridge. See Remote Canvas and HTTP-Only MCP Clients for a loopback-preserving SSH tunnel and matching JSON configuration.

Troubleshooting

  • CLI exit code 3 (canvas unreachable): the server is not running for an inspecting command such as status, auto-start is disabled (EXCALIDRAW_NO_AUTOSTART=1), or EXPRESS_SERVER_URL points at a non-loopback host. Run start explicitly or fix the env.

  • CLI exit code 4 (browser required): only mermaid and screenshot --renderer browser need an open tab — open http://127.0.0.1:3000 in a browser and retry, or drop --renderer browser to render headless.

  • Headless PNG shows boxes instead of CJK/emoji text: the bundled fonts cover Latin scripts; for other scripts resvg falls back to the machine's fonts (a warning is printed). Install a CJK font on the machine running the canvas server.

  • Canvas not updating: confirm EXPRESS_SERVER_URL points at the running canvas server (status shows the URL in use).

  • Something else looks wrong: the server log has the details; its location is in Environment Variables (LOG_FILE_PATH).

Known Issues / TODO

  • Optional persistent storage: set EXCALIDRAW_DATA_DIR for atomic local restart recovery; the default remains in-memory.

  • Mermaid conversion requires a browser: mermaid / create_from_mermaid lay out the diagram in the frontend. Image export and screenshots are headless.

Contributions welcome!

Development

npm run type-check
npm run build
npm run cli -- status      # run the CLI from the local build
npm run sync:skills        # after editing skills/excalidraw-skill, sync the repo-local agent copy

Bug reports and pull requests are welcome on GitHub issues. If this project helps you, a ⭐ helps others find it.

License

AGPL-3.0-only for the changes and additions in this project; the work it is based on, mcp_excalidraw © yctimlin, stays under its MIT license (see NOTICE). Not affiliated with the Excalidraw team. Excalidraw is its own MIT-licensed project.

Contributions: see CONTRIBUTING. Security: see SECURITY.

Links: npm package · GitHub · Issues

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to programmatically control a live Excalidraw canvas with element-level CRUD operations and real-time synchronization. It supports iterative diagramming through scene descriptions, screenshots, and advanced layout tools for collaborative AI-human workflows.
      2
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to create, modify, and share diagrams on a live Excalidraw canvas through MCP tools, supporting shapes, text, arrows, batch operations, and export to shareable links with images.
      8
      MIT