Skip to main content
Glama
AutoCAD MCP Server

AutoCAD MCP Server

by MuriloM676

🏗️ AutoCAD MCP Server

Automatize o AutoCAD (ou gere DWG/DXF headless) por linguagem natural, através do Model Context Protocol. Uma API, dois backends: File IPC (AutoCAD real) e ezdxf (headless, sem AutoCAD).


✨ O que este projeto faz

  • 8 ferramentas consolidadas (drawing, entity, layer, block, annotation, pid, view, system) sobre uma Ăşnica API.

  • Backend File IPC: controla o AutoCAD LT 2024+ real via mcp_dispatch.lsp + JSON em diretĂłrio temporário — sem roubar o foco da janela (PostMessageW(WM_CHAR)).

  • Backend ezdxf: geração de DXF totalmente headless (Linux, macOS, WSL), com render por matplotlib.

  • system(operation="execute_lisp"): executa AutoLISP arbitrário — vira uma plataforma de automação extensĂ­vel (plugins, fiberQ, FTTH, P&ID...).

  • Screenshots do desenho (Win32 PrintWindow no AutoCAD; render no headless).


Related MCP server: multiCAD-mcp

🚀 Como funciona

MCP Client (Claude / opencode / Cursor)
     │
     │  stdio · JSON-RPC
     â–Ľ
Python MCP Server (autocad_mcp — 8 tools)
     │
     ├──► File IPC ──► C:/temp/*.json ──► mcp_dispatch.lsp (AutoCAD LT)
     │      PostMessageW(WM_CHAR) → sem roubo de foco
     │
     └──► ezdxf ──► documento DXF em memória (headless)
            render de screenshot via matplotlib

Backend

Runtime

Precisa de AutoCAD?

Screenshot

File IPC

Windows + Python

✅ Sim — AutoCAD LT 2024+

Win32 PrintWindow

ezdxf

Qualquer plataforma

❌ Não (headless)

matplotlib

AUTOCAD_MCP_BACKEND=auto (padrĂŁo) tenta o File IPC e cai para ezdxf se nĂŁo encontrar a janela do AutoCAD.


📦 Instalação

Pré-requisitos (backends File IPC)

  • Windows 10/11 (usa APIs Win32 para envio de mensagens sem foco)

  • AutoCAD LT 2024 ou mais novo — AutoLISP foi adicionado ao LT em 2024 (Windows). AutoCAD LT para Mac nĂŁo suporta AutoLISP.

  • Python 3.10+ nativo do Windows (nĂŁo Ă© o Python do WSL)

  • Gerenciador de pacotes uv (guia de instalação)

O backend headless ezdxf roda em qualquer plataforma (Linux, macOS, WSL) sem AutoCAD instalado, para geração offline de DXF.

1. Clone e instale

git clone https://github.com/puran-water/autocad-mcp.git
cd autocad-mcp
uv sync

2. Carregue o dispatcher LISP no AutoCAD LT

Abra o AutoCAD LT e carregue lisp-code/mcp_dispatch.lsp com APPLOAD:

  1. Digite APPLOAD na linha de comando do AutoCAD.

  2. Navegue até <repo>/lisp-code/mcp_dispatch.lsp.

  3. Clique em Load.

  4. VocĂŞ deve ver: === MCP Dispatch v3.1 loaded === e Ready for commands via (c:mcp-dispatch).

Dica: adicione o arquivo ao Startup Suite (na caixa APPLOAD) para carregar automaticamente em todo desenho.

3. Configure seu cliente MCP

Adicione à configuração do seu cliente MCP (ex.: Claude Desktop claude_desktop_config.json):

{
  "mcpServers": {
    "autocad-mcp": {
      "command": "C:\\path\\to\\autocad-mcp\\.venv\\Scripts\\python.exe",
      "args": ["-m", "autocad_mcp"],
      "env": { "AUTOCAD_MCP_BACKEND": "auto" }
    }
  }
}

Pontos-chave:

  • command deve apontar para o Python do Windows dentro do venv do projeto (nĂŁo o Python do WSL).

  • AUTOCAD_MCP_BACKEND pode ser auto (padrĂŁo — tenta File IPC, cai para ezdxf), file_ipc (exige AutoCAD) ou ezdxf (somente headless).

Rodando a partir do WSL

Se seu cliente MCP roda no WSL (ex.: Claude Code), lance o servidor via cmd.exe para que execute como processo nativo do Windows:

{
  "mcpServers": {
    "autocad-mcp": {
      "type": "stdio",
      "command": "cmd.exe",
      "args": ["/d", "/s", "/c", "cd /d C:\\path\\to\\autocad-mcp && .venv\\Scripts\\python.exe -m autocad_mcp"],
      "env": { "AUTOCAD_MCP_BACKEND": "auto" }
    }
  }
}

4. Verifique

Do seu cliente MCP, chame:

system(operation="status")

VocĂŞ deve ver backend: "file_ipc" se o AutoCAD estiver rodando, ou backend: "ezdxf" em modo headless.


đź§° Ferramentas

O servidor expõe 8 ferramentas sobre transporte stdio MCP:

drawing — Gestão de arquivos/desenhos

create, open, info, save, save_as_dxf, plot_pdf, purge, get_variables, undo, redo

Operação

Descrição

File IPC

ezdxf

create

Cria novo desenho vazio

âś…

âś…

open

Abre um .dwg existente (FILEDIA suprimido)

âś…

❌

info

Extents, contagem de ent., layers, blocks

âś…

âś…

save

Salva (QSAVE, ou path com SAVEAS)

âś…

âś…

save_as_dxf

Exporta como DXF

âś…

âś…

plot_pdf

Plota para PDF

âś…

❌

purge

Limpa objetos nĂŁo usados

âś…

❌

get_variables

Obtém variáveis de sistema

âś…

❌

undo / redo

Desfazer / refazer

âś…

❌

create agora zera e limpa o desenho atual (apaga tudo + purge) em vez de _.NEW, preservando o namespace do dispatcher LISP.

entity — CRUD + modificação

Criar: create_line, create_circle, create_polyline, create_rectangle, create_arc, create_ellipse, create_mtext, create_hatch Ler: list, count, get Modificar: copy, move, rotate, scale, mirror, offset, array, fillet, chamfer, erase

layer — Camadas

list, create, set_current, set_properties, freeze, thaw, lock, unlock

block — Blocos e atributos

list, insert, insert_with_attributes, get_attributes, update_attribute, define

annotation — Texto, cotas e líderes

create_text, create_dimension_linear, create_dimension_aligned, create_dimension_angular, create_dimension_radius, create_leader

pid — Diagrama P&ID (biblioteca CTO)

setup_layers, insert_symbol, list_symbols, draw_process_line, connect_equipment, add_flow_arrow, add_equipment_tag, add_line_number, insert_valve, insert_instrument, insert_pump, insert_tank

A biblioteca CTO (src/autocad_mcp/pid/cto_library.py) cataloga 600+ símbolos ISA 5.1-2009 em .dwg por categoria (válvulas, bombas, tanques, instrumentos, etc.). No backend headless os símbolos passam por conversão DWG→DXF via ezdxf.addons.odafc.

view — Viewport e screenshot

zoom_extents, zoom_window, get_screenshot

get_screenshot captura a view atual do AutoCAD como PNG via PrintWindow (Win32) — funciona mesmo com o AutoCAD minimizado. No backend ezdxf, o render é via matplotlib.

system — Gestão do servidor

status, health, get_backend, runtime, init, execute_lisp


🧪 execute_lisp — plataforma de automação ilimitada

Além das ferramentas prontas, o servidor pode rodar qualquer AutoLISP:

system(operation="execute_lisp", data={"code": "(+ 1 2)"})

Isso transforma o servidor de um conjunto fixo de comandos em uma plataforma extensível — por exemplo, para acessar plugins LISP de terceiros (fiberQ/FTTH/G-PON):

system(operation="execute_lisp", data={"code": "(c:FQ)"})
system(operation="execute_lisp", data={"code": "(command \"_FQKABL\")"})

execute_lisp funciona somente no backend File IPC.


⚙️ Variáveis de ambiente

Variável

PadrĂŁo

Descrição

AUTOCAD_MCP_BACKEND

auto

Seleção: auto, file_ipc, ezdxf

AUTOCAD_MCP_IPC_DIR

C:/temp

DiretĂłrio dos arquivos IPC (deve coincidir nos lados Python e LISP)

AUTOCAD_MCP_IPC_TIMEOUT

10.0

Timeout do IPC em segundos (1–300)

AUTOCAD_MCP_ONLY_TEXT

false

Desabilita screenshots (sĂł texto)

CTO_LIBRARY_PATH

C:/PIDv4-CTO

Raiz da biblioteca CTO de sĂ­mbolos P&ID

Importante: se você mudar AUTOCAD_MCP_IPC_DIR, precisa atualizar a variável *mcp-ipc-dir* no mcp_dispatch.lsp para corresponder.


đź’» Compatibilidade com AutoLISP no LT

AutoLISP foi adicionado ao AutoCAD LT no lançamento de 2024 (Windows). AutoCAD LT para Mac não suporta AutoLISP.

Suportado (LT 2024+ Windows)

NĂŁo suportado

.lsp / .fas / .vlx / .dcl

VLIDE (Visual LISP IDE)

Todas as funções vl-*

vlax-* (ActiveX/COM)

I/O de arquivo (open, read-line, ...)

Express Tools

Acesso a entidades (entget, entmod, ...)

Operações 3D

Selection sets

AutoLISP no Mac

O dispatcher mcp_dispatch.lsp Ă© totalmente compatĂ­vel com LT 2024+.


đź§Ş Desenvolvimento

uv sync
uv run pytest tests/ -v

🆕 O que há de novo (v3.1)

  • execute_lisp — executa AutoLISP arbitrário via arquivo temporário. Vira uma plataforma de automação extensĂ­vel.

  • Undo / Redo — passo Ăşnico via ferramenta drawing.

  • Abrir desenho — abre .dwg existentes programaticamente (FILEDIA suprimido).

  • Criar desenho — zera e limpa o desenho atual (apaga tudo + purge), preservando o namespace do dispatcher.

  • Salvar com caminho — save com path usa SAVEAS; sem path usa QSAVE.

  • Correção get_variables — respeita o parâmetro names.

  • Correção polyline/leader — arrays de pontos codificados em formato separado por ponto e vĂ­rgula.

  • Prefixo ESC — envia 2x ESC antes de cada dispatch para cancelar comandos pendentes de timeouts anteriores.

  • Fallback UTF-8/cp1252 — lida com caracteres nĂŁo-ASCII nos arquivos de resultado LISP (AutoCAD grava Windows-1252).

  • Timeout IPC configurável — AUTOCAD_MCP_IPC_TIMEOUT (1–300s, padrĂŁo 10).

  • Init thread-safe — asyncio.Lock evita corridas de inicialização paralela.


🙏 Agradecimentos

Este projeto é uma adaptação e expansão do servidor de código aberto puran-water/autocad-mcp (MIT). Agradecemos aos contribuidores originais por criar a base.

📄 Licença

Licenciado sob a MIT License. Veja o arquivo LICENSE.

Available Tools

8 tools
annotationA

Annotation: text, dimensions, and leaders.

Operations: create_text — data: {x, y, text, height?, rotation?, layer?} create_dimension_linear — data: {x1, y1, x2, y2, dim_x, dim_y} create_dimension_aligned — data: {x1, y1, x2, y2, offset} create_dimension_angular — data: {cx, cy, x1, y1, x2, y2} create_dimension_radius — data: {cx, cy, radius, angle} create_leader — data: {points: [[x,y],...], text}

Inputs: operation (required), data, include_screenshot. Returns: result

blockA

Block definition, insertion, and attribute management.

Operations: list — List all block definitions. insert — data: {name, x, y, scale?, rotation?, block_id?} insert_with_attributes — data: {name, x, y, scale?, rotation?, attributes: {tag: value}} get_attributes — data: {entity_id} update_attribute — data: {entity_id, tag, value} define — data: {name, entities: [{type, ...}]}

Inputs: operation (required), data, include_screenshot. Returns: result

drawingA

Drawing file management.

Operations: create — Create a new empty drawing. data: {name?} open — Open an existing drawing. data: {path} info — Get drawing extents, entity count, layers, blocks. save — Save current drawing. data: {path?} (saves to path if given, else QSAVE) save_as_dxf — Export as DXF. data: {path} plot_pdf — Plot to PDF. data: {path} purge — Purge unused objects. get_variables — Get system variables. data: {names: [...]} undo — Undo last operation. redo — Redo last undone operation.

Inputs: operation (required), data, include_screenshot. Returns: result

entityA

Entity creation, querying, and modification.

Create operations: create_line — x1, y1, x2, y2, layer? create_circle — data: {cx, cy, radius}, layer? create_polyline — points: [[x,y],...], data: {closed?}, layer? create_rectangle — x1, y1, x2, y2, layer? create_arc — data: {cx, cy, radius, start_angle, end_angle}, layer? create_ellipse — data: {cx, cy, major_x, major_y, ratio}, layer? create_mtext — data: {x, y, width, text, height?}, layer? create_hatch — entity_id, data: {pattern?}

Read operations: list — layer? → list entities count — layer? → count entities get — entity_id → entity details

Modify operations: copy — entity_id, data: {dx, dy} move — entity_id, data: {dx, dy} rotate — entity_id, data: {cx, cy, angle} scale — entity_id, data: {cx, cy, factor} mirror — entity_id, x1, y1, x2, y2 offset — entity_id, data: {distance} array — entity_id, data: {rows, cols, row_dist, col_dist} fillet — data: {id1, id2, radius} chamfer — data: {id1, id2, dist1, dist2} erase — entity_id

Inputs: operation (required), x1, x2, y1, +6 more. Returns: result

layerA

Layer creation and management.

Operations: list — List all layers with properties. create — data: {name, color?, linetype?} set_current — data: {name} set_properties — data: {name, color?, linetype?, lineweight?} freeze — data: {name} thaw — data: {name} lock — data: {name} unlock — data: {name}

Inputs: operation (required), data, include_screenshot. Returns: result

pidA

P&ID drawing with CTO symbol library.

Operations: setup_layers — Create standard P&ID layers. insert_symbol — data: {category, symbol, x, y, scale?, rotation?} list_symbols — data: {category} draw_process_line — data: {x1, y1, x2, y2} connect_equipment — data: {x1, y1, x2, y2} add_flow_arrow — data: {x, y, rotation?} add_equipment_tag — data: {x, y, tag, description?} add_line_number — data: {x, y, line_num, spec} insert_valve — data: {x, y, valve_type, rotation?, attributes?} insert_instrument — data: {x, y, instrument_type, rotation?, tag_id?, range_value?} insert_pump — data: {x, y, pump_type, rotation?, attributes?} insert_tank — data: {x, y, tank_type, scale?, attributes?}

Inputs: operation (required), data, include_screenshot. Returns: result

systemB
Read-only

Server status and management.

Operations: status — Backend info, capabilities, health check. health — Quick health check (ping backend). get_backend — Return current backend name and capabilities. runtime — Return process/runtime details for spawn diagnostics. init — Re-initialize the backend. execute_lisp — Execute arbitrary AutoLISP code (File IPC only). data: {code}

Inputs: operation (required), data, include_screenshot. Returns: result

viewA
Read-only

Viewport control and screenshot capture.

Operations: zoom_extents — Zoom to show all entities. zoom_window — Zoom to window: x1, y1, x2, y2 get_screenshot — Capture current view as PNG image.

Inputs: operation (required), x1, x2, y1, +1 more. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 8 tools

    Disambiguation4/5

    Each top-level group targets a distinct domain (drawing, view, entity, layer, block, annotation, pid, system), so selection is mostly clear. Minor overlap exists where entity.create_mtext and annotation.create_text both create text, and pid's specialized insert_valve/instrument/pump/tank parallel generic entity creation, but descriptions keep the boundaries workable.

    Naming Consistency4/5

    Namespaces and operations use a consistent snake_case verb_noun pattern (create_line, set_current, insert_symbol, add_flow_arrow). A few bare verbs (list, count, get, copy, move, erase) deviate slightly but remain conventional and readable within their groups.

    Tool Count4/5

    Eight well-grouped top-level tools is a sensible scope for a large CAD domain, avoiding a flat blizzard of 60+ operations. The grouping is heavy (each group bundles many sub-operations), but that is a reasonable encapsulation rather than a mismatch.

    Completeness5/5

    The surface covers the full CAD lifecycle: file create/open/save/export/plot, entity CRUD with transforms and boolean-style ops, layer and block management with attributes, annotation, and a dedicated P&ID workflow. Undo/redo and system diagnostics round it out with no obvious dead ends.

    Maintenance

    ActivityStale
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables users to control CAD software like AutoCAD, GstarCAD, and ZWCAD through natural language instructions via the Model Context Protocol. It supports automated drawing of shapes, layer management, and saving designs to DWG files without manual interface interaction.
      2
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to control AutoCAD, ZWCAD, GstarCAD, and BricsCAD through the Model Context Protocol, supporting drawing, layer/entity/block management, data export, file operations, and natural-language CAD task automation.
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables users to control supported CAD applications through AI assistants using the Model Context Protocol, supporting drawing, layers, entities, blocks, files, exports, and natural-language automation.
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to control supported CAD applications through the Model Context Protocol, allowing drawing, layer/entity/block management, data export, and file/session operations via natural-language or direct tool calls.
      -