Skip to content
←Back to Open Source

OPEN SOURCE DEEP DIVE

FreeCADCADMCP3D Modeling

FreeCAD MCP: A CAD and FEM Control Plane for Agents

An MIT-licensed bridge connecting FreeCAD to MCP clients for model editing, screenshots, isolated code execution, and CalculiX FEM analysis.

neka-nat/freecad-mcp3.4kPythonMIT13 min read

A practical CAD control plane for agents

FreeCAD MCP is an MIT-licensed bridge that gives an AI client a usable control surface for FreeCAD. It is not a new CAD kernel, a hosted design service, or an autonomous engineer. Its value is narrower and more useful: an external Model Context Protocol server translates tool calls into operations performed by a FreeCAD addon, while the FreeCAD document remains the source of truth. The reviewed release is v0.1.32, published on 16 November 2026, and the external server requires Python 3.12 or later.

The project is most relevant to teams exploring agent-assisted mechanical design, parametric geometry, robotics hardware iteration, and simulation preparation. A conversational client can create a document, inspect its object graph, add or edit geometry, take a controlled screenshot, run Python for operations that do not have a structured tool, and invoke a CalculiX analysis. Each action is visible in the ordinary FreeCAD application rather than in a separate model silo.

Two processes, three responsibilities

The architecture deliberately separates the user interface from the protocol process. A FreeCAD addon runs inside the desktop application and exposes an XML-RPC endpoint, by default at 127.0.0.1:9875. The external freecad-mcp server is launched by Claude Desktop, an IDE, or another MCP client. It owns the MCP transport and forwards structured requests to the addon. The client owns the model's reasoning and tool-selection loop, while FreeCAD owns documents, geometry, and the graphical state.

ComponentResponsibilityDefault boundary
FreeCAD addonRuns CAD and graphical operations, manages the document transaction where supported, executes applications, and exposes status.XML-RPC on loopback port 9875.
MCP serverRegisters tools, validates inputs, converts calls to RPC, handles transport timeouts, and returns text or screenshots.Standard input and output, or HTTP on loopback port 8000.
MCP clientInterprets the user's goal, chooses tools, and decides what to do when an operation is uncertain.Client-specific process and conversation loop.

This split matters when the components run on different machines. The --host option selects the machine running the FreeCAD graphical application. Headless execution is different: freecadcmd runs on the machine hosting the MCP server. Anyone deploying the system must keep those two execution locations straight, especially when scripts write or reload files.

A tool surface built around design work

The tool set follows the shape of ordinary FreeCAD work rather than exposing every internal API. Document tools create, list, and reload files. Object tools create, edit, delete, list, and retrieve objects. Visualization returns an image of the active view, with selectable orientations and optional dimensions. A parts-library interface can list and insert reusable components. Status tools report RPC health, background jobs, and queued graphical tasks.

For operations outside that structured list, execute_code provides an escape hatch into FreeCAD's Python environment. That is useful for Draft objects, custom property trees, imports, exports, and compound modelling sequences. The project also adds dedicated factories for a few Python-defined types, including tubes, circles, rectangles, polygons, and wires, so common construction steps do not always require unrestricted code.

The distinction is practical, not a security boundary. A structured tool reduces ambiguity and gives the client a clean schema, but it still changes a real CAD document. Arbitrary code has the full privileges of the FreeCAD process. Neither path should be treated as a sandbox.

Three execution modes with different failure boundaries

The strongest engineering decision in the repository is that it does not pretend every script belongs on the same thread. FreeCAD's graphical and document APIs are not generally safe from arbitrary worker threads, while some OpenCascade operations are slow enough or unstable enough that running them in the main application is risky. The project exposes three distinct modes.

ModeBest useBoundary and tradeoff
execute_codeNormal document and view automation.Runs on the graphical thread. Safe access, but queued work can block the interface.
execute_code_asyncLong calculation over independent shapes.Runs in the background, but document and view writes must return to the graphical thread through commit().
execute_code_headlessHeavy lofts, sweeps, booleans, or operations that may crash native geometry code.Starts a separate freecadcmd process. A native crash kills the helper, not the open application, but the script must open and save documents itself.

The asynchronous contract is unusually explicit. A worker can build independent OpenCascade shapes, then call commit(fn, timeout=120) to apply the result and recompute the document on the graphical thread. Direct off-thread document access is not endorsed because it can wedge FreeCAD. The helper is persisted in the shared script namespace, so later jobs can reuse functions that call it.

Headless execution is designed for crash isolation. The helper process receives closed standard input, prints progress with line buffering, and is terminated as a process group on POSIX systems or a process tree on Windows when its timeout expires. Ordinary child processes therefore cannot keep writing indefinitely after the main helper is stopped. This is still not a transaction: files completed before a timeout are not rolled back, and a deliberately detached child or external service falls outside the cleanup guarantee.

A shared namespace that behaves like a session

execute_code and execute_code_async share a persistent Python namespace, with FreeCAD and App available alongside FreeCADGui and Gui. Variables survive between calls and even across a stop and restart of the RPC listener. They do not survive restarting the FreeCAD process. The server protects its own internals from accidental name replacement and removes the GUI dispatch helper from the script-visible namespace where necessary.

Only one shared-namespace script is admitted at a time. If another synchronous or asynchronous script is already running, the new request returns SCRIPT_BUSY with mutation_outcome: not_started. That response means the request did not enter execution, so retrying is materially different from retrying an operation whose outcome is unknown. Document tools, status queries, and an asynchronous commit() can still be serviced while the script namespace is occupied.

The namespace is not a database transaction. If a script changes a property and then raises an exception, earlier assignments and document changes remain. The documentation states this directly rather than implying rollback that does not exist. That honesty is important for an agent: it should inspect the document after a failure instead of repeating a mutation from a false assumption that nothing happened.

Timeouts that preserve uncertainty

A graphics-thread operation cannot always be cancelled safely. FreeCAD MCP therefore separates queue time from execution time. A call may wait for another task without consuming its own run budget. Once execution starts, the run budget takes effect. The default budget for execute_code is 90 seconds, and callers may request a positive finite value up to 1,800 seconds. FEM uses an explicit integer timeout with a 600-second default.

The client's socket timeout is widened to cover queueing, execution, and a 30-second margin. The configured client timeout can still be larger, and other MCP hosts must allow these response times in their own settings. The external server refreshes compatibility and budget information at tool admission so a cached connection does not permanently retain an old listener's limits.

When an operation starts but the caller reaches its own deadline, the response can say mutation_outcome: still_running and include a task identifier. The work continues on the graphical thread. The safe next action is to poll get_task_status, not to submit the same mutation again. The bridge retains pending tasks and the last 20 completed tasks, with bounded JSON-safe result snapshots. Unknown or evicted identifiers return an error instead of an assumed success.

The outcome vocabulary is one of the project's best features because it encodes operational reality:

  • not_started: admission was rejected or queued work was cancelled.
  • still_running: the caller timed out after execution began, and the task remains pollable.
  • rolled_back: the document transaction was aborted and creation cleanup completed.
  • retained_invalid: an invalid object was intentionally kept for inspection.
  • cleanup_incomplete: rollback or cleanup failed, so remaining objects must be checked.
  • partial_or_unknown: execution failed after state may have changed.
  • completed: execution finished, without claiming that arbitrary geometry is valid.

The transport also avoids a dangerous convenience. Python's XML-RPC transport normally retries a request after some lost connections. This project disables replay because a modifying request may have committed before its response disappeared. A lost response becomes an explicit instruction to inspect the document, not an automatic duplicate operation. The tradeoff is more manual recovery, but it is the right default for CAD edits.

Failure handling reaches the graphical scheduler

Graphical calls are placed in a first-in, first-out queue and awakened through a Qt signal, with a heartbeat as fallback. The scheduler avoids running while a mouse button is held, a popup is open, or a modal dialog is active. The mouse guard is capped at five seconds so stale Qt state cannot block the bridge forever. Each task has an isolated response queue, so a timed-out caller cannot consume a later task's result.

Once a running task exceeds its deadline, dispatch becomes stuck and later graphical calls fail fast until the original native operation returns. Status remains available because the XML-RPC server handles connections concurrently and status does not require the graphical thread. Queued calls retain their own queue deadlines and may still run after a stuck predecessor returns. This design does not make unsafe cancellation safe, but it prevents a single stuck task from silently turning the whole bridge into an unbounded queue.

The task history, listener generation, server identifier, queue counts, heartbeat age, and blocked reason are exposed through status. A restart is refused while native work or the namespace owner is still running. Calls from a previous listener generation cannot enter the new queue. These details make recovery diagnosable rather than turning every timeout into an opaque restart.

Finite element analysis inside the same loop

run_fem_analysis operates on an existing Fem::FemAnalysis container. If no compatible CalculiX solver object exists, the addon creates one. It runs the solver in an isolated working directory, reuses the configured solver when present, and imports each run's results once. The summary returns maximum von Mises stress, minimum and maximum displacement, node count, solver and result object names, applied loads, and the working directory.

The load report covers forces, pressures, and fixed constraints. A force includes its magnitude, referenced face, direction source, and whether the direction was reversed. Pressure is reported in megapascals. The addon reads these constraints after recomputation inside the same graphical operation as the solve, and it stops if a supported load cannot be interpreted.

One unit detail deserves special attention. When creating or editing a force through the MCP tools, use an explicit unit string such as "1000 N". Unitless forces supplied through ordinary FreeCAD Python use FreeCAD's native units, where a value of 1000 can represent one newton. The summary prints the load in newtons so the model does not have to infer the scale. This is exactly the sort of mismatch that can produce a plausible but wrong engineering conclusion.

The FEM boundary is also explicit. The tool assists an existing analysis; it is not a full simulation planner, material-verification system, or mesh-quality authority. It reports supported loads, not every possible FreeCAD load type. A successful solver return does not certify the engineering model.

Deployment security starts at the local boundary

The default configuration is intentionally local. The XML-RPC endpoint listens on loopback and the HTTP MCP transport listens on 127.0.0.1:8000. Streamable HTTP is the preferred long-lived transport, while Server-Sent Events remains available as a deprecated compatibility option.

Remote graphical connections require care. The addon supports an allowed-IP list, and it can require a bearer token. Its RPC traffic is not encrypted. The documentation recommends an SSH tunnel for networks that are not fully trusted and warns that --auth-token may be visible in a process list. Any client that reaches this endpoint may reach execute_code, so address filtering is not a substitute for host security.

The external HTTP transport has a separate safeguard. Binding to a non-loopback address is refused unless a bearer token is configured, unless the operator explicitly enables the insecure override. DNS-rebinding protection is always active and rejects host headers outside an allow-list. Browser-style requests to the addon are refused even when a token is set. These controls reduce accidental exposure, but they do not turn arbitrary CAD code into a multi-tenant security model.

Evidence of engineering maturity

This is not a thin demonstration wrapper. At the reviewed commit, the repository contains a substantial test suite covering GUI queue timing, stale mouse state, task-history bounds, listener restart, mutation outcomes, lost XML-RPC responses, asynchronous document commits, input validation, token handling, DNS rebinding, headless crash isolation, FEM result selection, force units, and parts-library path safety. Native tests exercise full HEADLESS sessions and repeated FEM solves when a FreeCAD command is available.

The suite's focus is revealing. It spends more effort on retries, partial state, thread affinity, and recovery than on adding a long list of flashy tools. Those are the issues that appear when an agent is allowed to alter a real design repeatedly. For a CAD bridge, deterministic failure semantics are core functionality.

Limitations and adoption guidance

The addon and external package are versioned and updated separately. The first connection compares protocol versions and reports a mismatch, but users still need to copy the addon directory and restart FreeCAD after addon updates. FreeCAD's bundled Python and the external server's Python environment are also separate. The external package needs Python 3.12 or newer, while the addon can run inside an older bundled interpreter.

Headless execution must be installed on the MCP server host. The published container image cannot provide headless FreeCAD because it does not include FreeCAD itself. File paths therefore belong to the server host, not necessarily the graphical host. After a headless script saves a document that is open in the GUI, the document must be reloaded to see the external changes.

Several operations have side effects beyond the obvious geometry change. A screenshot can alter camera framing and selection. Reload closes the old document before opening the file, so a failed reopen is not an automatic restoration. FEM failure can leave a new solver, a working directory, or modified results. An agent should inspect these states instead of treating any exception as a clean rollback.

The right first deployment is a trusted workstation or a narrow internal network, with loopback or an SSH tunnel, version-matched components, and a human reviewing consequential geometry and simulation outputs. It is well suited to iterative prototyping, parameter changes, repetitive construction, visual inspection, and simulation setup. It is not yet a substitute for revision control, engineering approval, mesh validation, or production change management.

Why it fits hardware and robotics teams

Robotics development creates many small mechanical variations: mounting plates, brackets, sensor housings, motor adapters, cable paths, and fixture geometry. An agent can help most when it can inspect the actual model and make bounded edits, then show the result. FreeCAD MCP provides that loop while keeping the model in an editable desktop application. The execution-mode split is especially relevant for geometry that may block or crash native CAD code.

The project's main contribution is therefore operational rather than cosmetic. It turns an MCP connection into a CAD session with a queue, explicit uncertainty, persistent script state, a separate crash boundary, and enough status information to recover without blindly repeating work. That makes it a credible foundation for deeper design-agent workflows, provided teams treat the underlying CAD and simulation results with ordinary engineering discipline.

As an Amazon Associate, we earn from qualifying purchases.