Renders draw.io diagrams inline in AI chat interfaces using the MCP Apps protocol.
| File | Purpose |
|---|---|
src/shared.js |
Shared logic: buildHtml(), processAppBundle(), createServer() |
src/index.js |
Node.js entry (Express + stdio transports) |
src/http-security.js |
Access control of the Node HTTP entry: the optional bearer token, the Origin check with its CORS headers, the startup banner — see Access control (Node entry) |
src/worker.js |
Cloudflare Workers entry (Web Standard fetch handler) |
src/build-html.js |
Build script: generates generated-html.js for the Worker |
src/semantic-bundle.js |
Bundles the semantic engine (shared/semantic) and the converters (shared/convert) into one classic script for the viewer's preview of create_semantic_diagram — see Semantic diagrams |
server.json |
MCP Community Registry manifest (io.draw/mcp, remote https://mcp.draw.io/mcp and the npm package @drawio/mcp) — publish runbook in README "Publishing to the MCP Registry"; keep version in lockstep with package.json, and packages[0].version at a tool server release with mcpName (test/server-json.test.js) |
snippet/mcp_edge.js |
Cloudflare Snippet in front of the Worker on mcp.draw.io: answers pings, notifications, session-less requests, GET/HEAD/DELETE/OPTIONS and OAuth discovery probes without a Worker invocation — see Edge snippet |
openai-plugin/ |
OpenAI Plugins Directory package (.codex-plugin/plugin.json: names, descriptions, starter prompts, policy URLs, icon; .mcp.json: the server, which can never change on an existing plugin) — zipped and uploaded as a new version in the portal; its own version, runbook in OPENAI-SUBMISSION.md |
At startup (Node.js) or build time (Workers), the HTML is assembled. The draw.io viewer, drawio-elk, and drawio-mermaid load from the viewer.diagrams.net CDN via <script src> — they're large, cached cross-session by the browser, and stay version-synced with each draw.io release (same host + release cadence as the viewer). The remaining bundles are inlined so the sandboxed iframe needs no further fetches for them:
app-with-deps.js(~319 KB, fromnode_modules/@modelcontextprotocol/ext-apps) — MCP Apps SDK browser bundle. The bundle is ESM (ends withexport { ... as App }), soprocessAppBundle()strips the export statement and creates a localvar App = <minifiedName>alias. This makes it safe to inline in a plain<script>tag inside the sandboxed iframe.pako_deflate.min.js(~28 KB, fromnode_modules/pako) — for compressing XML into the#create=URL format.- libavoid (the obstacle-avoiding orthogonal edge router behind
routing: "libavoid") is not vendored/inlined — the HTML loads the pure-JS router bundle (libavoid.min.js, a self-contained classic script that publishesglobalThis.Avoidand parkswindow.__libavoidReadysynchronously — no WASM, no fetch, nowasm-unsafe-evalneeded) + shared routing core from theviewer.diagrams.netCDN (js/libavoid-js/), like drawio-elk and drawio-mermaid. Requires the draw.io release that ships the pure-JS two-file layout there. The routing math isAvoidRouting.computeRoutesfromlibavoid-routing.js— the canonicaldrawio-dev js/libavoid-js/artifact, byte-identical to what the draw.io editor bundles and the mcp-tool-server vendors.buildHtmlacceptsoptions.libavoidJsto inline a local build instead (dev). Seevendor/libavoid/README.md.routeWithLibavoidpasses each vertex's style transform (libavoidShapeFrame→AvoidRouting.shapeFrame: rotation, direction, flips) and each pin'sexitPerimeter/entryPerimeter, so rotated shapes are routed as drawn; against a CDN core from before rotation support (noshapeFrame) it routes them unrotated, as before. A floating edge end gets one candidate pin at the middle of each side (LIBAVOID_SIDE_MIDPOINTS) instead of the shape's centre, and the pass asks the core to nudge apart the segments attached to a shape (opts.nudgeShapeSegments): from the centre, every edge leaving a shape shared its first segment and their labels piled up. Of those midpoints, a floating end only gets the sides that face the other end (libavoidFacingPins), as draw.io's orthogonal edge style draws them: shapes stacked vertically connect bottom to top, shapes side by side connect side to side, a diagonal pair gets both facing sides. Alone, libavoid takes the route with the fewest bends, which entered a shape below from its side, so a load balancer's edges to two servers under it left its bottom and turned into the servers' sides. When another shape blocks the corridor between the two ends (a loop back along a flowchart column), all four sides stay allowed; shapes drawn around an end (a container, a background band) don't block. A row of a table (an ER column, a class attribute: a child of astackLayout/tableLayout/tablecontainer) only gets its left and right side (libavoidRowPins), since its top and bottom border the rows next to it; with all sides, relations entered tables through their header. The pass reroutes only right-angle edges (libavoidRoutesEdge:orthogonalEdgeStyle,elbowEdgeStyle,entityRelationEdgeStyleand the other segment styles, notcurved=1). Straight and curved lines are a choice the diagram type makes (use case links, network cables, state transitions, mind maps) that orthogonal routes would undo, so they stay as drawn. XML withoutpostLayoutorroutingis routed anyway when a right-angle edge, as the built-in router draws it, runs through a shape it doesn't connect, through a label outside a shape or through a lane's title band (edgesCrossShapes, checked at finalize,opts.autoRoute): the model can't see where the basic router draws its lines. Containers and shapes drawn around an end don't count, as in the routing core'sfilterEnclosing. A vertex withlabelPerimeter=1and a label outside the shape also passes that label (libavoidOutsideLabel, from the viewer'sgetLabelPerimeterSide), so the core routes around it and ends edges on that side at its far edge, where draw.io ends them. Both need the draw.io release after 32.5.5: an older CDN core ignores the option and the label (the midpoint pins then share their first segment like the centre did), and an older viewer has nogetLabelPerimeterSide.LIBAVOID_PATH(a directory withlibavoid.min.jsandlibavoid-routing.js, e.g. drawio-dev'ssrc/main/webapp/js/libavoid-js) inlines a local build in the Node server for testing before that release, next toVIEWER_PATH.
Loaded from the CDN (not inlined):
viewer-static.min.js— the draw.io viewer (GraphViewer,Graph,mxCodec,mxUtils, …).drawio-mermaid.min.js(/js/mermaid/) — native Mermaid parser + layout that emits draw.io cells viamxMermaidToDrawio.parseText(text, config). Replaces the upstream ~2.7 MBmermaid.min.js+extensions.min.jsruntime. Supports 28 diagram types. ReadsglobalThis.ELKon init. Built fromjgraph/drawio-mermaid.drawio-plantuml.min.js(/js/plantuml/,PLANTUML_URL) — draw.io's PlantUML converter (mxPlantUmlToDrawio.parseText), built fromdrawio-plantuml. 1.2 MB, so it has no script element: the viewer adds one when a PlantUML diagram comes in (loadPlantUml).PLANTUML_PATH(Node) or buildHtml'splantumlJsinlines a local build instead. See PlantUML and CSV.drawio-elk.min.js(/js/elk/) — Eclipse Layout Kernel + the mxGraph ↔ ELK bridge, self-publishing IIFE. Definesvar ELK(engine) plusElkLayout/ElkAdapter/ElkApplieras globals, consumed by drawio-mermaid and thepostLayoutpass.ElkLayoutis the single source for the layout pipeline (prepare/execute), the per-algorithmDEFAULTS, theMENU_PRESETS(layout name → algorithm + direction) and theCANONICAL_EDGEtreatment (edgeStyleMode+corners) — shared verbatim with drawio-dev's editor. The MCP'sapplyPostLayoutdrives it vianew ElkLayout(...).prepare(...). Built fromjgraph/drawio-elk.
Script load order is viewer → pako → elk → mermaid, preserved because all are classic (non-async) <script> tags and execute in document order — external CDN tags block parsing just like inline ones. drawio-elk defines var ELK + ElkLayout and must come before drawio-mermaid (mermaid reads globalThis.ELK on init and throws otherwise); mermaid must come after the viewer so its mermaidShapes.js side-effect sees mxCellRenderer/mxActor. The viewer code reaches ElkLayout straight off the (CDN-loaded) bundle for the postLayout pass — no separate shim script.
Shape sizes in the ELK pass. applyPostLayout runs ELK with resizeParent: false, so it keeps every shape's size; only containers are refit. The layered pass takes the unconnected top-level cells out of the flow and stacks them above it (ElkLayout.placeIsolatedTopLevelAbove). Up to the bundle on the CDN in 32.6.10 it also narrowed each of them to the flow's width, a rule meant for the Mermaid title. With a single connected pair, every other box took that pair's width: in a Claude.ai test with one Sensor → Hub edge, all eight unconnected boxes rendered 80 wide (sent 100 to 140), and their labels stopped fitting. drawio-elk now narrows only text cells whose label doesn't wrap, since those draw the same at any width (test/verify-bridge-isolated.mjs there). Until a draw.io release ships that bundle, applyPostLayout saves the width of every top-level shape without children before ELK applies and restores any it changed, centred where ELK put it (saveLeafWidths / restoreLeafWidths). Text cells that don't wrap are left to the narrowing, as in the fixed bridge. Once the CDN has the fix the stopgap changes nothing and can go.
For local dev, set VIEWER_PATH / ELK_PATH / MERMAID_PATH to a built bundle to inline it instead of hitting the CDN (e.g. testing a drawio-elk/mermaid build before it's published). processElkBundle / processMermaidBundle accept both the published IIFE form and an ESM build. The published CDN files self-publish their globals (no export{}), so those functions are no-ops on them.
- The MCP Apps sandbox uses
sandbox="allow-scripts"but notallow-same-origin— Blob URL module imports fail silently. That's why we strip the ESM export and use a plainvaralias. - Links open through the host (
openUrl), never<a target="_blank">— noallow-popups.app.openLink({ url })(ui/open-link) everywhere but ChatGPT, wherewindow.openai.openExternal({ href, redirectUrl: false })opens them: ChatGPT's link check forui/open-linkprints the whole URL, and for a#createlink it was taller than the window, which cut off its buttons.openExternaltrusts the targets in_meta["openai/widgetCSP"].redirect_domainsof the app resource (REDIRECT_DOMAINS: app.diagrams.net, www.drawio.com;ui.cspcan't carry them, so that key repeats the rest of the CSP too), andredirectUrl: falsekeeps ChatGPT from appending?redirectUrl=…, which would land in the#createhash. ChatGPT reads these settings from its copy of the app resource's metadata, made when the plugin was scanned, but loads the HTML live, so a metadata change only reaches it after a Rescan in the portal (OPENAI-SUBMISSION.md). Until the rescan of 2026-10-31 its copy predatedredirect_domains, and every link still got the check.test/open-link.test.jschecks both paths. - ChatGPT's fullscreen header has its own "Open in draw.io" button. Without a target it opens the component's iframe path on
ui.domain, our Claude sandbox domain, so it answered "Not Found" (2026-10-30).commitDiagramXmlpasses every newdrawioEditUrltowindow.openai.setOpenInAppUrl({ href }), so it opens the diagram. ChatGPT accepts that target only from the CSP's connect domains or the widget domain, not the redirect domains (openInApp.validateUrlin its bundle), soCONNECT_DOMAINSlists app.diagrams.net although the viewer fetches nothing from there. ChatGPT checks it against the app's current metadata, so it works in chats from before the change too, but a ChatGPT tab opened before the Rescan keeps the old metadata until it reloads (the first test after 1.4.6 failed for that reason). GraphViewer.processElements()requires nonzerooffsetWidthon the container — hencemin-width: 200pxon#diagram-container.
Node.js (src/index.js) |
Worker (src/worker.js) |
|
|---|---|---|
| Transport | StreamableHTTPServerTransport (Express) |
WebStandardStreamableHTTPServerTransport |
| HTML build | Reads bundles from node_modules + vendor/ at startup |
Pre-built via build-html.js → generated-html.js |
| Session management | None — a server per request; the session's one bit of state rides in its id, the resource flag sits in an in-memory Map | None — a server per request; the session's one bit of state rides in its id |
The Worker serves /mcp statelessly: every request gets its own createServer() + WebStandardStreamableHTTPServerTransport, built in the Worker and dropped with the response. Nothing is held between requests, so it scales out with the Workers runtime and there is no Durable Object on the request path.
- Sessions (2025-era protocol): an
initializeis answered with a mintedMcp-Session-Id,ui-<uuid>ornoui-<uuid>— whether the client declared theio.modelcontextprotocol/uicapability, the one piece of per-session state the server needs (see Clients without an MCP Apps UI). A later request's server reads it back from the header (uiSessionoption ofcreateServer), and its transport is marked initialized (_initialized) since it never saw the handshake. Any session id is accepted — there is no "session not found" anymore; an id without either prefix (issued before this scheme) reads as "not declared". - Session-less requests other than
initializeget the transport's own400 Server not initialized— the answer MCP 2026-07-28 clients (claude-code, copilot-cli, some Claude.ai traffic) get for theirserver/discoverprobe before falling back toinitialize. GET /mcp→ 405 (no standalone SSE stream: the server never sends anything outside a response),DELETE→ 200 (nothing to release).MCPSessionManageris now one Durable Object per session id (idFromName(sessionId), RPC methodsmarkUiResourceRead/uiResourceRead), holding only the "fetched the app resource" flag in storage, dropped by an alarm 24 h after the last fetch. Only clients that did not declare the UI capability ever reach it — onresources/readof the app and oncreate_diagram— so it sees a tiny fraction of the traffic. A failed lookup counts as "not read", which only appends the fallback link. The class name is kept from the old design to avoid a wrangler migration./healthis the uptime probe (Pingdom watcheshttps://mcp.draw.io/health): it runs aninitializethrough the same per-request path as/mcpand answers200 ok(503otherwise). It exists because monitors count the non-2xx of a session-lessGET /mcpas down. The Node server answers/healthdirectly.
Why stateless? Until 2026-09-30 every session's server + transport lived in the memory of sharded Durable Objects (4, then 16, routed by the session id's first hex char). A DO handles its requests one at a time and has 128 MB: with each session building its own shape-search tag map (~8 MB), the shards hit their memory limit ~1,200 times an hour and reset (dropping every session), and on 2026-09-30 they overloaded outright ("Durable Object is overloaded"). Claude.ai opens a new session per connector refresh (initialize → tools/list → resources/list, rarely a call, never a DELETE), so the DOs mostly held idle sessions — ~0.3 MB each once they had served tools/list. The DOs were also the dominant cost (billed per active object, 128 MB each). The only state a session needs is one bit, which fits in its id.
MCP 2026-07-28 drops sessions and initialize altogether (capabilities arrive per request in _meta). Supporting it natively means SDK v2 (@modelcontextprotocol/server + ext-apps 2.x); v2's default handling of 2025-era clients is stateless too but loses their initialize capabilities, so the capability-in-session-id scheme stays for them.
snippet/mcp_edge.js is a Cloudflare Snippet (snippet mcp_edge, zone draw.io, Enterprise). Snippets run before Workers and cost nothing per request, so the requests whose reply never depends on the server are answered there and never invoke the Worker:
- a
ping(200, theidechoed,mcp-session-idechoed) and anotifications/*message (202), both within a session - any JSON-RPC message but
initializewithout a session (400 "Server not initialized") GET(405),HEAD(405),DELETE(200, or 400 without a session) andOPTIONS(204) on/mcp- OAuth/OIDC discovery probes (
/.well-known/oauth-*,/.well-known/openid-configuration,/mcp/.well-known/…: 404)
Everything else is passed on with fetch(request) and reaches the Worker unchanged. That includes initialize, tools/* and resources/*, batches, bodies over 1 KB or of unknown length, a Content-Type whose media type isn't application/json (the SDK parses it, so text/plain; a=application/json gets its 415), SSE-only clients, unknown mcp-protocol-versions and any message the SDK's strict JSON-RPC schemas might reject (ids and progress tokens must be safe integers). Every reply the snippet makes carries x-drawio-mcp-edge: snippet.
Why: Copilot CLI pings each open session every 21 s, forever, so windows left open keep pinging. In October 2026 that was ~71% of all Worker requests. Worker requests had grown from 2.3M a day (2026-09-29) to 7.1M a day (2026-10-12), and an 88 s wrangler tail sample put ~85% of them in the categories above.
Keeping it exact: the snippet must answer exactly as the Worker would. test/edge-snippet.test.js holds the Worker's recorded replies, checks the pass-through cases, and fails when the SDK's SUPPORTED_PROTOCOL_VERSIONS no longer matches the snippet's copy. EDGE_COMPARE_URL=<worker origin> npm test also compares every answered case live. Run it against staging after an SDK update or a change to worker.js's trivial paths (CORS headers, GET/DELETE handling), and redeploy the snippet when they change.
Rule:
http.host eq "mcp.draw.io" and (http.request.uri.path eq "/mcp" or starts_with(http.request.uri.path, "/.well-known/oauth-") or starts_with(http.request.uri.path, "/.well-known/openid-configuration") or starts_with(http.request.uri.path, "/mcp/.well-known/"))
The zone's snippet rules belong to drawio-dev. src/main/server/cf/cf-snippets/rules/draw.io.json there is the draw.io zone's complete rule list, and every draw.io production deploy (cf-deploy.yml) replaces the zone's rules with it. It lists this rule since drawio-dev 970f312abc; before that, the 32.5.1 deploy (2026-10-13 14:47 UTC) deleted it and the Worker took all the traffic again until it was restored at 16:32. So change the rule in that file as well as on the zone. The code is not in drawio-dev (no cf-snippets/mcp_edge/, so its deploy skips it): deploy it from here, cf snippets update mcp_edge --zone <zone id> --file snippet/mcp_edge.js --metadata '{"main_module":"mcp_edge.js"}'. Updating rules on the zone by hand (PUT /zones/{zone}/snippets/snippet_rules, which replaces all rules in the zone): GET them first and send them all back.
Rollout: deploy with and any(http.request.headers["x-drawio-mcp-edge-test"][*] eq "1") appended to the rule, so only requests carrying that header reach the snippet. Check them against production (the x-drawio-mcp-edge header shows which side answered), then drop the condition. Rollback: disable or remove the rule, which takes effect at once. Snippets have no logs: watch the Worker's daily requests in workersInvocationsAdaptive (GraphQL) drop instead.
DOMAIN secret:
- Set via
wrangler secret put DOMAIN - Value format:
{hash}.claudemcpcontent.comwhere hash is SHA-256 of the endpoint URL (first 32 hex chars) - Current value: SHA-256 of
https://mcp.draw.io/mcp, truncated to 32 hex chars +.claudemcpcontent.com - Used in
resources/readresponse_meta.ui.domainfor Claude.ai iframe sandbox origin
wrangler.toml migrations:
- The v3 migration tag is already applied in production
- Do NOT add a new
[[migrations]]tag unless the DO class name changes — it will cause deploy conflicts
create_diagram appends a second text block carrying an app.diagrams.net/?pv=0&grid=0 URL (or to a self-hosted editor, see Self-hosted editor under Viewer toolbar) (#R with the XML, like "Open in draw.io" below; #create= with the source for Mermaid, which draw.io converts) when the connected client doesn't render the app — a plain MCP client (Codex CLI, a terminal agent, a script) otherwise receives the JSON payload and nothing renders the diagram anywhere. Detection is capabilitiesDeclareUi() (the io.modelcontextprotocol/ui capability from getUiCapability, carrying RESOURCE_MIME_TYPE) OR uiResourceRead, a per-session flag set when the client actually fetches the ui:// resource — which covers a host that renders through its own negotiation without declaring the capability.
The declaration is trusted except from the clients in UI_DECLARED_NOT_RENDERED (clientUiState() → "hidden", by the clientInfo of initialize): those declare the capability and never render the app. The one entry is codex-mcp-client version 0.0.0, OpenAI's hosted Codex harness. ChatGPT's Work mode runs a plugin's own MCP server through it whenever the prompt mentions the plugin (plugin://drawio@openai-curated-remote, which the starter prompts on the plugin page insert), and the page shows those calls as a "Made N tool calls" line, never the app: users got neither the diagram nor the link (2026-10-31, reproduced with wrangler tail: user agent codex-mcp-client/0.0.0, OpenAI's network, one ui- session). A typed @draw inserts an app mention (app://asdk_app_…) instead, which ChatGPT calls through the connector (user agent openai-mcp/1.0.0 (Codex)) and renders. The Codex app and CLI send their release version and keep their declaration; within one version some sessions declare the capability and some don't.
Where the two signals live depends on how long the server instance lives. The stdio server has one instance for the whole session, so both sit on the instance. Both HTTP entries build one per request and pass createServer a uiSession: declared and hidden come from the session id minted at initialize (ui- / hidden- / noui-, from clientUiState), and the resource flag from that session's MCPSessionManager Durable Object (Worker — see Cloudflare Workers Architecture) or an in-memory Map with the same 24 h expiry (Node). The Node HTTP transport stays stateless: src/index.js sends the minted id in Mcp-Session-Id itself and reads it back from the header. Until 2026-10-13 it minted none, so every Node and Docker client got the link, VS Code (which declares the capability) included.
The block is only ever appended: the app reads the FIRST text block (content.find), so a host that renders but wasn't detected keeps working. For most clients the server only knows that they didn't declare the capability, and some of those do show the diagram (Claude.ai often declares nothing up front), so the note stays a condition ("if this client doesn't show the diagram inline"). Worded as a fact in 1.4.5 ("assume the user can't see this one"), Claude showed the diagram and told the user it didn't display. For a "hidden" client the server knows the user sees nothing, and there the condition was ignored: the model in ChatGPT Work assumed the diagram showed and left the link out. So that note says the user can't see the diagram and first asks the model to call another draw.io create_diagram tool that shows diagrams in the conversation, the draw.io app in ChatGPT, with the same arguments, giving the link only otherwise: ChatGPT Work offers the server both as the plugin's MCP server (never renders) and as the app (renders), and a model can't copy a link of several KB reliably (its copy in Work broke off after 447 characters and didn't open). Short links are not an option: they would store the diagram, which the service promises not to do. XML goes into the URL as-is, so a requested postLayout adds a note saying the link opens the authored coordinates (that pass lives in the app). Mermaid goes in as type: "mermaid" and the editor converts + lays it out on open — and a requested postLayout: "elk" does survive, because it is selected in the source: withElkLayout from shared/mermaid-elk.js (the canonical copy; the browser-side withElkRenderer in the app HTML is the same transform, kept in sync by hand since the self-contained HTML can't import).
create_diagram ends every result, XML and Mermaid, with a note (appendAnswerNote): the user sees the diagram itself, so the model shouldn't describe or list what it shows, and once it is done drawing it replies in at most two sentences unless the user asked for an explanation, for example with what it assumed or changed, or the offer of a next step shared/chat-view-xml.md asks for. Without the note the model summarized the diagram the user was already looking at.
- Where the client renders the app (
clientUiState"renders", or it fetched the resource), the note says the user already sees the diagram in the chat. Elsewhere it is a condition like the link note ("inline or through the link"), and the reply is short besides the link: the server doesn't know whether Claude.ai shows the diagram. - For a hidden client (
clientUiState"hidden") the link note just before it says the user can't see the diagram, so this note says nothing about what the user sees and doesn't make the link optional ("the user will look at it themselves", "besides the link"): the conditional wording read as the last block told the model the user sees the diagram and that the link is optional, the slip the hidden link note exists to prevent. - It is the last block, after the swap note, the warnings and the link, so the model reads it last; the viewer reads the first text block, the payload, and never sees it.
- Within the hosts' rules: plain text about the result the tool just produced, under 320 characters, no markup, nothing about other tools, and the user's request comes first ("unless the user asked for an explanation"). Result text only:
tools/listdoesn't change, so the ChatGPT app needs no rescan.test/answer-note.test.jscovers the wording per client, the order of the blocks and the length. - Measured in November 2026 with
claude -p(Sonnet 5.5, Opus 5.5) on an ER diagram, a swimlane flowchart (both XML) and an OAuth sequence diagram (Mermaid), the old and the new server side by side, timed from thecreate_diagramcall to the end of the answer. With the server told the client renders the app, as for ChatGPT, Claude.ai, VS Code and Cursor: Sonnet's answer went from a median of 408 to 115 output tokens (1,165 to 347 characters) and ended 4.4 s after the diagram instead of 5.7 s (9 runs each); Opus's from 605 to 97 tokens, 1.9 s instead of 6.2 s (5 runs each). Without a UI (Claude Code itself, so the link is appended), the text besides the link shrank from about 1,330 to 390 characters, but the time is the link's: an answer with the 1–3 KB link ran to 900–2,400 tokens, and the models gave it in 6 of 8 answers instead of 4 of 8, so the answer didn't end sooner (Sonnet 9.8 s instead of 11.5 s, Opus 30 and 55 s instead of 6 and 31 s).
Before that, repairDiagramXml (shared/repair-xml.js, shared with the tool server) fixes the mechanical slips LLMs make in the XML string: text around the diagram (a leaked tool-call tag after it, …</mxGraphModel></xml>), < or a stray & in attribute values, and the default layer written as its own parent. When the leaked text carries a postLayout, direction or routing argument with a value XML_OPTION_VALUES accepts (the same arrays the create_diagram schema uses) and the real argument is missing, leakedArguments recovers it. A well-formed diagram passes byte-identical. In LLM tests of the tool server these slips caused every broken diagram, 15 of 473; see mcp-tool-server/AGENTS.md.
Right after the repair, expandDiagramShorthand (shared/diagram-shorthand.js) expands the two shorthands shared/chat-view-xml.md teaches, so the model writes less: in the November 2026 benchmark the time to a diagram was almost all the model writing XML, styles were about half of it, and 75 of the 86 cells of a class diagram were attribute rows. The reference teaches rows for class diagrams only, and ER tables written out, cell by cell, as before. Taught for ER tables too, rows made ER diagrams twice as fast and worse: in a blind judgement on eight ER prompts against production, which had them written out (bench/, November 2026, three runs per prompt and model), main's ER diagrams scored 0.33 with Sonnet and 0.23 with Opus. The models wrote what the shorthand had no place for less often (bold primary-key rows in 11 of 48 diagrams against 46, two or more table colors in 5 against 38) and placed tables whose size they couldn't see, leaving wide gaps; stating the size and allowing 4 tables per row showed every schema whole but still scored 0.44 and 0.19, and bold primary-key rows with table colors by domain 0.58 and 0.35. Written out again, they scored 0.65 and 0.58, at production's time to the diagram (Sonnet 49 s against 51, Opus 264 s against 241; with rows 24 s and 105 s). Live, with staging deployed from this text (d0b219c) against production on the five held-out ER prompts (15 November 2026, three runs per prompt and model), they scored 0.5 and 0.53, where main had scored 0.20 and 0.20 on the same prompts; Sonnet took 49 s to the diagram against 54, Opus 317 s against 275. test/diagram-shorthand.test.js checks that the reference keeps it that way and that a written-out table passes unchanged. A vertex with rows="PK id|FK book_id|…" becomes a list table (a swimlane with childLayout=stackLayout under its own style, height from the rows, a width for the longest row when none is given) followed by one text row cell per entry, 26 px tall (font size + 10 above 16), --- an 8 px separator line; a row's id is table.name, the name being the first word after key markers (PK, FK, UK) and UML visibility, numbered when repeated, its position when there is none, and an edge naming a row by position (loan.2) or in another case is pointed at it. role=step|decision|start|end|error|data|external|container in a vertex style becomes the calm theme's shape, colors, fontSize=14, html=1 and whiteSpace=wrap, keys written beside it winning in place (a shape of its own replaces the role's), a container inside another one white, and a vertex without width or height the grid size of its role; on a table a role only sets the colors. String in, string out: no rows attribute or known role key is left, a diagram without them passes byte-identical, and expanding twice changes nothing. Start tags are scanned with their quoted values taken whole, since XML allows a raw > in a value and the repair escapes only < (value="Retries > 3?", a row List<Item>): at the first >, such a cell lost its vertex, rows and style and stayed unexpanded. The viewer inlines the same code (createDiagramShorthand.toString(), self-contained for that reason) and runs it on the healed partial XML and in finalizeStreamingView, since it draws from the raw tool input before the result arrives. On the partial XML ({ partial: true }) a table cut off before its <mxGeometry> stays as written: streamInsertCell hides a vertex without a geometry until one arrives, and the made-up geometry a complete table without one gets would show it at the top left first. The tool server, the skill and the project instructions don't expand them, so the shared references don't mention them. test/diagram-shorthand.test.js.
After the shorthand, getIconResolver().applyToXml (shared/icon-resolver.js, shared with the tool server) replaces icon=<provider> <service> in a vertex style with the style of the official icon from shared/icon-table.js: the current AWS, Azure, Google Cloud and Kubernetes sets, generated from the shape index by shape-search/generate-icon-table.js. The icon's keys win over the cell's (a theme's fillColor would repaint an AWS tile), the label keys stay, and a cell with children on its page or container=1 only takes an AWS group (icon=aws vpc); one larger than 100 × 100 without children takes a group when one fits as well as an icon (a VPC drawn before its subnets), and a service icon otherwise. A label color of the library that is hard to read on what the label sits on (isHardToRead: a gray under 4.5:1 against it or any color under 3:1; surfaceAt takes the fill of the nearest shape around the cell that has one, from the icon for an AWS group, white for a shape without a fillColor as draw.io paints it, nothing for fillColor=none, a group or a swimlane's body, and else the page's background, white without one; a group's own label, inside it, sits on the group's fill) becomes the calm theme's text color #1B1F24 (LABEL_COLOR), as the role styles and the references write it, while a fontColor of the cell still wins. On a white page that is the 128 Google Cloud products (gcp2, #999999, which a benchmark judge marked down as hard to read), AWS's VPC group (#AAB7B8) and its generic subnet (#879196); AWS's dark labels (#232F3E), the colored labels of its other groups, which match their borders (#D86613 and the like), and Google Cloud's current icons (#000000) stay; Azure and Kubernetes icons write no label color. On a dark page (the dark theme's background="#0F172A", which applyToXml reads from each mxGraphModel) the grays stay, as they read well there, and a label that doesn't, such as AWS's #232F3E, gets the dark theme's text color #F1F5F9 (DARK_PAGE_LABEL_COLOR): a cell the model wrote without the theme's fontColor would otherwise get a dark label on a dark page. Inside AWS's private and public subnets, which keep their pale library fills (#E6F6F7, #F2F6E8) on a dark page too, the dark labels stay and the subnets keep their own label colors: judged by the page alone, they had turned #F1F5F9 on the pale fill (about 1:1). Cisco has no icons by name. The resolver is one per process for every caller, so its cache keeps only the last 500 names, and a name longer than 100 characters matches nothing without being searched. A name that matches nothing stays as written and unresolvedIconWarnings tells the model what to write. The viewer inlines the resolver and the table (expandIcons, ~150 KB, ~35 KB gzipped) and applies it to the partial and the final tool input after expandDiagramShorthand, as the server does, so icons show while the XML streams in; the gcp2 icons, data URIs of 200 KB together, stay on the server and show as a gray placeholder, with the label color the result will have on that page, until the result. In the AWS architecture case of a November 2026 benchmark (Claude Code, claude -p), Sonnet wrote the names in 5 of 6 runs instead of making 9 search_shapes calls: the diagram was done after 39 s instead of 55 and had 7.1k instead of 10.3k characters. test/icon-names.test.js covers the server and the viewer; the resolver's cases are in the tool server's test/icon-resolver.test.js.
Every XML diagram passes through normalizeDiagram (shared/normalize-model.js) right after normalizeDiagramXml and the repair, before the payload reaches the app. It repairs three things generated XML carries: edges parked on the layer although both terminals sit inside one container (they render, but ELK reads an edge's coordinates in the frame of the node containing it, so the connector escapes the container — #64), edges written without a geometry (not rendered at all), and containers that would clip a child (grown, never shrunk).
Doing it here rather than inside the layout keeps postLayout free of hierarchy side effects, and the corrected diagram is what the viewer renders, what "Open in draw.io" exports, and what the fallback URL carries. The implementation is MxGraph.normalizeModel in shared/mx-model.js — a port of drawio-dev's Graph.normalizeModel, i.e. the desktop CLI's --normalize — driven over the XML by shared/mx-xml.js; idempotent, and it rewrites nothing else.
Right after the normalization, snapWaypoints (shared/edge-waypoints.js, shared with the tool server) moves the first or last waypoint of an edge onto the line of its fixed connection point when it lies less than 3 px (SNAP_DISTANCE) off it: on a left or right side its y, on a top or bottom side its x. An edge with exitX/entryX leaves the shape at a right angle, and draw.io's orthogonal router runs the line from there to the waypoint; a waypoint written at y = 510 for a connection point at y = 508.8 gets a 1.2 px jog next to the shape, and an arrowhead there takes its direction from that piece and points along the side. In the hand-written disk overview that led to it, the Time Machine arrow pointed up the side of its target; snapped, its last segment is 35 px. The pass only snaps where draw.io keeps the connection point where the style puts it: rectangular outlines, or the middle of a side of any outline (draw.io projects other points of a round or slanted one onto it), not rotated, flipped or turned shapes, nor corners. It rewrites only those edges and is idempotent. test/edge-waypoints.test.js runs it through create_diagram; the cases are in the tool server's test of the same name.
After it, addLabelPerimeters (shared/label-perimeter.js) adds labelPerimeter=1 to vertices with a label outside the shape, centered on one side (verticalLabelPosition top or bottom, or labelPosition left or right), unless their style already has the key: draw.io ends edges on that side at the label's far edge, the convention of cloud architecture diagrams. The editor sets the key the same way on new shapes; existing diagrams don't have it. Then fitEdgeLabels (same module) gives all edges, labeled or not (as new edges in draw.io after 32.5.5 have it), and the labeled label cells of edges the label gap (labelBackgroundColor=default;defaultLabelBackgroundColor=page, Transparent in the Background list of draw.io's Text tab: draw.io after 32.5.5 cuts the label out of the line instead of painting a white box; 32.0.2 to 32.5.5 paint the page color, older viewers the white box), unless a background is set, and puts the label of a straight horizontal edge just above the line (verticalAlign=bottom) where it fits between the shapes, and labelPlacement=auto on every labeled edge (draw.io after 32.5.5 picks above or on the line by the segment under the label, also for bent edges; older viewers ignore it). Both rewrite only those cells and are idempotent.
The fast mode: a tool of its own next to create_diagram. The model describes the diagram (nodes, edges, groups, a type) and the engine in shared/semantic lays it out as draw.io XML (shared/semantic/AGENTS.md). It is listed by default for flowcharts and swimlanes and taken on request: its description has the model use it only when the user asks for a quick or cheap diagram. When models use it, its limits, why it is a tool rather than a parameter of create_diagram, the measurement and what to measure again are in shared/semantic/FAST-MODE.md. create_diagram and the other tools are listed exactly as without it.
- On request: the description starts with the condition (
describeTool'sonRequest,onRequestTextandWISHinshared/semantic/description.js): only for a diagram the user explicitly asked to get fast or cheap, in any language ("schnell", "Skizze", "wenig Aufwand", "sparsam" are named as examples); a request without such words, however simple, and the types not listed go tocreate_diagram; a change to a diagram drawn here comes back here. On held-out prompts in English and German, with and without the wish, Sonnet and Opus followed it in 118 of 120 sessions (15 November 2026). The same condition on an argumentquickofcreate_diagramfailed and was removed. A change to the wording, or tocreate_diagram's description, needs the tool choice measured again (shared/semantic/FAST-MODE.md, What to measure again); the tests only check that the condition is there. - Which types:
SEMANTIC_TYPES_ONinsrc/shared.jsis the default: flowcharts and swimlanes, offered on request.SEMANTIC_TYPES_READYlists the types that passed the blind judgement inbench/(bench/README.md) for both models on three runs: flowcharts and swimlanes (Sonnet 0.87, Opus 0.70, no prompt below 0.33,shared/semantic/MEASUREMENTS.md, seventh measurement). The gate leaves out a prompt that the size rule below sends tocreate_diagram, with every pair of it whose diagram came from that tool: those are the model's XML against its own XML and measure nothing of the semantic tool. Listing the tool changestools/list, so the ChatGPT app needs a rescan once it is deployed.DRAWIO_SEMANTIC_TYPESis the switch (resolveSemanticTypes): unset,on(ortrue,1) offers the ready types, a comma list the types it names (er,architecture,network,flowchart,swimlane; unknown ones dropped;on,erthe ready types and ER),offnone (the tool isn't listed, andtools/listhas the three other tools alone). Every type offered is offered on request. The description explains a swimlane as a flowchart with lanes and a network as an architecture diagram (DESCRIBED_BYinshared/semantic/description.js), soswimlanealone offers flowcharts too, andnetworkarchitecture diagrams.createServer'ssemanticTypesoption takes the result. - Where the switch is read: the Node entry reads it at startup (
DRAWIO_SEMANTIC_TYPES=off npm startleaves the tool out). The Worker's HTML is built before the deploy, sobuild-html.jsreads it from the deploying shell, likeDRAWIO_BASE_URL, and exports the types fromgenerated-html.jsassemanticTypesfor the worker'screateServer: the HTML has the engine exactly when the tool is listed. A deploy without the variable offers the default;DRAWIO_SEMANTIC_TYPES=off npx wrangler deploy --env stagingdeploys without the tool. - The description and the schema come from
shared/semantic/description.jsand list only the offered types:describeTool(types, { hints: "ask", onRequest: true }), and the keys of nodes, edges and groups with what each one means fromdescribeSchema(semanticInputSchematurns its JSON Schema into zod, with the same types, descriptions and required keys). Placement is asked for (SEMANTIC_HINTS,"ask"): every node names its cell (row,col) in one grid for the whole diagram. That is the variant the judgement was made with (semantic-rowsinbench/), so the description, the schema, the server's layout and the viewer's preview all use it, andtest/semantic-tool.test.jscompares the listed schema with the one the bench ran with (the server adds no texts of its own to it). Of the three later wordings of the description only the one about placement is in it (PARTS_KEPT): measured one by one, it won the most judgements, and the other two cost some (shared/semantic/MEASUREMENTS.md, fifth measurement). With flowcharts and swimlanes offered the description has about 1,470 characters, the condition included. - Leniency:
typeis an enum of the offered types, in any case and with the engine's aliases (erd,schema:typeNamefromshared/semantic/spec.js). Lists are read as the engine reads them (jsonList→readList): JSON text, as models sometimes send them, one item alone, items as one string with|, nodes and groups by id alone or with a label for a missing id,source/targetforfrom/to, a number for a text (a title too), a row or a column as text ("2","2.0"),nullfor anything optional and for an entry of a list, which is dropped. Keys the schema doesn't name (lanes,direction) go on to the engine. So the server doesn't reject what the viewer's preview has already drawn for a slip of that kind. What still fails, with a message that names the key: JSON text that doesn't parse, a row that isn't a whole number (1.5,"top"), an edge as text ("a->b") and an edge without an end. None of them is in the 790 descriptions the bench runs saved.tools/listis the same as without this leniency (z.preprocess). - The size rules:
semanticToXml(args, { sizeRule: true })refuses a flowchart without lanes (no node in a group, also under the typeswimlane) of more than 24 nodes (MAX_NODES_WITHOUT_LANESinshared/semantic/index.js) and an architecture or network diagram of more than 18 (MAX_NODES), and the tool answers with anisErrorresult that sends the model tocreate_diagramfor it ("This flowchart without lanes is too large to lay out well from a description. Draw it with create_diagram instead, as XML you place yourself, with all of its content. Don't shorten the description to fit.", the second halfSEMANTIC_TOO_LARGE_NEXT). Neither that text nor the tool's description and schema name a number, sotools/listis the same with or without the rules: with "flowchart without lanes: at most 24 nodes" in the description oftype, Sonnet's descriptions of the large held-out flowchart had 22 and 23 nodes where they had 25 to 34 before, left out steps and lost; without it they have 25 to 30 again and are refused. The model describes the whole diagram and the size of that description decides (shared/semantic/MEASUREMENTS.md, seventh measurement). As XML, because sent on as "larger", models tookcreate_diagram's Mermaid with ELK, which lost every judgement. The viewer findsSEMANTIC_TOO_LARGE_NEXTin the error and shows the user a note in place of the diagram ("This diagram is too large to lay out from a description, so it is drawn shape by shape instead.",showNotice), not the red "Tool error" box, since the model draws the diagram with its next call. The large flowchart without lanes of the held-out prompts lost its blind judgements for Opus (its descriptions had 25 to 34 nodes, the normal one's 17 to 21), and large cloud diagrams with nested boundaries lost every judgement against XML the model placed itself (shared/semantic/MEASUREMENTS.md). Lane diagrams and ER schemas have no limit. Architecture and network are not among the ready types: their rule is there for when they are offered. The preview applies the rules too, so it stops drawing a description that has grown past one (the last drawing stays until the error arrives). In the preview (partial: true) a node that names a lane not there yet counts as in a lane, since the schema listsgroupsafter the nodes and a model that writes them last would otherwise have its large lane diagram stop drawing at the 25th node until its lanes arrive; the server reads the whole description and counts only the lanes it declares. - The answer is
create_diagram's payload with two more keys,{xml, described: true, layout, _buildId}, after the same passes (finishDiagramXml: normalization, waypoint snapping, label perimeters, edge labels), so the viewer, its layout check, "Open in draw.io", the model context and the fallback link for clients without a UI treat it as XML.layout(flowcharts and swimlanes, whose nodes name their cells) is what a change passes back so the shapes it doesn't touch stay in place (shared/semantic/AGENTS.md, A change keeps the layout); a second text block says so with the layout written out (semanticChangeNote): the model reads the instruction there rather than in a key of the JSON with the XML. The server stores nothing. What the diagram doesn't show as described (an edge to an unknown node, a layout that isn't used) follows in a text block of its own,WARNINGS (what the diagram doesn't show as described):; a description with nothing to draw is anisErrorresult with the reason. Likecreate_diagram's, the result ends with the link for clients that don't render the app and the note that asks for a short reply (appendOpenUrl,appendAnswerNote). For the hidden Codex harness the note names the tool to call in the draw.io app,create_semantic_diagramhere, with the same arguments. - The preview: while the arguments stream in, the viewer lays out what has arrived, with the same placement rule as the server, and draws it like streaming Mermaid (
handleSemanticPartial→runSemanticPreview→mergeSemanticXml: cells morphed in place, removed ones dropped), at most every 150 ms, or every twice the last layout's time when that is longer; the result ends the preview. Every layout is the whole diagram, and a node names its lane or group only later in the stream, so the merge of a description moves a cell to the parent the new layout gives it (streamMergeXmlDelta'smoveCells; streamed XML only grows and keeps its merge). The result is merged the same way and drops what the last partial left over. Without the move, the steps of a swimlane diagram stayed in the lane an earlier partial had put them in. A node that is still being written has its id and label before its cell, and one node without a cell makes the engine drop the page's grid for a grid per group, which draws the lanes the other way round: so the preview leaves out the nodes at the end of the list that have norowandcolyet, when a node before them has (semanticPreviewArgs; the arguments themselves stay as they came). Over six saved descriptions streamed in 60 steps each, the layout changed between the two grids 30 times without that and 6 times with it (once at the start of each, before the first cell is there). The engine decides for every partial whether the page is shown larger with rows and columns swapped, so on its own the lanes of a growing diagram turned with every partial that tipped the balance. So the viewer passes on how it has shown the page (semanticShownTurned, from the stats of the last layout on one grid for the page, askeepTurned), and the other way round has to show the diagram at a scale 0.3 larger (KEEP_MARGINinshared/grid-layout.js, chosen on the dev descriptions) before it turns. In the viewer check (bench/preview.mjs, the 48 held-out lane diagrams of the fourth and fifth measurements streamed in 24 steps, then the whole input and the result) 13 turned more than once before, up to four times, and none after: 42 turn once and 6 not at all. Of the 42, 29 turn at the result, which the server lays out on its own: the first partials show the lanes as rows, and the full diagram is shown larger with columns, but by less than the margin. The 12 flowcharts without lanes of the normal prompt: 9 turned more than once before (the engine's replay of the same steps), none after (shared/semantic/MEASUREMENTS.md, sixth measurement). The icons of the preview get the paths of the draw.io site, like the result's. The size rule is the server's: a description of an architecture diagram that is too large is previewed until the error arrives. - The engine in the HTML is the global
DrawioSemantic, inlined bybuildHtmlonly when it getsoptions.semanticJs, so it adds nothing when no type is offered and no format is converted on the server (DRAWIO_SEMANTIC_TYPES=offandDRAWIO_CONVERT=off; the preview code is there, and waits for it). It carries the converters ofshared/converttoo (DrawioSemantic.convertSource,serverConverts), see Mermaid, PlantUML and CSV converted on the server. The engine's modules are bundled by a small reader of their own import and export lines (src/semantic-bundle.js), since the sandboxed iframe can't load modules; a construct it doesn't read failstest/semantic-tool.test.js. What the viewer has anyway isn't bundled twice: the icon table, the icon resolver and the shorthand expansion are read from the page (bundleSemanticEngine({ externals: VIEWER_GLOBALS })), so the script comes after the viewer's own and has about 315 KB (91 KB gzipped) instead of 715 KB, about 484 KB (137 KB gzipped) with the converters. Since flowcharts and swimlanes are offered by default, every build of the app resource carries it. The table in the page has nogcp2data URIs: those icons show as a placeholder in the preview, as for streaming XML. - What the model is told afterwards: the viewer's update for the model (see below) says that the diagram was laid out from the description, and that a change to its content is a new call with the whole changed description and the same ids, the same cells for what stays and the layout of the result, the XML only for moving or restyling single shapes (
modelContextText'sdescribedandlayoutKey, from the result'slayout). The viewer knows it from the input it previewed or fromdescribedin the result, for a host that hands over the result alone. The layout check and the image are the same as for any XML diagram. - Tests:
test/semantic-tool.test.js(the tool and the switch with its values, the schema, the layout on the named cells, the leniency and what still fails, the size rule, the note for a client that shows nothing, the bundle with and without the page's globals, the HTML, the Worker's build),test/semantic-preview.test.js(the merge that moves cells and the nodes the preview waits for, run from the template source, with the engine's layout of both),test/model-context.test.jsandtest/layout-check.test.js(what the model is told) andtest/semantic-er.test.js(the ER layouts). - Not there yet: a change that doesn't pass the layout back is laid out anew, so its shapes can move;
create_diagramdoesn't use the grid pass for XML without positions; the ChatGPT app's review coverscreate_diagramonly; and whether a change without the wish to a diagram drawn on request comes back to this tool, as its description asks, is not measured.
The model only has the arguments it sent, but the viewer can show something else: Mermaid converted to draw.io XML, an ELK layout or libavoid routing pass, the user's layout toggle. Every change to what is shown goes through commitDiagramXml, which schedules sendModelContext (500 ms, so a render and its layout pass coalesce; the layout and routing state is taken with the XML, since a render's first commit comes before the layout state is set). modelContextText writes what the diagram is and how to change it (start from this XML, pass it as xml without postLayout / routing so the positions stay; for Mermaid, simple changes can stay in the Mermaid source), followed by the flat XML as shown — for Mermaid the converted cells, not the wrapGroup wrapper "Open in draw.io" uses.
- When: plain XML shown as sent isn't repeated. Mermaid and any pass are sent, and once a diagram has been sent, every later change is (so the toggle back to "as authored" updates the model too). Above
MODEL_CONTEXT_MAX_CHARS(60,000) nothing is sent. - How:
app.updateModelContext(ui/update-model-context) when the host declares theupdateModelContextcapability. The host keeps only the last update and passes it on with the user's next message. Otherwise, in ChatGPT,window.openai.setWidgetState({ modelContent }).[model-context]console lines say which channel was used, or that there was none. - Nothing reaches draw.io: the XML, the image and the layout check go from the iframe to the host's conversation, so the privacy page doesn't change.
test/model-context.test.jsrunsmodelContextTextfrom the template source.
The XML doesn't tell the model how wide a label comes out, where draw.io routes a line or what ends up on top of what: those exist only once the viewer has drawn the diagram. So the update carries two more things, measured on the graph as shown (after layout and routing):
- The layout check (
layoutCheck, for every host that takes model context): a short list of labels wider or taller than their shape, labelled shapes on each other, labels on labels (from 4 px) or on labelled shapes, and one line per connector with everything found on it, with ids and sizes in diagram units, at most 20 lines. On a connector it finds the shapes it runs through or the labels of shapes or lanes (edgesCrossShapes) and, fromedgeLayoutIssues: an arrowhead without room (its last straight piece shorter than half the arrowhead, so it points along the side or over the bend), a step of 1 to 3 units in the line (from 1 on rounded lines, where the two corners make an S, from 1.5 on square ones), a run of 20 or more along a frame's border (within 4) or in a gap under 30 between two frames side by side, more than 10 on top of another edge where one hides the other (another color, width or dash) or both join the same two shapes (lines of one look meeting on their way are a bus, a merge or the trunk of a tree, also when their arrowheads differ), and its label on a frame's border, on another edge's line, or turned (horizontal=0). Frames are shapes with a rectangular outline drawn around smaller shapes: containers, zones, subnets. One line per edge, because the chip counts the lines: the hand-written diagram the edge rules came from got 28 lines for its 4 defects without the grouping, and 6 with it. A list asks the model to fix the problems when it next changes the diagram, and to offer once when the next request is about something else: without that line nothing makes the model act on it, and without "once" an unrelated question would turn into a round of fixes. It leaves out what overlaps by design: unlabelled shapes (walls, chart cells, backgrounds), labels inside a frame at least 16 times their size, labels outside a shape or turned, shapes under 8 px, lifelines below their head, and lines that aren't connected at both ends, are sequence messages, are curved, or join two unlabelled anchors (sankey, git graph); a shape that holds a labelled shape (a card whose name is in a box of its own) counts as labelled (layoutCheckAnchor). Round and diamond shapes are tested by the box inside them. The crossings come fromedgesCrossShapes(graph, found): withfoundit collects every crossing over the connectorslayoutCheckedConnectoraccepts; without it, it still decides the automatic routing pass exactly as before. The rules were tuned on ~600 diagrams from the benchmark and gallery runs, replayed through the server's passes: 532 came out clean, and the ones sampled from the rest (a title crossed by a line, a multiplicity on an attribute, rack labels piled up, sequence labels running into the number badges of the Mermaid conversion) were real defects. The edge rules were tuned on 598 diagrams in November 2026 (the 67 gallery diagrams, 239 Mermaid conversions, 286 draw.io templates and examples, and 6 cases of the hand-written diagram: the original, the versions Sonnet and Opus made through the app server, a flowchart and an org chart), replayed the same way: 26 got edge findings, none of the Mermaid conversions, the Opus version, the flowchart or the org chart among them. Of the 58 edges they flagged, a visual review found 5 doubtful, all in hand-made templates (two arrowheads that read fine, two lines between dashed frames, two wires on top of each other); the labels on borders and lines, the steps and the runs along borders were all real. The overlap rule at first also compared arrowheads and flagged buses and tree trunks, so it compares color, width and dash only. A host that takes text only gets the check before the XML; for XML shown as sent, alone and only when it found something. - A PNG of the diagram (
renderModelContextImage), only when the host declareshostCapabilities.updateModelContext.imageand isn't ChatGPT, which shows each context block as an attachment in its message box (not tried with an image yet). draw.io's own client-side export (Editor.prototype.exportToCanvas, in the viewer bundle) runs on anObject.create(Editor.prototype)with the graph, at most 1568 px on the long side and twice the diagram's size, in the scheme the diagram is painted in (alight-dark()probe, notprefers-color-scheme; a scheme change sends the image again). Remote images are loaded with CORS and inlined (the icon service and the viewer's own images allow it); one that can't be is left out instead of tainting the canvas, and nothing goes through draw.io's image proxy. An SVG image can't use the page's web fonts, so every family without a generic one getsHelvetica, Arial, sans-serif(Recursive came out in Times). The image is sent on every render, also for XML shown as sent; the XML still only when it differs.
The update waits for document.fonts.ready (at most 2 s), since a web font still loading would make the labels measure the wrong width. Hosts pass it on with the user's next message, so the model sees it on its next turn, not within the turn that drew the diagram. The Claude desktop app's Code tab declares images and passes them on (seen with read_widget_context); it loads the app HTML once per session, so a new build only shows in a new session. [model-image] and [layout-check] console lines show the size, time and count. test/layout-check.test.js runs the check on a stand-in graph, and the content and fallback helpers, from the template source.
By the time the update reaches the model, the turn that drew the diagram is over. So when the layout check finds something, the toolbar shows a chip, "Fix N issues" (#fix-layout-btn, with an amber warning icon; its tooltip says "N layout issues"). A click sends the host a user message, "Fix the layout issues the draw.io viewer found in this diagram." (ui/message through app.sendMessage; in ChatGPT window.openai.sendFollowUpMessage). The host starts a model turn, and the image and the check are already in the model's context. The click first waits for the update in flight (modelContextInFlight), so the message never overtakes the check.
- Only on a click: a message sent on its own would start a turn the user didn't ask for, under their name, and after each fix the next check would send another.
- Only with something to fix:
updateFixLayoutChipshows the chip when the check counted at least one issue and the host declareshostCapabilities.message(or hassendFollowUpMessage). With nothing found, "Fix" would be the wrong word, so there is no chip. - It counts what is on screen: every commit hides the chip until the check of the new state (
scheduleModelContext), and the layout toggle hides it at once (applyLayoutChange). The toggle exists for XML withpostLayout: "elk"and for every Mermaid flowchart, and the two layouts usually have different issues. After a sent message the chip stays hidden for that layout (fixLayoutAskedFor, by layout state): a toggle offers it for the other layout, but not again for the one already asked about. A host that rejects the message gets "Could not send" for 2 s, then the chip again. - Hosts: Claude.ai declares
ui/message: in a test on 2026-11-06 the click posted the message and Claude fixed the diagram. For the other hosts, the[model-context] hostconsole line logsmessageandfollowUp;[fix-layout]lines show the chip and the send. - The message is in English, whatever the language of the chat.
Inline, the iframe grows to the diagram's natural height up to inlineHeightCap(): 800 px, at most 90 % of screen.availHeight (the screen, because the iframe's own height follows our sendSizeChanged and would feed back), never below 480 px. --inline-max-h on the root carries the same value to the CSS. Hosts resize the iframe both ways on sendSizeChanged, Claude.ai included. Expand switches the cap to 1000 px; fullscreen fills the window.
Where fitting a tall diagram whole would shrink it below STREAM_READABLE_MIN_SCALE (0.75, so 12 px labels stay 9 px), the camera settles on its top at that scale instead: computeDefaultViewTransform, used after drawing, layout passes, the layout toggle and Expand, and by streamFollowNewCells once there is nothing left to follow, so the window resize that follows the host's size change keeps the top view instead of zooming back out to fit-whole. The card's bottom edge fades while the diagram continues below (.more-below, from updateMoreBelowCue), and the Fit button and double-click still show the whole diagram. A diagram limited by its width keeps fit-whole. Before this, a fixed 480 px cap shrank tall flowcharts and sequence diagrams until their labels were unreadable: the 2026-10-16 benchmark spike scored draw.io's readability below Excalidraw's for exactly that. [inline-height] console lines show the cap, the host's reported height and when the top view is used.
What is fitted (computeCellsBBox): the shapes, the labels drawn outside of them (verticalLabelPosition / labelPosition, from the rendered label's box, so an icon's name below it counts) and the bends of the edges. A fit by the shapes alone cut off the names under the bottom row of icons and lines that run around the outside of the diagram. test/view-fit.test.js runs the function from the template source.
Labels. "Open in draw.io", "Copy" and the layout-issues chip carry text labels; the other buttons are 30 px icons. A label never wraps (white-space: nowrap, an ellipsis if it is ever squeezed). Whenever the labels can't be shown whole, fitToolbarLabels first drops the chip's label (chip-compact, the amber icon stays), then puts the toolbar in compact mode, icons only and every button square. A label squeezed to nothing counts as cut: its offsetWidth is 0, so the test asks whether its button is shown instead. With every button shown, all labels fit from about 660 px, and "Open in draw.io" and "Copy" keep theirs down to about 575 px. The chip first said "Fix N layout issues", which needed about 720 px: in Claude.ai's inline frame that made the whole toolbar compact and took the "Open in draw.io" label with it. It re-measures with the labels shown when the toolbar's width changes (ResizeObserver), when a button is shown or hidden, and when a label changes ("Copied!", the chip's count) (MutationObserver). The icon buttons never shrink (flex-shrink: 0), so the labels are what gives way, and in compact mode no button shrinks. In compact mode the gaps narrow to 4 px, which makes up for the split buttons' arrows.
Narrow frames. With every button shown (zoom, Open, Copy, Download, fullscreen, Expand, layout, the chip and help), the icons alone need about 420 px, and mobile chats are 350–390 px wide. There the compact toolbar wraps to a second row instead of cutting off the last buttons, as it did below about 385 px before the chip. flex-wrap: wrap applies only in compact, and fitToolbarLabels measures without it, so the labels go before anything wraps. When the wrap changes the toolbar's height, fitToolbarLabels calls resizeContainerToFit, which makes room for the second row where the frame's height is fixed (fullscreen).
Download and Copy are split buttons. A click on the button does what it always did (the .drawio file through ui/download-file; the XML to the clipboard). The 16 px arrow beside it opens a menu that starts with that same action, in bold and set off by a line as the default, followed by the image formats: Download .drawio, Download PNG and Download SVG (all through ui/download-file), and Copy as XML, Copy as Image and Copy as SVG (navigator.clipboard.write with a ClipboardItem, created in the click because the clipboard needs the user's gesture, its contents handed over as promises while they render). The wording follows draw.io's (its Edit menu has Copy, Copy as Image and Copy as SVG; toolbarMenuEntries). Copy as SVG writes what draw.io's does, an <img> with the SVG as a data URI as text/html, plus image/svg+xml only where ClipboardItem.supports says the browser writes it (Chrome from 124), since a ClipboardItem with a type the browser doesn't write fails as a whole, and the markup as text/plain for editors (svgClipboardTexts). Tested in a sandboxed frame like the hosts' (November 2026): Chrome 157 wrote all three types, Firefox 159 the HTML and the text; Safari takes Firefox's path (it writes no SVG type) and is untested. The arrow shows only when there is an image format, since a menu with the default alone would repeat the button. Until 1.8.0 the menus listed only the image formats. What a host doesn't support is hidden, never greyed out, and follows what it declares, never its name (toolbarMenuFormats, checked by test/download.test.js): the Download button and its menu need hostCapabilities.downloadFile; Copy as Image and Copy as SVG need the host to grant hostCapabilities.sandbox.permissions.clipboardWrite (the resource asks for it in _meta.ui.permissions) and a browser with ClipboardItem whose permission policy allows clipboard-write; PNG (Download and Copy) needs a canvas the viewer bundle's own check (Editor.useCanvasForExport, an SVG with HTML labels drawn to a canvas) found untainted. The images come from draw.io's own export code in the viewer bundle: Graph.getSvg and Editor.exportToCanvas on an Editor made with Object.create(Editor.prototype), since its constructor would change the shown graph (chromeless, math rendering). Both carry the .drawio file (the SVG in its content attribute, the PNG in a tEXt chunk), so draw.io opens them for editing. So they download as diagram.drawio.svg and diagram.drawio.png (imageFileRequest), the names draw.io gives such files, which tell that the image opens as a diagram; the menu entries keep their labels. The PNG is drawn at 2x in the theme the viewer shows; the SVG follows light or dark mode wherever it is shown. Both take the page color, shadow and adaptiveColors from the diagram's mxGraphModel (diagramPage, kept in currentPage by applyDiagramBackground), since the viewer's graph merges only the cells and has none of them: without that, a dark or blueprint theme lost its page and its light text landed on white or nothing. A diagram with adaptiveColors="none" is exported in its light colors (exportTheme), and its SVG gets a white page when it has none (svgExportBackground), as draw.io does. Images are embedded through exportImageConverter, which leaves absolute URLs as they are: draw.io's own converter would send every image not on the sandbox's origin through viewer.diagrams.net/proxy, which the sandbox can't reach, and leave the proxy URL in the SVG. Library SVGs (app.diagrams.net/img/lib/…, icons.diagrams.net) can't be fetched as text (not in connectDomains), so they are embedded as PNG at Editor.svgRasterScale.
"Open in draw.io" opens #create={"type":"xml","compressed":true,"data":…,"effect":"pop"}: the XML the viewer shows (for a Mermaid diagram, the converted XML wrapped by wrapGroup with its source in mermaidData), with the "pop" animation as draw.io creates the diagram. The plain links have no animation: the fallback link for clients without an MCP Apps UI and the tool server's links open XML as a raw #R link, and use #create= only for Mermaid (and the tool server's CSV), which draw.io converts in the browser because nothing has converted it to XML there. ?pv=0&grid=0 apply to both (draw.io reads them for every loaded diagram). test/links.test.js checks both forms.
Self-hosted editor. DRAWIO_BASE_URL points "Open in draw.io" and the fallback link at another draw.io, as in the tool server (#91). editorLinkBase builds the link up to its hash: the base URL with pv=0&grid=0 added to its query (after a query of its own), any hash dropped; anything but an http(s) URL throws, so the Node server fails at startup. buildHtml puts it in the iframe as window.__DRAWIO_EDITOR_URL, which generateDrawioEditUrl reads; createServer builds the fallback link from it and adds its origin to the connect and redirect domains (withEditorOrigin), next to app.diagrams.net. Only the links move: the viewer, shape images and libraries still load from diagrams.net (window.DRAWIO_BASE_URL, the viewer's own base for those, stays app.diagrams.net), so the inline preview needs no sign-in to a draw.io behind SSO. The Node server reads it at startup. The Worker's HTML is built before the deploy, so build-html.js reads it from the deploying shell and exports it from generated-html.js as drawioBaseUrl for createServer, which keeps both links on one value; a [vars] binding would come too late for the HTML. test/links.test.js covers both links, the CSP and the validation.
The "All changes will be lost!" dialog (draw.io up to 32.4.5): after a #create, draw.io rewrites the hash with the diagram it created, and its hashchange handler compares the result with the hash from before the load. If they differ, it loads the link again and asks. They differ whenever the link isn't exactly what draw.io writes back: a Mermaid or CSV link, another deflate or JSON encoder, or a host that re-encodes the link on the way to the browser. VS Code does the last: a link opened as a URI goes out as encodeURI(uri.toString(true)), which leaves : , + / = unescaped. draw.io never rewrites a #R hash, which is why the button used #R from 2026-10-12 until the fix: drawio-dev 5170e37146 and 6ee7e71444 (2026-10-13, first release after 32.4.5) have executeCreateObject store the hash it rewrites to on the created file, and the hashchange handler doesn't load that hash again. Tested with every link format here, it removes the dialog; comparing decoded hashes only covers re-encoded XML links, and history.replaceState alone covers none, because fileLoaded has already cleared the hash. Deploy the button's #create only once app.diagrams.net runs that release, or VS Code users get the dialog again.
registerAppToolinputSchemauses Zod shapes ({ key: z.string() }), not JSON Schema objects- CSP config goes on the resource contents
_meta.ui.csp, not on the tool's_meta.ui resourceDomainsincludeshttps://fonts.googleapis.comandhttps://fonts.gstatic.comso Google fonts offontSourcestyles load in the viewer (the font CSS is linked, it loads the font files) — e.g. the Recursive font of Mermaid 12 diagrams (redux-colortheme)_meta.ui.permissionsasks forclipboardWrite(Copy as Image, Copy as SVG), next tocspon the resource contents; the host says inhostCapabilities.sandbox.permissionswhether it granted it- TypeScript narrowing: use
if (block.type === "text")before accessing.texton content blocks - To accept more than a schema advertises, wrap it in
z.preprocess(lenientinsrc/shared.js): the JSON schema intools/liststays byte-identical to the wrapped one, so a tool can get more forgiving without a new tool definition (which the OpenAI and Claude directory listings were reviewed against). Put.optional()inside the wrapper: outside, it lets onlyundefinedthrough andnullfails before it is mapped. The SDK (1.32) answers a value the schema rejects with anisErrortool result ("Input validation error"), which the Claude directory counts as a tool error - The viewer renders from the raw tool input (
ontoolinputpartial,ontoolinput) before the result arrives, so input the server corrects has to be read the same way there:normalizeOptionValueis inlined for the options,diagramXmlStartskips text before the XML,expandDiagramShorthandexpands table rows and roles,expandIconsthen resolves icon names, and a diagram under the other parameter is left to the result
The get_drawio_reference tool ({ format: "xml" | "mermaid" }) returns one of two canonical reference files in shared/, with this server's chat-view sections inserted before their first section (src/references.js, readReference): shared/chat-view-xml.md (designing for the inline frame, one layout pattern per diagram type for XML the model places itself, changing a diagram, choosing a look) and shared/chat-view-mermaid.md. readReference also leaves out the shared sections a diagram in the chat doesn't use (OMITTED_SECTIONS: layers, tags, metadata and placeholders, cross-functional grids). That keeps the XML reference under 50,000 characters: Claude Code, and the hosts built on it, save a longer tool result to a file and show the model a 2 KB preview, so the model would draw without the reference (seen in tests on 2026-10-18 at 54.6 KB). test/references.test.js caps it at 48,000 and checks that the omitted headings still exist. Only create_diagram shows diagrams in the chat frame, and only its format rule has the model place flowcharts, class, state and other diagrams as XML; the tool server, the skill and the project instructions use the shared references without these sections.
shared/xml-reference.md— loaded as thexmlReferenceoption oncreateServer(); covers draw.io XML styles, the layout grid, edge routing, containers, metadata.shared/mermaid-reference.md— loaded as themermaidReferenceoption; covers syntax for all 28 supported Mermaid diagram types plus flowchart styling (style,classDef,linkStyle).
The create_diagram description stays short (~1.8k characters): the Mermaid-vs-XML decision with every Mermaid header keyword, the XML essentials, and an instruction to call get_drawio_reference once per format before the first diagram. Through app server 1.0.6 it carried both references (~55k characters), which broke VS Code Copilot's tool search: Copilot embeds tool descriptions in batches, and one description over the embedding limit fails the whole batch, other servers' tools included (#76). test/tools.test.js (npm test) caps every tool description at 2048 characters and checks that the tool returns both files. Guidance that only matters once a format is chosen belongs in the references, not in the description.
For the Cloudflare Worker, both files are pre-built into generated-html.js (exported as named strings) by build-html.js and re-imported by worker.js. The Node.js path reads them directly from shared/ at startup.
This is the viewer's conversion: of the Mermaid types the server leaves to it, of every type with DRAWIO_CONVERT=off, and the one the plugins' script runs. Flowcharts, ER and sequence diagrams are converted on the server (below).
Mermaid in, editable draw.io out: convertMermaidToXml() in shared.js runs mxMermaidToDrawio.parseText(text, null, {version: MERMAID_DEFAULTS_VERSION}) from the drawio-mermaid bundle, which parses, lays out and returns draw.io cells: shapes, connectors with a source and a target, labels as the cells' text. MERMAID_DEFAULTS_VERSION ("12", top of shared.js) is also passed by the streaming preview, stored by wrapGroup in the mermaidData behind "Open in draw.io" and added to #create= links of type mermaid, so the preview, the opened diagram and draw.io's re-conversion on edit all use Mermaid 12's defaults (no theme is forced; draw.io adapts the light themes to dark hosts). It waits for waitForGraphViewer(), because the cell factory needs Graph, mxCodec and mxUtils from viewer-static.min.js, and for the diagram's fonts:
- Fonts first: Mermaid 12's redux themes use the Recursive Google font (
fontSourcein the style; both hosts are in the CSPresourceDomains, see MCP Apps SDK Patterns).parseTextmeasures every label withmxUtils.getSizeForString, so the first diagram of a page was measured in the fallback font, and its boxes came out about 20 % too narrow for their labels once Recursive arrived (a class box 331 px wide instead of 397).loadMermaidFontsasksmxMermaidToDrawio.getFontsfor the diagram's fonts and loads them withGraph.addFont, then pollsdocument.fonts.loaduntil the face is there:parseTextadds the stylesheet itself, anddocument.fonts.loadresolves with no faces while that stylesheet is still loading. At mostMERMAID_FONT_TIMEOUT(3 s) per font, never rejecting. The streaming preview doesn't wait (mermaidFontsReady), but a conversion made before the fonts were there isn't reused as the cached result (lastConvertedMermaidFonts). - Nothing to draw:
parseTextreturnsnullfor an unsupported type and the empty diagram for a header with no statements it recognized. Both are a rejected promise, the second withMERMAID_NOTHING_TO_DRAW, so the viewer shows an error rather than an empty frame. A streamed diagram's preview parses the text up to its last newline (healMermaidText), sohandleMermaidPartialkeeps that parse for the final conversion only when what it left out is blank and it has cells: otherwise a final text that came with its last line lost that line, and one with nothing to draw showed an empty frame. - The plugins convert with the same bundle in a headless browser when draw.io Desktop isn't installed (
plugins/claude-code/skills/drawio/scripts/mermaid-to-drawio.js,HeadlessEditorUi.parseMermaidDiagramas in the desktop CLI, with the sameversion;plugins/claude-code/DEVELOPING.md).
Checked per type: test/mermaid-types.test.js converts one diagram of every type draw.io takes (the 28 of shared/mermaid-reference.md plus swimlane-beta, usecase-beta, agentflow-beta, railroad and cynefin-beta), in the app's HTML (the viewer's convertMermaidToXml, the class diagram first so the font wait is tested) and with the plugins' script, and every example of the reference, and streams three texts into the preview before their final conversion. It checks that the result is cells and not an image, that no cell is locked, that the listed labels are cells' text, which shapes are inside their container, and how many edges may have a loose end and how many cells may be images. It needs Chrome, Edge or Chromium (CHROME_PATH) and the network, and skips without them or with DRAWIO_TEST_BROWSER=off; MERMAID_TYPES_REPORT=<file> writes the counts per type. Run it through browser-slot where that is the rule.
Swimlane routing: drawio-mermaid with jgraph/drawio-mermaid#20 routes the edges of a swimlane-beta diagram around its shapes with libavoid (globalThis.Avoid and AvoidRouting.computeRoutes) when the page has it and not the editor's LibavoidRouting. The viewer loads libavoid before drawio-mermaid anyway (the libavoidBlock of buildHtml), and the plugins' script loads the same two files once its bundles have loaded, in an evaluate of their own (loadOptional), and only for a run with a swimlane-beta diagram (ROUTED_TYPES, by draw.io's getMermaidDiagramType), so other diagrams wait for no libavoid: it fetches both together and runs them in their order only when both have arrived within 20 s, so libavoid that is slow or missing never fails the conversion, and libavoid that comes late never runs between two diagrams; without it the diagram converts as before. test/mermaid-swimlane-routing.test.js converts Mermaid's swimlane example through a local mirror of viewer.diagrams.net/js/: the script must ask for LIBAVOID_FILES after drawio-mermaid for a run with a flowchart and the swimlane diagram, and not at all for the flowchart alone, convert the same shapes with libavoid answered 404 and the same diagram with libavoid sent later than it waits, and loadOptional must leave libavoid sent too late out of the page, even once it has arrived, and run it when it comes in time. With a drawio-mermaid that routes, the CDN's once a draw.io release ships it or MERMAID_PATH=<build> (ESM or IIFE, served by the mirror and inlined in the viewer), no edge may run through a shape, in the script's result and the viewer's; the layout's line from Pay to Raise invoice runs through Pick items. With one that doesn't, those checks are skipped and loading libavoid must change nothing.
What the conversion doesn't do yet (drawio-mermaid on the CDN of November 2026, written in the test as the most each type may leave undone, so a fix there makes the test pass with room to tighten):
- Lines without both ends: a timeline's lines from a period to its events (each period's label is also a text cell laid over its box), tree view branches, Ishikawa bones, railroad tracks, the arrows between event modeling frames, Cynefin's lines, and a sequence (or ZenUML) message that creates a participant, which ends next to its head. Journey axes, xychart lines and Wardley's axes and evolve arrows are drawings, as in Mermaid.
- Not inside their container: event modeling frames in their lanes, Cynefin items in their domains, treemap sections, architecture services in their group (a frame).
- Names beside the shape: an architecture service's name is a text cell under its icon, a Wardley component's beside its circle.
- Images: radar curves are SVG images (architecture and ZenUML icons are images by design).
- Railroad diagrams don't draw their title. Swimlane edges keep the layout's routes: the CDN's drawio-mermaid doesn't route them yet.
- A gantt fragment without tasks has nothing to draw.
create_diagram converts Mermaid, PlantUML and draw.io CSV on the server into draw.io cells, laid out and styled (shared/convert, see its AGENTS.md), instead of passing the source on for the viewer to draw. The model gets real XML back, with a syntax error named by line and fix, and the first sentence of the description says so, as the reason to send them: "Send Mermaid, PlantUML or CSV and get back an editable, styled draw.io diagram with an edit link (syntax errors by line), or send draw.io XML you placed. Exactly one." The format rule after it is unchanged.
- What is converted: Mermaid flowcharts (
flowchart,graph,flowchart-elk), ER and sequence diagrams; PlantUML sequence and activity diagrams (the new syntax); draw.io CSV except# list,# containerand thecircleand custom layouts. Everything else goes to draw.io's own converters in the viewer as before (see below), with a note that names it (convertedNote: "PlantUML class diagrams are converted by draw.io's own converter in the viewer, not on the server, …").serverConverts(format, text)decides, the same function on the server and in the viewer. - Layout and style: flowcharts, activity diagrams, ER schemas and CSV are laid out by
shared/semantic(semanticToXmlwithhints: falseandstyles: true) in the calm theme, with the colors the source writes on top (classDef,style, PlantUML's#colorand lane colors, a CSV'sfillColor=%fill%); sequence diagrams byshared/convert/sequence.jsin draw.io's UML shapes (lifelines, activation bars,umlFramefragments, notes). Subgraphs, partitions and CSV parents become frames, PlantUML lanes lanes. Themes,skinparam, the Mermaidinitconfig and the preprocessor are left out with a warning. - The result is
{xml, converted: "<format>", _buildId}afterfinishDiagramXml(convertedResult), so the rest is an XML diagram's: the viewer, the layout check, "Open in draw.io", and a#Rlink for clients without the app (PlantUML gets one for the first time). Then a note on what was converted, with counts, and how to change it (send the changed source again, or this XML for moving or restyling single shapes), the warnings (WARNINGS (what the diagram doesn't show as written):), the link and the answer note. - Errors: a syntax error is an
isErrorresult with the format, the line, its text, what is wrong and how to fix it (syntaxErrorinshared/convert/common.js): "Mermaid syntax error on line 3 (subgraph X): the subgraph "X" has noend. Fix: close every subgraph with a lineend." A misspelled Mermaid header is one too ("here probablysequenceDiagram"), where the viewer drew a blank frame before. What can be drawn anyway is drawn and named in a warning (a PlantUML line the converter doesn't know, a CSV placeholder that names no column, a Mermaidclick). - postLayout: a Mermaid flowchart keeps ELK. With
postLayout: "elk"or a source that selects ELK as draw.io reads it (aflowchart-elkheader,layout: elkin the frontmatterconfigor an%%{init}%%directive, or the olderdefaultRenderer: "elk"), the payload carriespostLayout: "elk"and the flowchart'sdirection, and the viewer lays the converted cells out again, as for XML withpostLayout. The other conversions have a layout of their own; apostLayoutthere is not applied, and the note says so. - The preview: while the source streams in, the viewer runs the same conversion (
DrawioSemantic.convertSourcewithpartial: true, which closes what is still open and leaves out the last line, which may be cut off), at most every 150 ms or twice the last conversion's time (handleConvertPartial,runConvertPreview), and merges it like a semantic description (mergeSemanticXml); the result moves the cells into place (described). The converters are in the engine script (semantic-bundle.js), which grows from about 315 KB (91 KB gzipped) to about 484 KB (137 KB gzipped). - The switch:
DRAWIO_CONVERT(resolveConvertFormats): unset oronconverts all three formats,offnone (the viewer-only behaviour of 1.10), a comma list the formats it names. The Node entry reads it at startup,build-html.jsfor the Worker (exported fromgenerated-html.jsasconvertFormats), likeDRAWIO_SEMANTIC_TYPES. Themermaid,plantumlandcsvparameters say what is converted on the server only when it is. - Not measured yet: the new first sentence changes
tools/list(the ChatGPT app needs a Rescan), and which format models choose with it (XML placed by the model or Mermaid) has not been measured again; for flowcharts the measured rule still asks for XML. - Tests:
test/convert.test.js(the three formats, errors with their line, partial input, what is left to the viewer, the switch, the bundle giving the same XML as the modules, the tool's results and parameters),test/plantuml-csv.test.js(the viewer's path, with the switch off and for the types it leaves there).
What the server doesn't convert (or everything, with DRAWIO_CONVERT=off) is converted in the viewer with draw.io's own converters, as in its Arrange > Insert > Advanced menu, and drawn like a Mermaid result: complete (nothing while the text streams in), replacing what is shown, without the XML passes (postLayout, routing, the routing of placed XML), since the converters lay the diagram out. The tool input and the tool result share one conversion (convertSourceToXml). The viewer counts plantuml or csv as given only when its text is more than white space, as the server does (sourceArgument): some hosts send the parameters a call doesn't use as "", and an empty one had stopped the preview of an XML or Mermaid diagram and, for plantuml, shown a converter error. A conversion still running when the tool result or endStreaming comes is dropped (sourceRender): drawio-plantuml takes a while to load, and when the server rejected the call meanwhile, the late conversion replaced its error with the diagram or with the converter's own error. A result without a text block leaves such a conversion running, as it leaves a streamed diagram shown.
- PlantUML:
mxPlantUmlToDrawio.parseText(text, {})from drawio-plantuml, which the viewer loads fromviewer.diagrams.netthe first time (loadPlantUml). It takes the page's ELK for class, state and component diagrams, as in draw.io. Its errors are written for the user (a family it doesn't convert, such as@startchen) and shown in the frame. "Open in draw.io", Copy and Download get the diagram wrapped bymxPlantUmlToDrawio.wrapGroup, the group draw.io makes on insert, which keeps the source, so the diagram can be edited as PlantUML there (currentPlantUmlText). - CSV:
EditorUi.prototype.doImportCsvof the viewer bundle on an offscreen graph, with a stand-in for the editor (convertCsvToXml:editor.graph,csvToArray, no animation, errors throughoptions.error); the graph's container is in the page while labels are measured.%column%placeholders work in labels and styles, andstylePlaceholders=1keeps them in the style. The ELK layouts (verticalflow,horizontalflow,auto) use the page's ELK.orgchartneeds a bundle the viewer doesn't load, so the server turns it away.
The server only checks what would fail in the viewer, so the model can correct it: PlantUML without its @start… and @end… lines, a CSV without a header and a data line after its # lines, the orgchart layout (when the server doesn't convert the CSV; its conversion draws it in layers). It removes blank lines before a CSV's # lines (the import reads them in the first column only), and the viewer does the same on the tool input (trimCsv). PlantUML passed as xml or mermaid (an @start… line, no draw.io XML) is drawn as PlantUML with a note, and the viewer doesn't parse it as Mermaid meanwhile (isPlantUmlText). A client without the app gets a #create= link of type csv for CSV the viewer imports, encoded before it is compressed: draw.io's Graph.decompress runs decodeURIComponent on the inflated data, which throws "URI malformed" on the %fi of a raw %fill%. draw.io has no #create= type for PlantUML, so such a client is asked to draw the diagram again as Mermaid or XML for a link. The model gets the converted diagram in its context, as for Mermaid ("your PlantUML diagram converted to draw.io XML", sourceFormat of modelContextText).
The search_shapes tool uses a pre-built index from shape-search/search-index.json (~10,000 shapes). The index is embedded in generated-html.js at build time (adds ~4 MB to the Worker bundle). The local search runs in-process; the tag lookup map (~100 ms to build, several MB) is built once per process or Worker isolate, on the first search, and shared by every server (getTagMap). If the index file is missing, search_shapes is silently not registered.
When the local index has no strong match for a query (no result exact-matched every term), results are supplemented live from the draw.io icon service (icons.diagrams.net — brand logos and general-purpose concept icons, returned as shape=image styles). The merge pipeline is searchShapesAndIcons in shared/icon-search.js: strong local results lead and icons only fill spare slots; weak (Soundex/OR-fallback) local results keep at most half the budget. A full page of strong local results makes no network request; a service failure degrades to local-only results. The endpoint is configurable via createServer's iconServiceUrl option, wired to DRAWIO_ICON_SERVICE_URL in both entries (set to off to disable). https://icons.diagrams.net is whitelisted in the iframe CSP resourceDomains so the referenced icon images render in the inline viewer.
- Allman brace style: Opening braces go on their own line for all control structures, functions, objects, and callbacks.
- Prefer
function()expressions over arrow functions for callbacks. - See the root
AGENTS.mdfor examples.
Claude.ai sends Accept: application/json, text/event-stream (both). The server prefers JSON when both are present:
const wantsSSE = acceptsSSE && !acceptsJson; // JSON wins when both present- JSON mode (Claude.ai): the Worker's per-request transport is created with
enableJsonResponse: true - SSE mode (Claude Desktop): standard SSE streaming via
handleRequest() - This was a critical fix — the original code matched on
text/event-streamalone, routing Claude.ai to SSE mode which it can't consume
Debug logging is off by default. Enable via wrangler secret put DEBUG (set to "true"). The worker includes diagnostic logging for debugging MCP protocol issues:
| Tag | Content |
|---|---|
[rpc] |
HTTP method, JSON-RPC method name, session ID (prefix + first chars), NEW for an initialize |
[transport-error] |
SDK-internal errors (e.g. "Server not initialized") |
[response] |
Method, session, mode (SSE/JSON), HTTP status, elapsed ms |
[response-body] |
Full response for resources/list, resources/read, tools/list, tools/call |
[ui-flag] |
A failed read/write of a session's "fetched the app resource" Durable Object |
Unexpected exceptions are always logged ([error], with the stack) and answered with a JSON-RPC 500.
Note: At high traffic, wrangler tail enters sampling mode and drops messages. Use wrangler tail --format json | grep to filter for specific methods.
npm start # Node.js server on port 3001
npm run build:worker # Generate generated-html.js
npm run dev:worker # Wrangler local dev (port 8787)
npm run deploy # Build + deploy to Cloudflare WorkersDockerfile packages the Node.js entry. It must be built from the repository root (docker build -f mcp-app-server/Dockerfile -t drawio-mcp-app .) because src/index.js reads ../../shared/*.md and ../../shape-search/search-index.json at startup and src/shared.js imports ../../shared/*.js — a build context of just this directory cannot see them. The root .dockerignore trims the context to what the COPY lines need (no node_modules, .git, public/, or the other packages). wrangler is a devDependency and is left out of the image (npm ci --omit=dev). The Node entry binds to LISTEN (default 127.0.0.1); the image sets LISTEN=0.0.0.0 so -p works, and the docs recommend -p 127.0.0.1:3001:3001 (a plain -p 3001:3001 publishes on every host interface, past ufw and firewalld). ALLOWED_HOSTS turns on the SDK's Host header check — deliberately not implied by a loopback bind, since tunnels (cloudflared, Tailscale Funnel) connect to localhost but forward their public Host. The token, the Origin check and the banner are in Access control (Node entry).
Publishing to Docker Hub — .github/workflows/publish-app-server-image.yml (manual workflow_dispatch, like the tool server's npm publish) builds the Dockerfile for linux/amd64 + linux/arm64, smoke-tests the native build first (initialize must answer as drawio-mcp-app and the io.modelcontextprotocol.server.name=io.draw/mcp label must be present — the label the MCP registry requires before an OCI package can be listed in server.json), then pushes jgraph/drawio-mcp:<version> and :latest, where <version> is this package.json's — bump and commit it first; a tag that already exists on Docker Hub fails the run before anything is built. It also syncs DOCKER_HUB.md to the Hub page (that step needs a token with Read, Write and Delete scope and is continue-on-error). Needs the DOCKERHUB_USER / DOCKERHUB_TOKEN repository secrets (the same names as jgraph/docker-drawio). Run with gh workflow run publish-app-server-image.yml; -f dry_run=true builds and smoke-tests without logging in or pushing.
src/http-security.js, used by src/index.js only. The Worker is the public endpoint mcp.draw.io and has none of it (CORS *, no token); a self-hosted Worker is restricted with Cloudflare Access.
- Why: loopback keeps the server off the network, not off the machine. On a shared dev box every user and process (another agent, a script, a package's install script) can call the port, and Docker's
-p 3001:3001publishes it on every interface past ufw and firewalld. Raised in public replies to the post announcing the Docker image (November 2026);README.md#securityis the user-facing threat model. - Bearer token:
AUTH_TOKEN, orAUTH_TOKEN_FILEnaming a file (Docker/Compose secret, white space trimmed), off by default so existing setups keep working.bearerAuthguards/mcponly (/healthand the favicon stay open for health checks) and runs beforeexpress.json(), so a refused request isn't parsed. Both tokens are hashed with SHA-256 beforetimingSafeEqual, so the comparison takes the same time whatever the lengths. A 401 carriesWWW-Authenticate: Bearer realm="drawio-mcp"(witherror="invalid_token"for a wrong one) and a JSON-RPC error; the[auth]log line names the reason and the peer, never the header.readAuthTokenthrows, which stops the server, on what would otherwise leave authentication off unnoticed: both variables, an empty token (-e AUTH_TOKEN=$UNSET), a file it can't read, or characters a header can't carry. Clients that can't send a static header (Claude.ai's custom connectors: OAuth or none) can't use it. - Origin check: always on, as the Streamable HTTP transport requires against DNS rebinding (MUST validate
Origin). A request withoutOriginpasses: MCP clients outside a browser send none, and it is also how the Python SDK's localhost protection decides. With one, the default allowshttp(s)://localhost,127.0.0.1and[::1]on any port;ALLOWED_ORIGINSreplaces that list (origins compared as browsers send them,normalizeOrigin;nullonly when listed;*any). Refused: 403 with a JSON-RPC error that namesALLOWED_ORIGINS. It runs after the Host check and before the token, so a rebinding page gets 403 whether or not a token is set. - CORS:
corsHeaders, right after the Origin check and before the token, gives a request whoseOriginthat check allowsAccess-Control-Allow-Originwith that origin (Vary: Origin) and exposesMcp-Session-Id,Mcp-Protocol-VersionandWWW-Authenticate, and answers its preflight (OPTIONSwithAccess-Control-Request-Method) with 204, the methods and the headers a Streamable HTTP client sends (Authorizationamong them). Browsers send the preflight without the token, so behindbearerAuthit got a 401 and an origin listed inALLOWED_ORIGINSstill couldn't connect; without the headers a page couldn't read any answer either. ALLOWED_HOSTS:parseAllowedHosts. Unset or empty is no Host check, as before; a value that names no hostname (only commas or white space) stops the server, since dropping its empty entries would otherwise have turned the check off without a word.- Startup banner:
securityBannerprints, after the bind, the endpoint (first line unchanged,MCP App server listening on …), the bind address and whether it is loopback, whether authentication is on and from which variable, the allowed hosts and origins, and aShared machine:verdict (NOT SAFE without a token). Warnings go to stderr: listening beyond loopback without a token (with the Docker-p 127.0.0.1:rule, since the image always listens on0.0.0.0and can't see the mapping), a token under 16 characters,ALLOWED_ORIGINS=*without a token (every origin gets CORS headers, and a page callinglocalhostpassesALLOWED_HOSTS). Never the token. - Tests:
test/http-security.test.jscovers the functions and startssrc/index.json a free loopback port (PORT=0) without and withAUTH_TOKEN_FILE: the banner, no token / wrong token / other scheme (401), the right one (also through the SDK'sStreamableHTTPClientTransportwith the header inrequestInit, as clients configure it), Origin allowed and refused, the Host check,/healthopen, the token absent from the output, an emptyAUTH_TOKENand anALLOWED_HOSTSwithout a hostname stopping the server, and the CORS preflight and headers for an originALLOWED_ORIGINSlists, with a token set. It also readsREADME.mdandDOCKER_HUB.md: adocker runwith a token has--pull alwaysand a Compose examplepull_policy: always(a cached image from before tokens ignoresAUTH_TOKEN), they show thecurlcheck for the 401, and no client command takes the token's value as an argument (other users can read process arguments).