Connect your AI agent to Modudraft
Modudraft exposes a Model Context Protocol (MCP) server that lets Claude, Cursor, or any MCP-compatible client read and modify your cloud diagrams. Your agent can build architecture diagrams, generate sequence flows, scaffold DB schemas, define API endpoints, write notes, manage which tabs are visible, and fill in node metadata - all from a chat window.
Step by step Connect your AI agent
The MCP integration needs a paid Modudraft plan (Pro, Team or Enterprise) or the Pro trial, and an API key. Changes made by your agent appear instantly in your open diagram.
Authentication
The MCP server authenticates using an API key you create in your dashboard. Keys are scoped to diagram read/write - they cannot access account settings or create new keys.
Create an API key
- Go to app.modudraft.com/account
- Open Account, then the API Keys section
- Under API Keys, enter a name (e.g. "Claude Desktop") and choose an expiry
- Click Create - copy the key immediately, it won't be shown again
Keys start with mdft_ and expire after the period you choose (30 days, 90 days, 1 year, or never). You can revoke a key at any time from the Account page.
A key that goes unused for 90 days is revoked automatically, and Modudraft emails you 7 days before a key expires or is auto-revoked. Revoked keys stay in your key list for 30 days. When a key has expired or been revoked, the MCP server tells you which and links to the page where you can create a new one. Creating a key asks you to sign in again if your session is older than 15 minutes, and it can only be done in the web app, never through the MCP server.
Installation
No install needed. The server runs on demand via npx:
MODUDRAFT_API_KEY=mdft_your_key npx -y @modudraft/mcp Or install globally for faster startup:
npm install -g @modudraft/mcp Connecting a client
Claude Desktop
Add the following to your Claude Desktop configuration
(~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"modudraft": {
"command": "npx",
"args": ["-y", "@modudraft/mcp"],
"env": {
"MODUDRAFT_API_KEY": "mdft_your_key_here"
}
}
}
}
Restart Claude Desktop. You should see the Modudraft tools in the tools panel.
Using Claude Desktop and want the agent to import from or write to your repo? Add
MODUDRAFT_PROJECT_ROOTS (see File access).
MODUDRAFT_TOOLSETS is optional too: the default lists the core, modeling,
import and analysis tools, and MODUDRAFT_TOOLSETS="all" lists every tool
(see Toolsets).
Cursor
Add to .cursor/mcp.json in your project (or ~/.cursor/mcp.json globally):
{
"mcpServers": {
"modudraft": {
"command": "npx",
"args": ["-y", "@modudraft/mcp"],
"env": {
"MODUDRAFT_API_KEY": "mdft_your_key_here"
}
}
}
} Any MCP client
Point your client at npx -y @modudraft/mcp with the
MODUDRAFT_API_KEY environment variable set.
The server uses stdio transport - compatible with all standard MCP clients.
In Claude Code, that is one command in your repo:
claude mcp add modudraft -e MODUDRAFT_API_KEY=mdft_your_key_here -- npx -y @modudraft/mcp File access
Some tools work with the source code on your machine. scan_project,
read_file, import_file, import_directory and
watch_project read your docker-compose.yml, Kubernetes manifests,
OpenAPI specs, SQL and .env files to build diagrams. sync_project reads
the same structured files, but never .env files. export (with output_path),
generate_docs and generate_runbook write their output next to your code.
The npx @modudraft/mcp check command reads the same files from the folder you run it in
(see CI drift check).
These tools only use your source-code folders - the repo, or git worktree, you're working on. Your diagrams are saved to your Modudraft account, not to this folder. The server finds the folder from, in order:
- the workspace folders your MCP client shares (MCP roots), if it shares any;
- the optional
MODUDRAFT_PROJECT_ROOTSenvironment variable - one or more repos, separated by:(;on Windows),~allowed; - the folder the server was started in (Claude Desktop starts it from
/, so set the variable there).
Your home folder itself is never used as a source-code folder, and credential files (.ssh,
.aws, .npmrc, private keys and similar) are always refused. Relative paths
resolve against the first source-code folder. If a file tool says file access is disabled and you want to use it, set
MODUDRAFT_PROJECT_ROOTS to your repo. Tools that don't touch local files never need it.
Tools that write files never overwrite an existing file unless you pass overwrite: true.
Toolsets
The default lists the core tools and the modeling, import and
analysis groups; every other group is one load_toolset call away. Set
MODUDRAFT_TOOLSETS=all to list everything, or core for the smallest set.
The core group covers diagram management, nodes and edges, rendering,
discovery, org context and search_diagrams.
modeling Bulk create and node metadata sequences Sequence diagrams: sequences, lanes, messages, fragments database DB tables and ER export api API endpoints, contracts, OpenAPI and AsyncAPI export infra Cloud resources and network devices data_flows Data-flow pipelines and stages views Show and hide tabs, the Notes tab import Read and scan the repo, import files, apply env values export Mermaid, PlantUML, draw.io, Terraform, K8s, Structurizr, write files, generate docs and runbooks analysis Validate, diff, review, cross-diagram suggestions, clone project Watch a repo for drift, generate sequences from the API history Server version history and the local edit log security Threat model: trust zones, data classes, STRIDE threats, the Markdown report states State machines per component, event consumers, Mermaid, XState and PlantUML export MODUDRAFT_TOOLSETS="core"lists the core tools only;"sequences,api"lists core plus those groups;"all"lists everything; unset lists the default groups (core,modeling,import,analysis).- A value made only of unknown names keeps the default groups and prints a warning on stderr.
load_toolset(name)adds a group at runtime and sends a tools-changed notification. If your client doesn't refresh tools afterload_toolset, setMODUDRAFT_TOOLSETSinstead.- Calling a tool by name works even when it isn't listed, if your client lets the agent call a tool it was not shown: the server loads its group and runs it. Otherwise use
load_toolsetorMODUDRAFT_TOOLSETS.
Resources and prompts
Besides tools, the server offers MCP resources and prompts, for clients that support them.
- Resources: each diagram is readable as plain-text line art at
modudraft://diagram/<id>(the architecture tab, the same output asrender_diagram_text). The resource list holds your 50 most recently edited diagrams; any diagram id you can reach can be read by URI. - Prompts:
map_repo(optionalpath) scans a repository and imports what it finds;check_drift(diagram_id) checks a diagram against the project code;structure_review(diagram_id) validates a diagram and lists its structural issues;threat_model(diagram_id) builds a STRIDE threat model and exports the report. Each is one message that names the toolset to load.
Diagram management
Toolset: core
Every tool requires a diagram_id. Use list_diagrams to find yours or create_diagram to start fresh.
list_diagrams List your diagrams from every workspace you belong to: id, name, updatedAt, workspaceId, workspaceName, workspaceKind create_diagram Create a new diagram (uses your personal workspace) get_diagram Read a diagram. By default a summary: the tabs and their sizes, node and edge counts, per-tab outlines (ids, names, types) and the first 3 hints. Pass include for full data: ["diagram"] (nodes, edges, levels), section names (sequence, db-schema, api, cloud, network, data-flow, hints) or ["all"] (everything) delete_diagram Move diagram to Bin (recoverable for 90 days) clear_diagram Remove all content from a diagram layout_diagram Auto-arrange the architecture tab like the editor's Tidy button (direction: LR, TB, RL, BT). Adding or removing nodes and edges also tidies once, after the changes stop - set MODUDRAFT_AUTO_TIDY_MS to change the quiet period, or 0 to turn it off get_share_link Get or create a share link for the diagram Nodes & edges
Toolset: core
add_node Add a component with archetype (compute, database, queue…), optional tool, and position. The tool can be a catalog key or a common name ("Better Auth", "NextAuth", "k8s") and is resolved to the catalog key; an omitted archetype is taken from the tool update_node Change a node's label, tool, or archetype. A tool name is resolved to the catalog key; the archetype is left alone delete_node Remove a node and all its connected edges add_edge Connect two nodes with an optional label and protocol update_edge Change an edge's label or protocol delete_edge Remove a connection add_boundary Add a grouping boundary box around a set of nodes add_note Add a sticky-note annotation to the canvas move_to_level Move items (items: ids, or labels for components) into another component (inside: id or label) or back to the top level (inside: null). Moves that would put a component inside itself are refused Levels. A component can contain other items. add_node, bulk_add_nodes,
add_boundary, add_note and update_node take inside (a component id or label);
update_node also takes c4_kind and description. delete_node takes
inside: "delete" or "lift" for a component that has items inside, and asks before deleting one.
get_diagram returns a levels summary with include: ["diagram"], and render_diagram_text,
layout_diagram and export take level (a component id or label; default is the top level).
validate_diagram reports broken levels as errors and C4 rule breaks as warnings.
Node metadata
Toolset: modeling (except get_node_schema, which is in core)
Each archetype has well-known configuration fields - for example, a database node
expects host, port, replication, and engine-version.
Use these tools to fill in and discover missing configuration.
set_node_metadata Set a single property on a node (e.g. host, port, framework, region) suggest_metadata Scan the diagram and return nodes with missing configuration fields - ask the user to fill them in get_node_schema Get the expected metadata fields for an archetype so you know what to ask for
The get_diagram summary includes the first few hints, and include: ["hints"] returns every one, including the nodes with empty metadata fields.
A good workflow: build the architecture first, then call suggest_metadata and ask
the user for hostnames, regions, frameworks, and other config details before saving.
Sequence diagram
Toolset: sequences (except generate_sequence_from_api, which is in project)
add_sequence_message Add a message between two nodes (node id or exact node label; sync, async, return, create, destroy, note) bulk_add_sequence_messages Add many sequence messages, plus optional loop/alt/opt/par fragments, in one call get_sequence Read just the sequence - messages (with ids and node labels) and fragments - much smaller than get_diagram update_sequence_message Edit one message in place (sender, receiver, label, type) or move it to a new position delete_sequence_message Delete one message; the rest are renumbered and fragments that included it are trimmed add_sequence_participant Register a named participant explicitly generate_sequence_from_api Generate a richer sequence diagram from the API tab - groups endpoints by tag or URL prefix, creates one participant per group, and adds request + response message pairs in HTTP method order. Much more detailed than auto_sequence clear_sequence Remove all sequence messages (leaves architecture untouched) Sequence fragments
Toolset: sequences
Fragments annotate a group of messages with a flow control label - loop,
alt (conditional), opt (optional), or par (parallel).
Each fragment references the message IDs it wraps.
add_sequence_fragment Wrap a set of messages in a fragment - supply kind (loop / alt / opt / par), a condition label (e.g. "payment fails"), and the message_ids to include update_sequence_fragment Change a fragment's kind, condition, or message_ids delete_sequence_fragment Remove a fragment by fragment_id (messages are kept) DB schema (ER diagram)
Toolset: database
add_db_table Add a table with columns to a database node's schema update_db_table Replace a table's column list delete_db_table Remove a table from the schema export_er_diagram Export the DB schema as SQL DDL (CREATE TABLE statements) API schema (OpenAPI)
Toolset: api
add_api_endpoint Add an http, GraphQL, gRPC, WebSocket, or event endpoint to a service node. Its request and response shapes go in contract: per-protocol slots of JSON Schema, where fields are required unless marked optional: true update_api_endpoint Update path, method, summary, tags, or the contract (slots you pass are replaced, the rest are kept). Changing the protocol converts the contract and lists anything dropped delete_api_endpoint Remove an endpoint export_openapi Export the http endpoints as an OpenAPI 3.1 document (JSON, or YAML with format: yaml) export_asyncapi Export the event endpoints as an AsyncAPI 3.0.0 document: a channel per topic, a send operation per publisher and a receive operation per consumer. YAML text by default, JSON with format: json; with output_path it writes the file under your project folders Notes
Toolset: views
Each diagram has a global Markdown notes field - useful for ADRs, runbooks, meeting notes, and sprint plans. Notes are visible in the Notes tab in the editor and persist as part of the diagram file.
get_notes Return the current notes content for a diagram set_notes Replace the notes with new Markdown content append_to_notes Append content to the end of the existing notes - useful for adding meeting notes or decisions without overwriting what's already there replace_in_notes Find and replace exact text in the notes - tick a checkbox or fix a sentence without resending everything Tab management
Toolset: views
Each diagram can show a custom subset of the 8 available tabs: Architecture, Sequence, DB Schema, API Schema, Cloud, Data Flow, Network, and Notes. By default all tabs are visible. Use these tools to tailor the view to the role or use case.
get_enabled_tabs Return the list of tabs currently visible in the diagram. When all tabs are visible (the default), returns all 8 tab types enable_tab Make a tab visible - adds it to the enabled set. If the diagram already shows all tabs, this is a no-op disable_tab Hide a tab without deleting its data. When disabling from an all-tabs state, the remaining 7 tabs become the explicit set. The tab can be re-enabled at any time Discovery (static)
Toolset: core
These tools return static catalog data - no diagram needed.
list_archetypes All 23 node archetypes with their expected metadata fields and default tools list_tools Available technology tools per archetype (postgresql, redis, kafka, aws-ec2…) list_protocols Valid edge protocol values (HTTPS, gRPC, Kafka, WebSocket, GraphQL…) Cloud resources
Toolset: infra
Manage the Cloud diagram tab - K8s clusters, VPCs, subnets, and cloud provider resources. Resources can be nested (e.g. a pod inside a namespace inside a cluster).
add_cloud_resource Add a resource (k8s-cluster, vpc, subnet, ec2, rds, s3, lambda…) - supply type, name, optional parent_id for nesting, and optional key-value config delete_cloud_resource Remove a cloud resource and all its children by resource_id update_cloud_resource Change a resource's name, type, or config Network devices
Toolset: infra
Manage the Network diagram tab - routers, switches, firewalls, racks, and zones. Devices can be nested (e.g. a server inside a rack inside a zone).
add_network_device Add a device (router, switch, firewall, server, access-point, load-balancer, rack, zone…) - supply type, name, optional parent_id for grouping, and optional key-value config delete_network_device Remove a network device and all its children by device_id update_network_device Change a device's name, type, or config Data flow
Toolset: data_flows
Manage the Data Flow diagram tab. You can group stages into named flows, or leave them ungrouped. Stages have a role of source, transform, or sink, an optional technology tool (kafka, spark, dbt, s3…), and an optional description to explain what each stage does. Flows also support edge notes on the arrows between columns.
add_data_flow Create a named flow (e.g. "Ingestion pipeline") - returns a flow_id you can attach stages to. Optional: source_to_transform_note and transform_to_sink_note set labels on the connecting arrows list_data_flows List all named flows in the diagram add_data_flow_stage Add a stage - supply type (source / transform / sink), a label, an optional tool slug (e.g. "kafka", "spark", "dbt", "s3"), an optional flow_id to scope it to a named flow, and an optional description to explain what the stage does delete_data_flow_stage Remove a stage by stage_id update_data_flow_stage Change a stage's type, tool, label, and/or description reorder_data_flow_stages Reorder all stages by providing the complete ordered array of stage_ids File import
Toolset: import
Import existing files from your project directly into a diagram. Use scan_project to
discover what's importable, then import_file to bring it in. Format is detected
automatically from the file path and content.
scan_project Recursively scan a directory and return all importable files with their detected formats - run this first to discover what you can import read_file Read a file inside your repo and return its raw content - useful for files you want to inspect before importing import_file Import a file into the diagram - auto-detects format; supply an optional target_tab (db-schema, api, cloud, network) to override. Re-importing the same file updates its items, adds new ones and removes importer-created items that vanished from the file. Existing items without import history whose name matches are adopted and from then on kept in sync with the file (listed under adopted); other hand-made items are kept. Items are keyed by repository and path, so two repos with the same file never collide. An empty parse is refused unless allow_empty: true Supported import formats
docker-compose.yml Architecture - one node per service, edges from depends_on workspace.dsl / workspace.json Architecture - a Structurizr workspace (the DSL with its !included files, or the JSON): levels, groups, relationships, dynamic views as sequences, deployment on the cloud tab, docs and ADRs in the notes. See Move from Structurizr Kubernetes YAML Cloud tab - Deployment, Service, Ingress, StatefulSet, ConfigMap, Secret, and more Terraform .tf Cloud tab - aws_*, google_*, azurerm_* resources with dependency edges AWS CloudFormation YAML/JSON Cloud tab - 60+ AWS::* resource type mappings with DependsOn edges SQL DDL (.sql) DB schema tab - CREATE TABLE with columns, PKs, FKs, indexes, defaults schema.prisma DB schema tab - model blocks with @relation FK resolution DBML (.dbml) DB schema tab - dbdiagram.io format, inline [ref: >] and standalone Ref: declarations schema.rb (Rails) DB schema tab - create_table blocks, t.timestamps, add_foreign_key TypeORM entities DB schema tab - @Entity, @Column, @ManyToOne, @OneToOne decorators SQLAlchemy models DB schema tab - Column() definitions with ForeignKey() resolution across models dbt schema.yml DB schema tab - models and sources with column tests: (unique, not_null, relationships) OpenAPI 2.x / 3.x API tab - paths, methods, tags, request body, and response codes GraphQL SDL (.graphql) API tab - Query, Mutation, and Subscription fields as endpoints Protocol Buffers (.proto) API tab - service + rpc blocks; detects UNARY, SERVER_STREAM, CLIENT_STREAM Postman collection v2.1 API tab - all requests from nested folders, folder names become tags Insomnia export v4 API tab - requests from all resource groups AsyncAPI YAML/JSON API tab - channels as PUBLISH / SUBSCRIBE endpoints (v2.x and v3.x) .env / .env.example Context only - returns filtered topology metadata (host, port, database, region); sensitive values are always redacted package.json, go.mod, requirements.txt, Gemfile, pom.xml, Cargo.toml Context only - returns a tech-stack summary so the agent can make better architecture suggestions .env security: only topology metadata is ever extracted - hostnames, ports, database names,
and regions. Passwords, tokens, API keys, and any high-entropy string are always replaced with
[REDACTED] regardless of key name.
Export
Toolset: export (except render_diagram_text in core, export_er_diagram in database and export_openapi in api)
Export a diagram to a standard format with one tool, export. Pass format; it returns the generated content as a string, or with output_path writes it to a file in your repo
(it won't overwrite an existing file unless you pass overwrite: true).
The 0.27 names (export_mermaid, export_plantuml, export_drawio, export_terraform, export_k8s_yaml,
export_to_file, export_structurizr) still work in 0.28: they return what they returned before, plus a deprecated field, and they are not listed. They are removed in 0.29.
export Export a diagram. format: mermaid (flowchart, sequence or er via diagram_type), plantuml (component, sequence, er or api), drawio (architecture or db-schema via tab_type), terraform or k8s (from the cloud tab, with warnings), sql (DDL) or openapi (these two only write a file), structurizr_dsl or structurizr_json (with a summary of what was exported, left out or changed; see Export back to Structurizr). Returns the text, or with output_path writes the file under your project folders and returns the path and size (overwrite: true replaces an existing file). level exports one level of the architecture render_diagram_text Draw a tab as plain-text line art any agent or terminal can show - the whole tab or a part of it. Architecture (a node and its neighbours, chosen nodes, a boundary, an archetype), sequence (a message range, chosen participants), DB schema as an ER diagram (a table and its relations, chosen tables, a name prefix or schema, column detail level), cloud and network (nested boxes or a tree: a subtree, a depth, a resource type) and data flow (one lane per flow, sources to transforms to sinks). Unicode or ASCII export_er_diagram Export the DB schema tab as SQL DDL (CREATE TABLE statements) export_openapi Export the API tab as an OpenAPI 3.1 JSON document (http endpoints only) Validation & diff
Toolset: analysis
validate_diagram Check a diagram for issues - dangling edges, orphaned nodes, tables with no PK, duplicate column names, FK references to non-existent tables, duplicate API routes, cloud resources with invalid parent IDs. Returns structured issues with severity (error / warning / info) diff_diagram Compare two diagrams and return a list of changes - nodes, edges, tables, endpoints, and cloud resources that were added, removed, or modified. Useful as a CI check after a PR AI review
Toolset: analysis
AI Architect reviews a design for single points of failure, scaling, bottlenecks, data and consistency, resilience, security basics and patterns. A review costs credits from the same monthly allowance as the web app. Read how it works.
review_diagram Run a Review, or a Deep review with type: "deep". Optional focus points it at one part of the design. Returns the free Quick checks, the findings (each fix lists diagram edits to ask the user about before applying them), a summary, the size tier and the credits left get_review Read the latest saved review of a diagram, free: the Quick checks, the findings, the summary, when and by whom it ran, and whether the diagram changed since. Use it when a review timed out instead of running it again get_ai_usage The credits left this month, when they reset, this month's spending by type, and the price of a Review, a Deep review or a chat message by diagram size. Check it before a Deep review Cross-diagram intelligence
Toolset: analysis
find_shared_services Scan multiple diagrams and find nodes that appear in more than one - identified by matching label and archetype. Useful for auditing shared infrastructure suggest_connections Detect likely missing edges based on archetype pairs - e.g. a service node and a database node with no edge between them probably need one suggest_architecture Generate a suggested node and edge structure from a text description. Pass an optional diagram_id to enable extend mode - the tool fetches what's already in the diagram and only suggests components that are missing, so it adds to your work rather than replacing it clone_diagram Deep-copy a diagram under a new name - all IDs are remapped, useful for creating variant architectures from a template Org context
Toolset: core
The server maintains a local cache of your organization's existing tools, protocols, and naming
conventions - derived from scanning your diagrams. This context is used by suggest_architecture
and suggest_metadata to make suggestions that match how your team already builds.
get_org_context Return the cached org context - most-used tools, protocols, archetypes, and naming patterns across all your diagrams refresh_org_context Force a fresh scan of your diagrams to rebuild the org context cache (cached for 7 days by default) Bulk operations
Toolset: modeling
Add many nodes and edges in a single tool call. The key tool is
apply_architecture - it takes the output of suggest_architecture
directly (nodes array + edges with from_label/to_label) and applies
everything in one shot, including auto-layout.
apply_architecture 1-shot: add all nodes and edges from a suggest_architecture response in a single call. Edges are matched by label - no need to track IDs. Runs auto-layout afterward bulk_add_nodes Add multiple nodes at once - returns a label → id map for use with bulk_add_edges bulk_add_edges Add multiple edges at once - reference nodes by ID (source_id/target_id) or by label (source_label/target_label) Version history
Toolset: history
Snapshots are server versions: named checkpoints that appear in the web app's Version history
alongside automatic versions, shared with everyone who can open the diagram. restore_snapshot adds a new
version; the state before the restore stays in the history, so a restore can be undone by restoring the previous version. Each diagram keeps up to
50 versions on Pro and the Pro trial, 100 on Team and 200 on Enterprise, oldest first; Free has no version history. delete_snapshot was removed
in 0.19.0. The edit log (get_edit_log) stays local to the agent's machine.
snapshot_diagram Save the current diagram state as a named server version (e.g. "before refactor", "v1 baseline") list_snapshots List a diagram's server versions, newest first (legacy local snapshots are still listed and can be restored for this release) restore_snapshot Restore a diagram to a version; snapshot_id is a version id, a version number or a legacy local snapshot id. The state before the restore stays in the history, so it can be undone Edit history
Toolset: history
Every mutation tool (add, update, delete, import, layout, etc.) is automatically logged after a
successful call. The log persists in ~/.modudraft/edit-log.v2.json across sessions,
keyed by diagram ID.
get_edit_log Return the recent edit history for a diagram - tool name, human-readable summary, and timestamp for each call. Returns up to 50 entries, newest first. Useful for answering "what did we change?" without re-fetching the full diagram Threat model
Toolset: security
A threat model lives on the Architecture tab: trust zones on boundaries, data classes and encryption on
arrows and data stores, and a list of STRIDE threats. The agent runs suggest_threats first,
then adds threats specific to each component's tool and archetype (the rules are generic and don't know a
technology's own weaknesses), then fills in mitigations and owners. Threat edits are sent as targeted
changes, so they don't overwrite edits someone is making in the web app at the same time.
get_security_view Boundaries with their trust zones; each component's tool, archetype, zone and (data stores) data class and encryption at rest; each arrow's protocol, data class and encryption in transit; and the threats suggest_threats Run the Modudraft STRIDE rules and add the new suggestions. Safe to re-run: it never adds a duplicate, and a threat marked not-applicable never comes back add_threat Add a threat (source: agent) about a component, an arrow, a boundary or the whole system update_threat Change a threat's title, STRIDE category, target, severity, status, description, mitigation or owner delete_threat Delete a threat (for a rule suggestion that doesn't apply, mark it not-applicable instead) set_trust_zone Set a boundary's trust zone: internet, dmz, internal, restricted or third-party set_data_class Set the data class (public, internal, pii, credentials, payment) of an arrow or a data store, with encryption in transit (arrows) or at rest (data stores) export_threat_model The Markdown threat-model report, the same as the web app's download; with path it writes a .md file under your project folders State machines
Toolset: states
Any component on the Architecture tab can own state machines: nested, parallel, history and final states,
with transitions triggered by plain events, by API-tab events and endpoints, by timers or eventlessly.
The quickest way to build one is apply_state_machine with one nested JSON shape; the other tools
make targeted edits. States are referenced by id, by a dotted path from the machine root
(Box.Inner) or by a name unique in the machine. Edits are sent as targeted changes, so they
don't overwrite edits someone is making in the web app at the same time. Names, guards and actions are
capped at 200 characters, descriptions at 2000.
list_state_machines The machines of a diagram or of one component, with state, transition and warning counts get_state_machine One machine as a tree of states with their transitions, linked endpoints resolved (or shown as removed), and its warnings create_state_machine Create a machine on a component with one initial state ("Idle" unless you name it) update_state_machine Rename a machine, change its description or initial state, or move it to another component delete_state_machine Delete a machine with its states and transitions apply_state_machine Build a whole machine from one nested JSON shape in one write (all or nothing, at most 500 operations), or replace one with machine_id. Ambiguous targets and broken rules are refused with the state path and the fix add_state Add a state at the top level or inside a compound or parallel state; a parallel state starts with two regions update_state Change a state's name, kind, parent, initial child, history type, entry and exit actions or description delete_state Delete a state with its child states and the transitions touching them; initial states are reassigned add_transition Add a transition with one trigger (event, API event, endpoint, timer or always), an optional guard and actions update_transition Change a transition's source, target (empty for internal), trigger, guard, actions or description delete_transition Delete a transition set_event_consumers Set which components consume an event endpoint; this completes the AsyncAPI export and clears the missing-consumer warning export_state_machine Export a machine as Mermaid, XState or PlantUML text; with path it writes the file under your project folders Project watch
Toolset: project
Associate a local project directory with a diagram. After the initial snapshot, the MCP server
can detect which files changed so you know exactly what needs to be re-imported.
get_diagram will also hint when watched files have changed.
watch_project Scan a directory and save a snapshot of all importable files (path, format, size, modified time). Stored in ~/.modudraft/watch.v2.json check_project_drift Re-scan the watched directory and compare against the snapshot - returns lists of added, modified, and removed files so you know exactly what to re-import. It only reports: drift stays until you pass acknowledge: true; re-importing a modified file clears it for that file, while new files stay listed as added until acknowledged; truncated scans are flagged unwatch_project Remove the watch association for a diagram sync_project Compare repo files with a diagram and update it. Previews by default (dry_run: true); dry_run: false saves once into version history. Can write modudraft.json with write_config. See CI drift check
After calling watch_project, the hints in every get_diagram reply will include
a note if any watched files have changed - even if you haven't explicitly run
check_project_drift. This makes your diagrams a living document that stays in
sync with your codebase.
CI drift check
sync_project compares the files in your repo with a diagram and brings the diagram
up to date. The same engine powers the check command and the
modudraft/drift-check GitHub Action, which check every pull request against your diagram.
The full guide (supported files, modudraft.json, exit codes, keys and example workflows)
is on the CI drift check page.
Search
Toolset: core
Search across all your diagrams by node label, archetype, or technology - without fetching every diagram manually.
search_diagrams Search node labels, archetypes, and tool names across all diagrams. Returns matching diagrams and the specific nodes that matched. Scope to label, archetype, or tool, or search all three at once Env auto-apply
Toolset: import
Parse a .env or .env.example file and automatically fill in node
metadata - no manual matching needed. Sensitive values are always redacted; only topology
metadata (host, port, database name, region) is applied.
apply_env_to_nodes Match env vars to nodes by label prefix (e.g. POSTGRES_HOST → node labelled "Postgres") and auto-fill metadata. Reports ambiguous matches that need manual assignment Docs & runbook
Toolset: export (except import_directory, which is in import)
Generate structured Markdown documents directly from a diagram - no manual writing required.
Both tools optionally write to a file path via output_path.
import_directory Scan a directory and import all importable files in one call, in the right order: architecture first, then cloud, then DB schemas, then API specs generate_docs Generate an architecture document - Mermaid diagram, component table, connection summary, DB schema, API endpoints, sequence diagram. Paste into README, PR, or wiki generate_runbook Generate an incident response runbook - services table with host/port/restart commands, per-service dependency map, blast-radius analysis (what breaks when X goes down), health check URLs, happy-path sequence diagram, and incident checklist Examples
Design a microservices architecture
Create a new Modudraft diagram called "E-commerce backend". Add an API
gateway, user service, product service, order service, and Postgres databases
for each service. Connect them and run a left-to-right layout. Fill in node configuration from your environment
Check my Modudraft diagram for missing metadata. I'll share my .env file
- use the hostnames and ports to fill in the database and cache nodes. Generate a sequence diagram from the architecture
Look at my Modudraft architecture diagram and auto-generate a sequence
diagram showing the user checkout flow. Scaffold a DB schema
Add the DB schema for the order service node: orders, order_items,
and payments tables with the right columns and foreign keys. Then export
the SQL DDL. Add a retry loop to a sequence diagram
In my Modudraft sequence diagram, wrap the payment-service messages
in a loop fragment with condition "retry up to 3 times on timeout". Map a cloud deployment
Add a Cloud diagram showing a VPC with two private subnets,
an RDS instance, an ECS cluster, and an Application Load Balancer. Export the API contract
Add REST endpoints to the API gateway in my Modudraft diagram -
GET /users, POST /orders, GET /products. Export the OpenAPI spec. Scan a project and import everything
Scan ~/code/myapp and import everything you find into diagram "My App".
Start with the docker-compose, then Prisma schema, then OpenAPI spec. Import a Terraform stack into a cloud diagram
Import infra/main.tf into the cloud tab of diagram "Production Infra".
Then layout the diagram top-to-bottom. Validate a diagram before a deploy
Validate diagram "Checkout Service". Tell me about any dangling edges,
orphaned nodes, or DB tables with missing primary keys. Diff two versions of a diagram
Compare diagram "v1 Architecture" with "v2 Architecture" - what nodes,
edges, and tables changed between the two versions? Suggest an architecture from a text description
Suggest an architecture for a checkout service that uses Stripe for
payments, Postgres for orders, Redis for session caching, and publishes
events to Kafka. Add the suggested nodes and edges to diagram "Checkout". Export a diagram to a local file
Export diagram "Production Infra" as Terraform stubs and save the file
to ./infra/generated.tf. Then export the architecture as Mermaid and
append it to ./docs/architecture.md. Find shared infrastructure across diagrams
Which services appear in more than one of our diagrams?
I want to know what's shared so we can extract it into a shared-services diagram. Generate a rich sequence diagram from an imported API spec
Import our openapi.yaml into diagram "Checkout Service", then generate a
sequence diagram from the API endpoints - group by tag, include response messages. Keep a diagram in sync with the codebase
Watch ~/code/myapp for diagram "My App". Then, every time I ask you to
check the diagram, tell me if any files have drifted and offer to re-import them. Recap what changed in this session
What did we add to diagram "Checkout Service" in this session?
Show me the edit history. Extend an existing diagram from a description
We're adding a fraud-detection service that uses a Kafka topic and
a Redis cache. Suggest what to add to diagram "Checkout Service" - only
the pieces that aren't already there. Build a full architecture in one shot
Suggest an architecture for a SaaS platform with a React frontend,
API gateway, auth service, Postgres, Redis, and Kafka - then apply it
to diagram "Platform v2" in one call and layout the result. Snapshot before a big refactor
Save a snapshot of diagram "Checkout Service" labelled "before
microservices split", then split the monolith into three services.
If anything looks wrong, restore the snapshot. Find where a technology is used across diagrams
Search all our diagrams for "kafka" - show me every diagram that
uses Kafka and which nodes reference it. Auto-fill node metadata from the environment
Apply our .env.production file to diagram "Production" - fill in
host, port, and database name for every node you can match automatically,
and tell me which ones need manual input. Generate a runbook for on-call
Generate an incident runbook from diagram "Checkout Service" and
save it to ./docs/runbook.md - I want the blast radius table and
restart commands for each service. Import an entire project in one call
Import everything from ~/code/myapp into diagram "My App" in one go -
docker-compose, Prisma schema, and OpenAPI spec. Write an ADR into the Notes tab
Write an ADR for the decision to use Kafka over RabbitMQ in diagram
"Event Platform" and save it to the Notes tab. Append meeting notes to an existing diagram
Append today's architecture review notes to diagram "Checkout Service" -
we decided to add a Redis cache in front of the product service and to
deprecate the synchronous inventory check. Tailor a diagram to a specific role
For diagram "Product Overview", hide the Cloud and Network tabs -
this is for the backend team who only care about Architecture, Sequence,
DB Schema, and API.