scripts/smoke_pid_com.py runs the whole track against the live AutoCAD in a new document. ComBackend.connect() is lazy by design, so the script reads reachability from system_status()["connected"] rather than from connect() as the plan sketched, and closes its document without saving unless --keep is passed. On this machine (AutoCAD 2026, "25.1s (LMS Tech)") it exits 0: 5 nodes, 4 edges, 0 dangling, confidence_min 1.0, 0 critique issues, 2 XDATA chunks — identical to the headless engine on the same spec. The first attempt exited 2 on a stale win32com gen_py cache (a package folder holding only __pycache__); an environment fault, no backend change needed. A/B against v1.5.1 published as ab-v1.5.1-vs-v1.6.0-dev.json: 26/29 -> 29/29, three miss -> pass, zero regressed. check_doc_numbers.py now names the report and the two row labels in one place (AB_REPORT, AB_*_LABEL), and README.md / benchmarks/README.md carry the new rows; the v1.5.0 and v1.4.0 tables stay as history. README: P&ID row, the showcase and catalogue images, the token table re-measured (161 / 44,930 by default, 152 / 41,420 with TOOL_PACKS=core, lean 50 / 14,007), every stale count reconciled (154 -> 166 registered, 149 -> 161 advertised, corpus 158/672 -> 162/731 by the same count, 19 -> 20 groups, 6 -> 8 resources, six-task matrix with pid_roundtrip), a "Known limitations of the P&ID track" subsection, and the snapshot line at this machine's 2423 collected tests (CI has not run on this tree; noted in the changelog with the pre-existing 1369 vs 1363 drift). CLAUDE.md: section 17, sections 5 and 7 counts, TOOL_PACKS, the two 1.6 contracts and the reader rules. Spec status -> implemented. The plan and spec markdown were reformatted by ruff (fenced Python only) because `ruff format --check .` was already red on them at HEAD and the gate requires the whole tree clean. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FKFStjEFzpGyLq5bMpWxTd
16 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
AutoCAD MCP Pro is a FastMCP 3.0 server that exposes ~166 tools, 8 resources, and 5 prompt templates for AutoCAD automation. (The exact tool count is reported dynamically by system_status / system_about — never hardcode it.) It runs with a dual-engine architecture: a live COM backend (Windows/AutoCAD required) and a headless ezdxf backend (works anywhere).
Running the Server
# STDIO mode (default, for MCP clients like Claude Desktop)
python server.py
# HTTP mode
fastmcp run server.py:mcp --transport http --port 8000
# Force a specific backend
AUTOCAD_MCP_BACKEND=ezdxf python server.py # headless file ops
AUTOCAD_MCP_BACKEND=com python server.py # live AutoCAD (Windows only)
AUTOCAD_MCP_BACKEND=auto python server.py # auto-detect (default)
Installation
# Core (ezdxf backend only)
pip install -e .
# With COM backend (Windows + AutoCAD)
pip install -e ".[com]"
# With PDF/screenshot support via matplotlib
pip install -e ".[pdf]"
# Everything
pip install -e ".[full]"
Running Tests
pytest
pytest tests/test_specific.py::test_name # single test
pytest -x # stop on first failure
Uses pytest-asyncio for async test support.
Architecture
Dual-Backend Pattern
The server uses a strategy pattern with an abstract base:
backends/contracts/— the interface, one module per domain (drawing.py,layouts.py,entity_creation.py, …). Split in v1.5.0 out of a single 1854-line ABC; some slices (premium, gdt, settings) also carry shared concrete implementations, so they are mixins rather than pure interfaces.backends/capability.py— the refusal vocabulary (UnsupportedCapabilityError) plus@capability(key, reason=...), which marks a contract method optional and gives it a default that raises that refusal. Use it only for genuine engine boundaries, never for an unfinished method;@abstractmethodstays the default. Every key used must be declared in both capability maps —tests/test_capability_contract.pyfails otherwise, which is what stops the decorator becoming a way to ship undeclared holes.backends/base.py— shared dataclasses (EntityInfo,LayerInfo,BlockInfo,DrawingInfo,CapabilityMap) and theAutoCADBackendcomposition of every contract. Import surface is unchanged:from backends.base import AutoCADBackend, UnsupportedCapabilityErrorstill works.backends/ezdxf_backend.py—EzdxfBackend: file-based DXF operations using theezdxflibrary. All sync ezdxf calls are wrapped withasyncio.to_threadvia_async(). Transactions are implemented as full DXF snapshots on an_undo_stack.backends/com_backend.py—ComBackend: live AutoCAD control viapywin32COM. All COM calls are routed through aThreadPoolExecutorwith a single thread to satisfy AutoCAD's STA (Single-Threaded Apartment) COM requirement.
Backend selection at startup (in server.py::_make_backend):
- Check
AUTOCAD_MCP_BACKENDenv var - On Windows with
auto/com: try COM first, fall back to ezdxf - On non-Windows: always use ezdxf
FastMCP Server Structure (server.py)
The mcp FastMCP instance is configured with:
- Lifespan (
autocad_lifespan): initializes the backend singleton; stores it inctx.lifespan_context["backend"] - Middleware stack:
ErrorHandlingMiddleware→AuditMiddleware(custom timing/audit log) →TimingMiddleware→LoggingMiddleware _backend(ctx)helper: retrieves the backend from lifespan context, raisesToolErrorif not ready
Tools are organized into sections (counts are indicative — system_about is authoritative):
- Drawing Management (12 tools):
drawing_*(includesdrawing_redo) - Entity Creation (14 tools):
entity_create_*(includesentity_create_table,leader_create_mleader) - Dimensions (5 tools):
dimension_* - Entity Modification (16 tools):
entity_move/copy/rotate/scale/mirror/offset/delete/array_*, corner ops (entity_trim/extend/fillet/chamfer), plus in-placeentity_edit_text(TEXT/MTEXT content/height/rotation) andentity_edit_geometry(CIRCLE/LINE/ARC — center/radius/endpoints/angles), both handle-preserving - Entity Query (9 tools):
entity_get,entity_list,entity_delete_many,selection_get,selection_window/polygon/filter, andentity_get_xdata/entity_set_xdata(typed by group code) - Layer Management (14 tools incl. 2 linetype_*):
layer_*,linetype_list,linetype_load - Block Operations (8 tools):
block_*— includesblock_define(a block from typed primitive specs + ATTDEFs, no source entities needed) - Analysis & Query (8 tools):
analysis_*— plus Batch (2), Templates (2), Validation (1) - View & Screenshot (4 tools — includes
view_zoom_and_screenshot):view_* - Transactions (3 tools):
transaction_begin/commit/rollback - System (8 tools):
system_status/get_variable/set_variable/run_command/run_lisp/about/capabilities, plusdrawing_settings(friendly units/scale/precision/osnap facade over system variables) - Engineering / Deterministic CAD (8 tools):
gear_draw_*,keyway_draw_*,titleblock_apply_iso_a3,drawing_finalize - Premium meta-tools (12):
drawing_preflight,drawing_plan,drawing_critique,drawing_refine,drawing_deliver,point_from_snap/intersection/tangent,construction_*,drawing_apply_iso_layers,dimension_auto,entity_select_smart - GD&T (ISO 1101 / ASME Y14.5):
gd_frame(feature control frames),datum_feature— enforced by thegdtcritique focus - Layouts & Paper Space (12 tools): tab lifecycle
layout_list/create/set_current/delete/rename/copy, viewportsviewport_create/list/set_scale/lock/delete, andentity_change_space(CHSPACE — taggedlayoutandmodify, andlayoutwins the group priority, so it files here).drawing_export_pdftakes an optionallayoutparam and does project model content through viewports on both engines (viewport_render— v1.4 declared this COM-only and was wrong; the headless renderer only omits the viewport borders).entity_change_spaceis the mirror case — ezdxf-only (chspace), because ActiveX exposes no change-space member and the COM route is unverified. - 3D Solids (5 tools, opt-in via
ENABLE_3D=true, COM only):solid_box/cylinder/extrude/revolve/boolean— hidden from discovery and rejected while disabled; ezdxf reportssolid_3das unsupported (no headless ACIS). - P&ID (9 tools, pack
pid):pid_symbol_list/insert(ISO 10628-2 + ISA-5.1 catalogue authored in code, real blocks with TAG attributes, named ports, ACADMCP_PID XDATA),pid_line_draw(port-to-port orthogonal routing, ISA-5.1 line classes → layer/linetype/marker blocks, line numbers),pid_tag_parse(ISA-5.1 grammar), the readerpid_graphand its deliverablespid_instrument_index/line_list/equipment_list, andpid_from_spec(whole sheet, one transaction). Sixpid_*critique focuses (pid_dangling_line,pid_duplicate_tag,pid_incompatible_connection,pid_untagged_instrument,pid_illegal_tag,pid_unconnected_equipment) run underfocus=Noneand insidedrawing_finalize; they return nothing on a drawing without P&ID nodes. Two resources (autocad://pid/symbols,autocad://standards/isa51) carry the catalogue and the ISA-5.1 letter tables. Both engines implement every P&ID contract; the COM paths were executed live once byscripts/smoke_pid_com.py(AutoCAD 2026).
Tool profiles: TOOL_PROFILE=lean|full (default full) controls the advertised surface — lean ≈ 50 curated drafting tools (47 with TOOL_PACKS=core; including cad_batch, since a client with a tight tool cap is exactly the client paying most per turn). Applied in the lifespan; reported by system_about. The core profile was removed in v1.5.0 (the discovery layer replaced it); TOOL_PROFILE=core falls back to full with a warning.
Tool packs: TOOL_PACKS=all|core,pid (default all) advertises only the vertical packs a client uses; core is always on and is everything no other pack claims; unknown names are ignored with a warning; a lean profile intersects with the enabled packs. system_about reports tool_packs.
Tool discovery: DISCOVERY_MODE=off|search (default off). search replaces the advertised catalog with search_tools + call_tool, ranking hits over an AutoCAD command / synonym corpus (discovery/aliases.py) layered on fastmcp's BM25 index.
ISO 129 tolerances: dimension_linear / dimension_radius / dimension_diameter take tol_upper / tol_lower / tol_mode (symmetric ± / deviation +a/-b / limit / basic) and text_override (e.g. ⌀20 H7). Prefer these over hand-drawn tolerance text.
ISO 286 fits: the same dimension tools take fit="H7" (mutually exclusive with tol_*) — deviations are resolved from authored ISO 286 tables (engineering/fits.py; shafts d/e/f/g/h/js/k/m/n/p, holes D/E/F/G/H/JS, sizes 1–500 mm) against the measured nominal and the fit code is appended to the dimension text.
Drawing score: drawing_finalize returns payload["score"] — a 0-100 scalar + invalidity_ratio + A-F grade over the validator + critique union. Use it as the objective quality metric.
Measuring: never read vertices back and shoelace them — that loses 28.2% of the area on a semicircular edge, silently. analysis_measure_entity(handle) reads the real geometry, and its payload states its own accuracy: exact, flatten_tolerance, assumed_closed, self_intersecting. A HATCH reports the area it fills (outer loops minus islands) plus hatch_style; on a curved hatch edge flatten_tolerance is not the accuracy knob, because ezdxf hands boundaries over as cubic Beziers whose ~0.028% circle error is already baked in. boundary_trace / boundary_from_entities report the same number analysis_measure_entity gives for the polyline they just drew — if those ever diverge, one of them is approximating and neither says so.
Benchmark matrix: benchmarks/tasks_v4.py is the current set (16 tasks; --matrix v3 / --matrix v2 reproduce the earlier sets). The published competitor reports are pinned v1.4 runs against v2 and are never back-filled for the five v3 tasks or the v4 pid_roundtrip — the chart shows them not run, not zero. benchmarks/correctness_suite.py (29 checks) is the release A/B gate: python benchmarks/compare_versions.py v1.5.1 (the published report is benchmarks/results/published/ab-v1.5.1-vs-v1.6.0-dev.json; scripts/check_doc_numbers.py names it in AB_REPORT).
Adding a New Tool
- Add the method to the matching module in
backends/contracts/—@abstractmethodif both engines must have it,@capability("key", reason=...)only if it is a real engine boundary (and then declarekeyin both capability maps, or the gate fails) - Implement it in
EzdxfBackend(backends/ezdxf_backend.py) using the_async(func)wrapper - Implement it in
ComBackend(backends/com_backend.py) usingself._com(func) - Register the tool in
server.pywith@mcp.tool(...)calling_backend(ctx).your_method(...) - Use
_dc(result)to convert dataclass returns to dicts
Key Conventions
- Entity handles: hex strings (e.g.
"1A2B"). Always returned from create/copy operations; required by all modify/query operations. - Coordinates: drawing units (mm by default); angles in degrees, counter-clockwise from X axis.
Every coordinate in or out of a tool is WCS on both engines. DXF stores
CIRCLE/ARC/LWPOLYLINE/TEXT/INSERT geometry in a per-entity frame (
extrusion);backends/ocs.pytranslates at the backend boundary, so OCS never reaches a tool. An entity in a plane tilted out of WCS XY reportsplane_normaland omits the fields xy cannot express; writing an xy into such an entity is refused withcapability: "ocs_tilted_plane"— useentity_moveinstead. - ACI colors: 1–255 for specific colors, 256=ByLayer, 0=ByBlock.
- COM backend only:
system_run_command,system_run_lisp, andview_zoom_extents/window(view ops are no-ops in ezdxf). - Screenshot: COM uses Win32 window capture (Pillow required); ezdxf renders via matplotlib.
_dc(obj): converts dataclasses to dicts recursively for JSON serialization.- Engineering layer scaffold:
drawing_newauto-bootstraps standard linetypes (CENTER, HIDDEN, PHANTOM) and engineering layers (GEOMETRY, DIM, CENTER, HIDDEN, PHANTOM, HATCH, TEXT, TITLEBLOCK). Passbootstrap=Falseto opt out. - Generic contracts added in 1.6:
block_define(name, entities, attdefs)(typed primitives + ATTDEFs, both engines;overwritereplaces contents so INSERTs keep the name) andentity_get/set_xdata(typed by group code; 255-char strings, 16 KB per entity, enforced before writing). - P&ID reader rules:
pid_graphnever modifies the drawing, reads geometry from the drawing (an INSERT's real rotation/scale) rather than the catalogue, and reportssource/confidenceper node (catalog 1.0, xdata 0.95, heuristic 0.6, inferred 0.3) — never raised by agreement between heuristics. Readstats.confidence_minbefore trusting a foreign drawing. TOOL_PACKS=all|core,pidadvertises only the packs a client uses;coreis always on;system_aboutreportstool_packs.- Production drawings: For real engineering output, use the
engineering/package primitives via thegear_*/keyway_*/titleblock_*MCP tools — do NOT hand-draw teeth/keyways/sections with rawentity_create_*calls. Always end withdrawing_finalizefor the 8-step validator.
Premium Drawing Rules
These rules are non-negotiable for production engineering output.
- Plan before draw: Call
drawing_plan(intent, scale, sheet)before anyentity_create_*. The returned PlanSpec is held by the backend and replayed bydrawing_critiqueat finalize time. - No coordinate guessing: Never compute snap points (endpoints, midpoints,
intersections, perpendicular feet) from memory. Use
point_from_snap(handle, "end"|"mid"|"center"|"quad"|"perp"|"near", ref_x, ref_y). - Layer discipline: All geometry on engineering layers (GEOMETRY, HIDDEN,
CENTER, ...). Construction geometry on
CONSTRUCTIONlayer (color 250, lightest weight); wipe withconstruction_clear()before finalize. - Lineweights are ISO 128: 0.13/0.18/0.25/0.35/0.50/0.70/1.00/1.40/2.00 mm
only. Use
drawing_apply_iso_layers("mech"|"pid"|"iso13567")to bootstrap correct lineweights per layer; never set lineweight manually outside this set. - Corners must be explicit: Two intersecting lines that should meet at a
sharp corner must use
entity_trim(withkeep_x/keep_y) — leaving overshoot is reported asuntrimmed_cornerbydrawing_critique. Rounded/beveled corners useentity_fillet/entity_chamfer. - Dimensions via auto: Prefer
dimension_auto(handles, "chain"|"baseline"| "ordinate")over individualdimension_linearcalls. Manual dimensions only for special cases (leader notes, ordinate origins). - Critique-then-finalize:
drawing_critique(focus=[...])must return zero issues beforedrawing_finalize. Available focuses (closed enum):iso128,layer_color,dim_overlap,untrimmed_corner,duplicate_entities,construction_left. Passfocus=Nonefor all. - Meta-tools over raw: When a meta-tool exists for a workflow, use it; do not reimplement with low-level primitives. Same rule as the engineering- primitives line above.
Standard Premium Workflow (template)
1. plan = drawing_plan(intent, sheet_size="A3", scale=1.0)
2. drawing_apply_iso_layers("mech") # or "pid", "iso13567"
3. construction_xline(...) # scaffolding (optional)
4. entity_create_line / circle / ... # main geometry on engineering layers
5. entity_trim / fillet / chamfer # close corners explicitly
6. handles = entity_select_smart({...}) # avoid handle-memorization
7. dimension_auto(handles, style="chain") # ISO 129 dims
8. issues = drawing_critique(focus=None) # must be []
9. construction_clear() # wipe scaffolding
10. drawing_finalize(save_path=..., screenshot_path=...)