Draw.io MCP Server

repository·main·Indexed 23 days ago

https://github.com/lgazo/drawio-mcp-server

A Model Context Protocol (MCP) server and browser plugin that enables AI agents to programmatically create, inspect, and modify diagrams in Draw.io. It supports a built-in hosted editor mode and a browser extension mode for connecting to existing Draw.io sessions. Includes a development proxy for HTTPS/WebSocket verification and a compatibility layer for handling Draw.io versioning.

Tokens
47.6K
Snippets
101
Records
222
Agent score
79%

What's inside drawio-mcp-server

  1. Core architecture and capabilities

    main

    The Draw.io MCP server is built on several key technical pillars:

    • Bi-directional Communication: Enables real-time interaction between MCP clients and Draw.io.
    • WebSocket Bridge: Uses a built-in WebSocket server (defaulting to port 3333) to facilitate connectivity with the browser extension.
    • Standardized Protocol: Maintains full MCP compliance for seamless integration with AI agents.
    • Event-driven System: Built using Node.js EventEmitter.
    • Validation: Uses Zod schema validation for all tool parameters to ensure data integrity.
    • Debugging: Supports Chrome DevTools integration via the --inspect flag.
  2. Capabilities and Features of Draw.io MCP Server

    main

    The Draw.io MCP server provides tools for AI agents to programmatically interact with diagrams. Key capabilities include:

    • Document & Page Management: List connected documents, target specific tabs/files using list-documents and target_document, and manage pages via list-pages, create-page, copy-page, and rename-page.
    • Diagram Inspection: Read shapes, pages, layers, and cell properties.
    • Diagram Modification: Add, edit, or delete shapes, edges, and labels. Supports edge geometry control (waypoints) and parent-child relationships for grouping.
    • Layer Management: Create, switch, and organize layers.
    • Automatic Stencil Discovery: Automatically discovers vendor stencils (AWS, GCP, Azure, Cisco19, CiscoSafe) at runtime, allowing agents to use icons like mxgraph.gcp2.cloud_run without manual catalogs.
    • Mermaid Integration: Import, embed, or expand Mermaid diagrams.
    • Data Formats: Import/export via XML, SVG (with embedded XML), or PNG (with embedded XML).
  3. How tool version dispatching works in the plugin

    main

    When a tool is invoked, the plugin uses a dispatch shell to match the detected Draw.io version against a COMPAT_MATRIX.

    Dispatch Outcomes:

    • matched: The tool runs the implementation specifically designed for that version range.
    • above-window: The version is newer than the tested window. The tool runs using the newest available implementation, but a warning is emitted via report.ts.
    • below-floor: The version is too old. The tool returns a failure response indicating the required minimum version.
    • no-version: The version could not be detected. The tool returns a failure response.
    // Example of the tool wrapper logic used in the plugin
    export function import_mermaid(
      ui: any,
      options: Record<string, unknown>,
    ) {
      const detected = detectDrawioVersion(ui);
      const outcome  = dispatchTool("import-mermaid", detected, COMPAT_MATRIX);
    
      switch (outcome.kind) {
        case "matched":
          return outcome.impl(ui, options);
    
        case "above-window":
          // run on newest impl, but emit a warn-level mismatch via report.ts
          reportMismatch("import-mermaid", outcome);
          return COMPAT_MATRIX.versionedTools["import-mermaid"].at(-1)!.impl(ui, options);
    
        case "below-floor":
          return Promise.resolve({
            success: false,
            message: `drawio v${outcome.detected} predates supported floor v${outcome.floor}. Upgrade drawio.`,
          });
    
        case "no-version":
          return Promise.resolve({
            success: false,
            message: `cannot detect drawio version (${outcome.reason}); pin a supported drawio build.`,
          });
      }
    }
  4. How the `drawio-mcp-server` vendoring mechanism works

    main

    To ensure the drawio-mcp-server can be published as a standalone npm package without a runtime dependency on the private drawio-mcp-compat package, the project uses a build-time vendoring strategy.

    Instead of declaring drawio-mcp-compat as a dependency, a vendor:compat script copies the source files from packages/drawio-mcp-compat/src/* into packages/drawio-mcp-server/src/vendored/compat/* immediately before every build or development session.

    Key aspects of this model:

    • Source of Truth: The canonical source remains in the drawio-mcp-compat package.
    • Git Hygiene: The generated src/vendored/ directory is ignored via .gitignore to prevent local build artifacts from being committed.
    • Import Strategy: The server code (specifically matrix.ts) uses relative imports pointing to the vendored files (e.g., ../vendored/compat/index.js) rather than the package name. This ensures the compiled JavaScript contains no references to the workspace package.
  5. TLS Configuration Validation Rules

    main

    When configuring TLS, the following validation rules apply:

    1. Mutual Exclusivity: You cannot combine --tls-auto with --tls-cert/--tls-key. You must choose either automatic management or manual file provision.
    2. Completeness: If using manual mode, both --tls-cert and --tls-key must be provided.
    3. Activation: Enabling --tls without specifying a mode (auto or manual) will result in an error.
    4. Dependency: Using --tls-cert or --tls-key without the base --tls flag is not allowed.
  6. How `drawio-mcp-server` handles `drawio-mcp-compat` dependencies

    main

    The drawio-mcp-server package uses a vendoring strategy to include compatibility utilities from the drawio-mcp-compat package without creating a runtime dependency on a private npm package.

    Instead of importing from the drawio-mcp-compat package directly, the server copies the source files from the compat package into a local src/vendored/compat directory during the build process. This allows the server to be published to npm successfully while still sharing the same logic used by the drawio-mcp-plugin.

    Key Concepts

    • Canonical Source: The source of truth remains packages/drawio-mcp-compat/src/.
    • Vendored Source: The server uses a generated copy located at packages/drawio-mcp-server/src/vendored/compat/.
    • Import Pattern: Code within the server that requires compatibility utilities must import from the relative path ../vendored/compat/index.js rather than the package name.

    Build Workflow

    To ensure the vendored files exist before compilation, the vendor:compat script must be run before tsc or any other build command. This is handled automatically by the standard build and dev scripts in the server package.

  7. Understand the Draw.io Version Compatibility Architecture

    main

    The project implements a version compatibility system to ensure the MCP server and its tools work correctly across different eras of Draw.io. The architecture relies on a shared package, drawio-mcp-compat, which provides the core logic for version detection and validation.

    Key components include:

    • drawio-mcp-compat: A shared package containing pure types and helper functions for version comparison.
    • drawio-mcp-plugin: Handles runtime detection of the Draw.io version via detectDrawioVersion(ui), dispatches tools based on the detected version using a compatibility matrix, and reports compatibility state via WebSocket handshakes.
    • drawio-mcp-server: Mirrors the compatibility matrix to manage assets and uses log-report.ts to consume plugin handshakes and emit diagnostic logs.
    • drawio-mcp-extension: Provides a CompatBanner and CompatState in the background bridge to notify users via a popup banner if their Draw.io version falls outside the supported window.
  8. Target documents and pages in Draw.io MCP

    main

    All live Draw.io tools operate on a connected browser tab. To interact with a specific document or page, you must use targeting selectors.

    Document Targeting

    Use list-documents to find connected instances. Each instance has an id (the instance ID of the browser tab, not a file path).

    • Single Document: If only one document is connected, target_document is optional.
    • Multiple Documents: If multiple tabs are open, every live tool must include target_document: { "id": "..." }.
    • Failure Case: If no documents are connected, tools fail with No connected Draw.io documents.

    Page Targeting

    Page-scoped tools require a target_page selector. Use exactly one of:

    • { "index": 0 } (zero-based index from list-pages)
    • { "id": "page-id-from-list-pages" } (stable ID, recommended for workflows)

    Note on UI-bound tools: Tools like get-selected-cell, set-active-layer, get-active-layer, import-diagram, and export-diagram operate through the visible page and may cause the browser to switch pages.

  9. Understand TLS Certificate Storage and XDG Paths

    main

    When using automatic TLS generation, the server stores certificates and keys in an XDG-compliant data directory based on your operating system. You can override this location using the --tls-dir flag.

    Default Storage Locations

    | Platform | Default Path | |---|---|---| | Linux | $XDG_DATA_HOME/drawio-mcp-server/tls (defaults to ~/.local/share/drawio-mcp-server/tls) | | macOS | ~/Library/Application Support/drawio-mcp-server/tls | | Windows | %LOCALAPPDATA%\drawio-mcp-server\Data\tls (defaults to ~/AppData/Local/drawio-mcp-server/Data/tls) |

    Managed Files

    The following files are managed within the TLS directory:

    • ca.crt: The Certificate Authority certificate.
    • ca.key: The Certificate Authority private key.
    • server.crt: The server's leaf certificate.
    • server.key: The server's leaf private key.
    • meta.json: Metadata used for tracking certificate state and SAN hashes.
  10. How TLS SAN (Subject Alternative Name) Drift Detection Works

    main

    To ensure certificates remain valid when the server's host configuration changes, the server uses SAN (Subject Alternative Name) drift detection.

    By default, the server includes localhost, 127.0.0.1, and ::1 in the SAN list. If an explicit --host is provided, it is added to the list. The server generates a stable hash of the SAN list. If the current host configuration results in a different SAN list than what is recorded in the certificate's metadata, the server detects 'SAN drift' and automatically regenerates the leaf certificate to match the new host configuration.

  11. How page execution and document targeting works

    main

    The server manages interactions with Draw.io through a hierarchical targeting system. To ensure stability, especially when multiple agents are active, you must understand how tools select their targets:

    1. Document Targeting: Tools use target_document to specify which Draw.io tab to interact with. If only one document is connected, the server can auto-select it. If multiple documents are open, you must provide the id obtained from the list-documents tool.
    2. Page Targeting: Page-scoped tools use target_page selectors. You can address pages using either a stable { id } or an { index }.
    3. Execution Modes: Page execution supports visible-page, background-page, and hybrid-page modes, which determine if the operation requires the Draw.io UI state.
    4. Concurrency Control: Live operations are serialized per document using a FIFO (First-In-First-Out) queue. This prevents multiple MCP clients from interleaving page switches and writes within the same tab.

    Important Limitation: The server only communicates with already-open Draw.io tabs. It cannot open new files, open new browser tabs, or switch tabs for you.