FreeCAD MCP
This server automates FreeCAD modeling, scripting, FEM, and verifiable assembly work.
Create, list, reload, and inspect FreeCAD documents, including save/recompute status.
Create, edit, and delete objects, including Part/PartDesign and supported Draft/FEM types.
Run Python synchronously, as background jobs, or in headless
freecadcmd; poll async jobs.Capture screenshots, focused multi-view images, and insert parts from the parts library.
Run CalculiX FEM analyses and return stress/displacement summaries.
Inspect world-space geometry and define mounting faces plus ordered hole interfaces.
Plan and preview alignments without modifying the document.
Apply alignments transactionally with rollback and independently verify hole errors, axes, gap, and scoped collisions.
Submit, poll, and cancel long native assembly jobs with request-id idempotency.
Create native assemblies and persistent Fixed Joints with solver and numeric checks.
Query assembly capabilities and RPC/addon health.
Provides tools for interacting with FreeCAD to inspect parts, define mounting interfaces, plan and preview alignments, apply positioning and recompute geometry, verify assembly results, create native assemblies with fixed joints, and capture inspection images. Supports queued CAD operations, job tracking, cancellation, and document status checks.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@FreeCAD MCP align the mounting bracket to the base plate and verify the assembly"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
FreeCAD MCP: сборка с проверкой результата
Fork neka-nat/freecad-mcp (MIT) для агентов, которые собирают реальные механические узлы.
Upstream позволяет агенту сделать что-то в FreeCAD. Этот fork позволяет агенту доказать, что деталь встала правильно: числами, а не фразой «скрипт выполнен».

В чём разница
Возьмём типичную задачу: прикрутить кронштейн к основанию по двум отверстиям.
В upstream агент сам пишет Python: ищет грани, переводит координаты в мировые, считает Placement, применяет его. Затем получает «скрипт выполнен» и один скриншот. Если отверстия не совпали на 0,3 мм, это видно только на глаз.
execute_code(<свой скрипт: найти грани → посчитать Placement → применить>)
→ "Script executed successfully"
get_view() → одна картинка с одного ракурсаВ этом fork то же самое — это готовые операции с измерениями и откатом:
define_interface(основание) define_interface(кронштейн) # какая грань, какие отверстия
plan_alignment(...) # план без изменения документа
preview_alignment(plan_id) # голубая деталь в предлагаемом положении, 3 ракурса
apply_alignment(plan_id) # перемещение в транзакции; при нарушении допуска — откат
check_assembly(plan_id) # независимая повторная проверка
inspect_region(...) # изометрия + сверху + справа одним ответомРезультат — измерения, а не «успех»:
passed: true
max_hole_error_mm: 6.2e-14 hole_axis_angles_deg: [0.0, 0.0]
gap_mm: 3.6e-14 opposing_faces_error_deg: 0.0
collisions: [{part: "Base", overlap_mm3: 0.0}]
collision_scope: ["Base"] whole_assembly_checked: falseЭто вывод реального запуска (FreeCAD 1.1.4, аддон 0.2.1): два бруска 40×24×6 мм с двумя отверстиями, кронштейн изначально смещён и повёрнут. Значения порядка 1e-14 мм — шум вычислений с плавающей точкой, то есть отверстия совпали точно. Анимация выше снята на этой же сцене.
Сравнение
Сравнение относится к взятой за основу версии upstream 0.1.28 (коммит 8babe992); с тех пор в upstream новых коммитов нет. Возможность написать собственный Python-код сохранена, отличие fork — готовые операции с общими правилами проверки и ошибок.
Задача | upstream | этот fork |
Количество инструментов | 17 | 32: те же 17 + 14 инструментов сборки/статуса и конвертация STL в BREP |
Найти геометрию крепления | Объекты, свойства и скрипты агента |
|
Подготовить перемещение | Агент рассчитывает и задаёт Placement |
|
Подтвердить результат | Успех скрипта и то, что агент отдельно запросил | Ошибки отверстий, углы осей, зазор и объёмы пересечения с указанными деталями |
Неудачное совмещение | Транзакцию и откат нужно писать в скрипте |
|
Увидеть сборку |
|
|
Долгая операция и таймаут |
| Задания: |
Не устарел ли план | Агент проверяет сам | Отпечатки геометрии, счётчик изменений, идентичность документа: устаревший план отклоняется |
Закрепить связь деталей | Assembly API вручную через Python |
|
Что не сохранено |
|
|
Что не изменилось
Все 17 исходных инструментов, аддон, headless-исполнение, FEM, история коммитов и авторство upstream сохранены. Fork — надмножество: всё, что умел upstream, работает как раньше. Новые операции требуют нашего аддона 0.2.1; со старым аддоном возможен лишь ограниченный режим (см. Быстрый запуск). Документация upstream: UPSTREAM_README.
Что изменено в аддоне
Аддон работает внутри FreeCAD и выполняет то, что просит MCP-сервер. Новые инструменты сборки возможны только благодаря ему: без аддона 0.2.1 они недоступны.
Часть аддона | upstream 0.1.28 | этот fork |
Прежний RPC-код | Управление документами, объектами, скриптами, скриншотами | Почти не тронут (+45 строк): добавлены вызовы нового API и статус документов |
| Нет | Геометрия сборки: поиск граней и отверстий, расчёт перемещения, замеры, откат при нарушении допуска, предпросмотр, Fixed Joint |
| Нет | Очередь долгих операций: защита от повторного запуска по |
| Нет | Счётчик изменений документа: план отклоняется, если модель изменилась после его построения |
| Нет | Статус сохранения: GUI-флаг изменений, наличие файла, пересчёт |
Установка | Копирование папки вручную |
|
Раньше такую логику агент писал скриптом в каждом диалоге и мог ошибиться. Теперь это готовый код внутри FreeCAD, который покрыт тестами и live smoke. Для рисования деталей, FEM и обычных скриптов поведение аддона не изменилось. Проверки выполнены на наших тестах и сценариях, а не на произвольных CAD-моделях.
Когда достаточно upstream
Если вы рисуете детали, редактируете объекты, гоняете FEM или генерируете модели скриптами, а не совмещаете готовые детали по крепёжным отверстиям, новые инструменты вам не нужны: upstream проще и ставится быстрее. Fork нужен, когда важно проверяемо состыковать детали и знать, что именно проверено.
Related MCP server: SolidWorks MCP
Зачем появился fork
Задача проекта — помогать агенту собирать реальные механические узлы для подставки androsaur-stand: совмещать крепёжные отверстия основания и кронштейна с заданным зазором. Upstream дал рабочую основу: управление FreeCAD, создание и редактирование объектов, скрипты, скриншоты, фоновые задания, headless и FEM. В нашей работе проявились три ограничения.
Успех скрипта не равен правильной сборке. Агент сам писал код поиска граней, перевода координат и проверки; Python выполнялся, а детали оставались смещены. После правок снова требовались замеры и итерации.
Один скриншот не подтверждает соосность. По общей изометрии трудно увидеть совпадение отверстий, контакт плоскостей или малый зазор.
Неясно, что после таймаута. Можно ли повторить перемещение, актуален ли план, какие документы не сохранены — отдельные скрипты в каждом диалоге.
Цикл «план → предпросмотр → применение с откатом → измерение → несколько ракурсов» делает условия успеха явными и даёт агенту данные для следующего решения. Он призван сократить число исправлений на глаз; отдельного сравнительного измерения скорости или числа итераций мы пока не проводили.
Что подтверждено и где остаются ограничения
Версия 0.2.1: 286 тестов проходят (проверено запуском uv run pytest), на MCP SDK
1.x и 2.x; CI также проверяет Python 3.12 и 3.13. Live smoke в FreeCAD проверяет
вложенные Placement, PartDesign Body, откат при коллизии и отмене, предпросмотр, а также
Fixed Joint после смещения и после сохранения и повторного открытия FCStd. Это
проверенные сценарии, а не гарантия для произвольной CAD-модели.
Что остаётся за агентом и за границами проверки:
правильно выбрать контактные грани и порядок отверстий (симметрия не угадывается);
коллизии проверяются только с фиксированной деталью и явно указанными
obstacles; в ответе всегдаwhole_assembly_checked: false;нет поддержки
App::Link, перемещения контейнеровApp::Partи редактирования произвольных сетей Assembly-связей.
Полные условия: «Границы проверки».
Автоматическая сшивка STL в BREP
convert_mesh_to_brep превращает STL-файл или объект сетки в отдельное твёрдое
BREP-тело и автоматически восстанавливает настоящие плоскости, цилиндры и
поддержанные частичные дуги. Это изменение геометрии, не визуальное сглаживание;
размеры определяются из STL без исходников OpenSCAD и ручного выбора граней.
Например, платформа наклона из 2884 треугольников восстановлена в 31 грань: 21 плоскость и 10 цилиндрических поверхностей. Все шесть STL контрольного набора проверены одним инструментом, включая сохранение и повторное открытие.
Исходник сохраняется, результат проверяется по валидности, объёму, габаритам и остаточной гранёности. Опциональный ремонт ограничен численным допуском. Параметрическая история не восстанавливается; неподдержанные поверхности могут остаться гранёными. Файл автоматически не сохраняется.
Подробное руководство: STL → BREP — запуск, этапы восстановления, результаты шести деталей, отчёт, проверки и ограничения. Параметры MCP-инструмента.
Быстрый запуск
Требуются Python 3.12+, uv и открытый FreeCAD с запущенным MCP RPC на порту 9875.
uv sync
uv run freecad-mcp --host 127.0.0.1Нужен наш аддон 0.2.1, а не только старый upstream-аддон. Сборочные операции
исполняются через отдельный нативный RPC API; Python-код для них не передаётся.
CAD-ядро имеет один исходник addon/FreeCADMCP/freecad_mcp_core/ и также включено
в MCP wheel. get_assembly_capabilities проверяет независимый assembly-протокол.
Установка с резервной копией предыдущего аддона:
uv run python scripts/install_addon.py --target /absolute/FreeCAD/user/Mod/FreeCADMCPОбычная установка требует перезапуска FreeCAD. Если старый RPC уже работает,
добавьте --activate: установщик проверит отсутствие открытых транзакций и
фоновых работ, заменит обработчики в существующем сервере и проверит протокол.
Документы не закрываются. GUI-диспетчер и очередь сохраняются; обновление самого
диспетчера требует обычного перезапуска. Старый аддон сохраняется вне Mod/.
Для временной совместимости со старым аддоном есть явный --allow-legacy-addon;
в этом режиме доступны операции, доставляемые через execute_code, а нативные
jobs и их гарантии отсутствуют. По умолчанию автоматического fallback нет.
Для новой установки аддона см. исходную инструкцию.
При включённой аутентификации задайте FREECAD_MCP_TOKEN в окружении MCP.
Таймауты
Для долгих операций задайте в MCP-клиенте таймаут вызова не меньше 240 секунд. При
сетевом таймауте состояние операции неизвестно: дождитесь освобождения GUI и проверьте
check_assembly, прежде чем снова перемещать деталь. Таймаут RPC не останавливает
выполняющуюся CAD-операцию.
Какие документы не сохранены
get_document_status() возвращает все открытые документы; doc_name выбирает
один по внутреннему имени. list_documents(include_status=true) даёт тот же
снимок; прежний вызов без аргументов сохраняет список имён.
modified— флагGui.Document.Modified, соответствующий состоянию интерфейса.saved_once— сохранялся ли документ раньше (App.Document.isSaved()).needs_recompute— нужен ли пересчёт (isTouched()), отдельно от сохранения.file_path,file_exists— связанный файл и его наличие на диске.needs_save— true для нового, изменённого документа или отсутствующего файла; null, если состояние Modified не удалось получить для ранее сохранённого файла.
Отсутствие GUI-состояния никогда не трактуется как «сохранён». Новый пустой документ может иметь modified=false, но needs_save=true. App.save()/saveAs() может оставить GUI Modified=true; инструмент честно сообщает флаг интерфейса. GUI-сохранение сбрасывает его. Чтение статуса не сохраняет и не пересчитывает документ. Проверяйте статус перед закрытием или reload документа.
Задания и отмена
Все нативные операции ставятся в GUI-очередь как задания. Обычный инструмент
ждёт до 20 секунд, затем возвращает job_id для get_assembly_job, вместо
продолжения ожидания до таймаута клиента. Задание живёт в аддоне, независимо от
MCP-процесса. Перезапуск FreeCAD или активация нового аддона сбрасывает историю. Для важных долгих операций используйте явный протокол:
start_assembly_operation("apply_alignment", {"plan_id": "..."}, request_id="mount-story-42")
get_assembly_job(job_id)
cancel_assembly_job(job_id)Повтор того же request_id и аргументов возвращает тот же job; другие аргументы
отклоняются. Гарантия действует в пределах истории: 32 завершённых задания + все
активные, не более 8 ожидающих/выполняемых. Не повторяйте запрос после истечения
истории без проверки текущей геометрии. outcome_unknown означает, что GUI
превысил бюджет диспетчера: продолжайте опрашивать исходный job.
Отмена ожидающего job исключает выполнение; отмена уже работающего проверяется между безопасными этапами. Для применения это вызывает откат транзакции. Сам вызов OCCT не прерывается. После начала commit отмена отклоняется. accepted=true означает принятую просьбу — дождитесь конечного состояния job.
Рабочий цикл
inspect_part(doc_name, part)— валидность, габариты, плоские грани, цилиндры, оси и радиусы в мировых координатах, в миллиметрах. Большие детали выдаются страницами по 100 граней каждого типа; следуйте полям next_*_offset.define_interface(doc_name, part, plane_face, hole_faces)— явный интерфейс: контактная плоскость и не менее двух отверстий в заданном порядке.plan_alignment(fixed_interface, moving_interface, obstacles=[...])— план без изменения документа. Порядок отверстий определяет соответствие; симметрию и назначение крепления агент должен разрешить явно.preview_alignment(plan_id)— три PNG с голубой полупрозрачной деталью в предлагаемом положении и осями креплений; документ не меняется.apply_alignment(plan_id)— транзакция, перемещение, recompute, измерения. Ошибка или нарушение допуска вызывает откат. Файл не сохраняется.check_assembly(plan_id)— повторная независимая проверка текущего положения: ошибки отверстий, углы осей, зазор и объёмы пересечений.inspect_region(doc_name, parts=[...])— PNG изометрии, сверху и справа одним ответом с отпечатками геометрии. Камера и видимость восстанавливаются.
Например, две пластинки с двумя отверстиями:
fixed = define_interface("Fixture", "Base", "Face6", ["Face7", "Face8"])
moving = define_interface("Fixture", "Bracket", "Face5", ["Face7", "Face8"])
plan = plan_alignment(fixed.interface_id, moving.interface_id,
gap_mm=0, tolerance_mm=0.01, obstacles=["Motor"])
apply_alignment(plan.plan_id)
check_assembly(plan.plan_id)
inspect_region("Fixture", ["Base", "Bracket", "Motor"])Имена граней в примере условные: их нужно получить через inspect_part.
Противоположные нормали плоскостей задают соприкосновение, положительный зазор
откладывается наружу фиксированной детали. Радиусы могут различаться для
зазорного крепления: совместимость крепежа по диаметрам остаётся отдельной задачей.

Границы проверки
apply_alignmentпозиционирует через Placement. Для постоянной связи естьcreate_assemblyиcreate_fixed_joint: стандартный FreeCAD Fixed Joint + Grounded Joint, штатный solver, транзакция и проверка геометрии после решения. Обе детали должны быть прямыми членами пустой нативной Assembly без других joints.create_assemblyпринимает только корневые детали, сохраняя их положения. После перемещения в Assembly нужно заново определить интерфейсы и план. Коннекторы Fixed Joint сохраняют относительное положение и отвязаны от топологии: изменение геометрии не переопределяет крепление автоматически. Редактирование произвольных существующих сетей constraints пока не поддерживается. apply_alignment отказывается перемещать детали в Assembly с существующими joints, чтобы не нарушать их Placement-изменением.Для проверяемых изменений нужен включённый FreeCAD Undo. Сохранение файла остаётся явным действием; Fixed Joint сохраняется и решается после reopen.
Проверены
Part::Feature, детали во вложенномApp::Partи произвольные повороты. Для PartDesign выбирайте сам Body какpart(проверено live smoke). Применение кApp::Linkи перемещение контейнераApp::Partпока запрещены.Поддерживаются полные цилиндрические внутренние стенки, открывающиеся на выбранную плоскость перпендикулярно ей. Частичные цилиндры, пазы и составные стенки требуют отдельного расширения. Кандидат цилиндра не равен доказанному сквозному отверстию.
Коллизии проверяются только между перемещаемой геометрией, фиксированной деталью и явно перечисленными
obstacles. Ответ всегда содержит область проверки иwhole_assembly_checked: false.Интерфейсы привязаны к отпечатку геометрии и положения. После изменений нужно определить их заново. Аддон наблюдает изменения документа; план устаревает при структурных изменениях, а close/reopen всегда меняет идентичность документа. Видимость и служебный _GroupTouched не считаются изменением геометрии. Идентификаторы живут в FreeCAD: истекают при перезапуске, обновлении runtime или вытеснении из кэша (256 записей каждого типа).
Успешный скрипт и красивый скриншот не доказывают правильность сборки. Агент должен сообщить численный результат и область проверки.
Проверка разработки
uv run pytest -q
uv run python -m compileall -q src addon
uv build
# Отдельный live smoke с открытым FreeCAD / RPC:
uv run python scripts/smoke_mounting.py --native
uv run python scripts/smoke_mounting.py --native --body --assemblyLive smoke создаёт и закрывает только одноразовый документ: два крепления, поворот детали, вложенное размещение, препятствие для проверки отката, контроль повторного применения и устаревших интерфейсов, три PNG. Нативный режим проверяет откат после отмены, ghost preview, а --assembly также штатное решение Fixed Joint после смещения и после сохранения/повторного открытия FCStd. Рабочие детали не меняет.
Available Tools
31 toolsapply_alignmentA
Apply a fresh plan in one FreeCAD transaction. Refuse reused/stale plans.
Recompute and measure actual hole errors, axes, mating gap and scoped intersections.
Roll back placement if any check fails. Does not save files. Moves Part::Feature or
PartDesign Body; App::Link and App::Part container application are unsupported.
Inputs: plan_id (required).
cancel_assembly_jobA
Cancel queued jobs or request safe-point cancellation with rollback for running mutations.
Running OCCT calls cannot be interrupted. accepted=true is a request, not proof
of cancellation: poll for terminal state. Once committing begins cancellation is refused.
Inputs: job_id (required).
check_assemblyA
Measure current geometry against a plan, without moving it; reports passed=false on failure.
This checks only declared interface geometry and collision scope, not every assembly component, topology intent, mechanical strength, or persistent assembly constraints.
Inputs: plan_id (required).
create_assemblyB
Create a native FreeCAD Assembly containing specified ROOT parts, preserving world poses.
Changes document organization in one transaction. Refuses parts already inside containers. Creates the native joint group. Does not save files.
Inputs: parts (required), doc_name (required), name.
create_documentB
Create a new document in FreeCAD.
Args:
name: The name of the document to create.
Returns:
A message indicating the success or failure of the document creation.
Examples:
If you want to create a document named "MyDocument", you can use the following data.
```json
{
"name": "MyDocument"
}
```
Inputs: name (required).
create_fixed_jointA
Persist verified mounting pose as a native Fixed Joint, grounding the fixed part.
Requires an applied, still-valid plan and both owners directly inside an existing native Assembly with no prior joints. Runs solver then numeric/collision checks; rolls back if they fail. Native joint survives saving/reopening; connectors preserve relative pose, detached from face topology. This is not a general constraint-network editor.
Inputs: plan_id (required), assembly_name (required), joint_name.
create_objectA
Create a new object in FreeCAD.
``obj_type`` must name a type registered in FreeCAD's C++ type system, such
as "Part::", "PartDesign::" or "Fem::" types. A number of FreeCAD features
are implemented in Python rather than C++ and so are not registered types;
of those, these are supported here through dedicated factories, and each
requires the properties listed beside it:
Part::Tube InnerRadius, OuterRadius, Height
Draft::Circle Radius
Draft::Rectangle Length, Height
Draft::Polygon FacesNumber, Radius
Draft::Wire Points (list of {x, y, z}), optional Closed
Any other Python-implemented type (Draft::Point, Draft::Ellipse, ...) must
be built with ``execute_code`` instead.
Note that the Draft factories name objects themselves, so for those the
returned object_name will differ from the requested obj_name, which is
applied to the object's Label instead. Always use the returned name in
later get_object/edit_object calls.
Args:
doc_name: The name of the document to create the object in.
obj_type: The type of the object to create (e.g. 'Part::Box', 'Part::Cylinder', 'Part::Cut', 'PartDesign::Body', etc.).
obj_name: The name of the object to create.
obj_properties: The properties of the object to create.
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when visual feedback is not needed,
e.g. for intermediate steps in a longer sequence of changes.
view_name: The view orientation of the returned screenshot (default "Isometric").
Pick the view that best shows the change being made.
Returns:
A message indicating the success or failure of the object creation and a screenshot of the object.
Examples:
If you want to create a cylinder with a height of 30 and a radius of 10, you can use the following data.
```json
{
"doc_name": "MyCylinder",
"obj_name": "Cylinder",
"obj_type": "Part::Cylinder",
"obj_properties": {
"Height": 30,
"Radius": 10,
"Placement": {
"Base": {
"x": 10,
"y": 10,
"z": 0
},
"Rotation": {
"Axis": {
"x": 0,
"y": 0,
"z": 1
},
"Angle": 45
}
},
"ViewObject": {
"ShapeColor": [0.5, 0.5, 0.5, 1.0]
}
}
}
```
If you want to cut one solid out of another, create both solids first,
then reference them by name as 'Base' and 'Tool'.
```json
{
"doc_name": "MyPart",
"obj_name": "Cut",
"obj_type": "Part::Cut",
"obj_properties": {
"Base": "Box",
"Tool": "Cylinder"
}
}
```
If you want to create a pipe with an outer diameter of 250, a 10 wall
and a length of 500, you can use the following data.
```json
{
"doc_name": "MyPipe",
"obj_name": "Pipe",
"obj_type": "Part::Tube",
"obj_properties": {
"OuterRadius": 125,
"InnerRadius": 115,
"Height": 500
}
}
```
If you want to create a FEM analysis, you can use the following data.
```json
{
"doc_name": "MyFEMAnalysis",
"obj_name": "FemAnalysis",
"obj_type": "Fem::AnalysisPython",
}
```
If you want to create a FEM constraint, you can use the following data.
```json
{
"doc_name": "MyFEMConstraint",
"obj_name": "FemConstraint",
"obj_type": "Fem::ConstraintFixed",
"analysis_name": "MyFEMAnalysis",
"obj_properties": {
"References": [
{
"object_name": "MyObject",
"face": "Face1"
}
]
}
}
```
If you want to create a FEM mechanical material, you can use the following data.
```json
{
"doc_name": "MyFEMAnalysis",
"obj_name": "FemMechanicalMaterial",
"obj_type": "Fem::MaterialCommon",
"analysis_name": "MyFEMAnalysis",
"obj_properties": {
"Material": {
"Name": "MyMaterial",
"Density": "7900 kg/m^3",
"YoungModulus": "210 GPa",
"PoissonRatio": 0.3
}
}
}
```
If you want to create a FEM mesh, you can use the following data.
The `Shape` property is required (legacy `Part` is also accepted).
On FreeCAD 1.x the size limits are `CharacteristicLengthMax/Min`;
the legacy `ElementSizeMax/Min` keys are also accepted.
```json
{
"doc_name": "MyFEMMesh",
"obj_name": "FemMesh",
"obj_type": "Fem::FemMeshGmsh",
"analysis_name": "MyFEMAnalysis",
"obj_properties": {
"Shape": "MyObject",
"CharacteristicLengthMax": 10,
"CharacteristicLengthMin": 0.1
}
}
```
Inputs: doc_name (required), obj_name (required), obj_type (required), view_name, +3 more.
define_interfaceB
Define a mounting interface: planar mating face and >=2 ordered full inner cylinders.
Hole order determines correspondence, including symmetric patterns. Cylinders must
open onto the plane and be perpendicular to it. owner defaults to part; for a
feature inside a PartDesign Body, supply the Body name. No document changes.
Inputs: part (required), doc_name (required), hole_faces (required), plane_face (required), +1 more.
delete_objectA
Delete an object in FreeCAD.
Args:
doc_name: The name of the document to delete the object from.
obj_name: The name of the object to delete.
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when visual feedback is not needed,
e.g. for intermediate steps in a longer sequence of changes.
view_name: The view orientation of the returned screenshot (default "Isometric").
Pick the view that best shows the change being made.
Returns:
A message indicating the success or failure of the object deletion and a screenshot of the object.
Inputs: doc_name (required), obj_name (required), view_name, include_screenshot.
edit_objectA
Edit an object in FreeCAD.
This tool is used when the create_object tool cannot handle the object creation.
Args:
doc_name: The name of the document to edit the object in.
obj_name: The name of the object to edit.
obj_properties: The properties of the object to edit.
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when visual feedback is not needed,
e.g. for intermediate steps in a longer sequence of changes.
view_name: The view orientation of the returned screenshot (default "Isometric").
Pick the view that best shows the change being made.
Returns:
A message indicating the success or failure of the object editing and a screenshot of the object.
Inputs: doc_name (required), obj_name (required), obj_properties (required), view_name, +1 more.
execute_codeA
Execute arbitrary Python code in FreeCAD.
Args:
code: The Python code to execute.
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when the code does not change the model's
appearance, e.g. analytical or computational scripts whose result is
printed output, or intermediate steps in a longer sequence of changes.
view_name: The view orientation of the returned screenshot (default "Isometric").
Pick the view that best shows the change being made.
timeout: Positive finite seconds for each of the queue and GUI execution
budgets, overriding the 90 s default for this call (capped at 1800).
Raise it for slow work that must
run on the GUI thread, such as importing or exporting a large STEP
assembly. Without it the call reports a timeout while the task keeps
running, and the result is lost even though the work finishes. Prefer
execute_code_async for heavy pure-geometry work that touches neither
the document nor the GUI.
Returns:
A message indicating the success or failure of the code execution, the output of the code execution, and a screenshot of the object.
Inputs: code (required), timeout, view_name, include_screenshot.
execute_code_asyncA
Execute Python code in FreeCAD without waiting for completion.
Use this ONLY for long-running background computations that do NOT touch the
FreeCAD GUI or mutate the FreeCAD document tree directly.
This tool runs the submitted code in a background thread and returns
immediately. Because it does not run on FreeCAD's main GUI thread, the code
must NOT directly call FreeCADGui APIs, manipulate the active view or
selection, create or edit document objects, change object properties, call
doc.recompute(), or save documents. FreeCAD documents and the Coin3D
scenegraph are not thread-safe: writing to them from this thread races the
GUI thread and can wedge FreeCAD's event loop, after which the RPC server
stops responding entirely and FreeCAD must be restarted.
Every document or view write must instead be handed to the GUI thread through
the injected commit() helper:
commit(fn, timeout=120) -> fn's return value
Scripts share a live namespace. Saved functions can use commit() in later
async calls; calling it from execute_code or a GUI callback raises immediately.
Coordinate concurrent scripts that intentionally modify the same variables.
commit() queues fn on the GUI thread, waits for it, and raises RuntimeError if
dispatch fails or times out. Example:
fused = base.fuse(addition).removeSplitter() # slow, safe in background
def apply(): # runs on the GUI thread
obj.Shape = fused
doc.recompute()
commit(apply)
For code that is not dominated by heavy geometry computation, use execute_code
instead. execute_code runs entirely on the FreeCAD GUI thread and is the safe
default for normal FreeCAD automation.
Use execute_code_async only when the heavy part is long-running OCCT geometry
(e.g. fuse/cut/loft on already-fetched shapes) or other CPU-bound computation
that would exceed execute_code's 90 s GUI-thread budget.
Typical usage pattern:
1. Fetch shapes into module-level variables first (via execute_code).
2. Run the heavy computation via execute_code_async.
3. Apply the result inside commit(), or store it in a module-level Python
variable (not in the FreeCAD document) for a later execute_code call.
Performance note: boolean operations against shapes with many faces (e.g. a
ribbed lid) are expensive. Fuse the additions together first, then apply a
single boolean against the heavy shape, and avoid doc.recompute() unless the
dependency graph really needs it.
Args:
code: Background-safe Python code to execute. Use commit(fn) for all
document and view writes.
Returns:
A message with the job_id of the started background execution.
Inputs: code (required).
execute_code_headlessA
Run a FreeCAD Python script in a separate headless freecadcmd process.
Use this for OCCT work that can crash or block FreeCAD: helical threads
(makeHelix + makePipeShell), lofts and sweeps, booleans with many or
B-spline tools, long parametric rebuilds. A native OpenCascade crash
here only kills the helper process; the GUI and its open documents
survive, and the tool reports the crash signal and the script's output.
The script runs on the MCP server machine, independently of --host, in a
fresh process without GUI: import FreeCAD/Part
yourself, open documents from disk (FreeCAD.openDocument(path)), save
results with doc.save()/saveAs() or Shape.exportBrep(). Nothing from the
execute_code namespace is available. Print progress to stdout; it is
returned when the process ends. After the script saved a .FCStd that is
open in the GUI, call reload_document(doc_name) to show the result.
Args:
code: Complete Python script for freecadcmd.
timeout: Positive finite seconds to wait before killing the process
(default 600). Partial output is preserved on timeout.
Returns:
Exit status, crash/timeout diagnosis and the script's printed output.
Inputs: code (required), timeout.
get_assembly_capabilitiesB
Check native addon protocol and supported assembly operations before working.
Inputs: no named parameters.
get_assembly_jobA
Poll without waiting for the GUI. Includes durable outcome and native PNGs when done.
outcome_unknown means the GUI exceeded its dispatch budget and may still finish:
continue polling; do not duplicate the mutation. Results last until history eviction
(32 completed jobs) or FreeCAD exit.
Inputs: job_id (required), include_result.
get_async_statusA
Report the state of background jobs started by execute_code_async.
Does not use the FreeCAD GUI thread, so it answers even while a job runs.
Args:
job_id: The id returned by execute_code_async. Empty lists all running
jobs and up to 20 recently completed jobs.
Returns:
For one job: its state (running/done/failed), the error and traceback
when it failed. History is held in memory until FreeCAD exits.
Inputs: job_id.
get_document_statusA
Read which open documents need saving, without saving or recomputing anything.
Empty doc_name lists all; otherwise inspect one named document. modified is the
GUI dirty flag (same save-state indicator as the UI), saved_once means saved before,
needs_recompute is independent. needs_save is true for new/modified/missing-file
documents; null means the dirty flag could not be read, never assumed clean.
file_path and file_exists identify the associated disk file. App.save()/saveAs()
can leave the GUI modified flag set; this reports the actual GUI flag honestly.
Inputs: doc_name.
get_objectA
Get an object from a document. You can use this tool to get the properties of an object to see what you can check or edit.
Args:
doc_name: The name of the document to get the object from.
obj_name: The name of the object to get.
include_screenshot: Whether to return a screenshot of the document (default True).
Set to False to save tokens when only the object data is needed.
view_name: The view orientation of the returned screenshot (default "Isometric").
Returns:
The object and a screenshot of the object.
Inputs: doc_name (required), obj_name (required), view_name, include_screenshot.
get_objectsB
Get all objects in a document. You can use this tool to get the objects in a document to see what you can check or edit.
Args:
doc_name: The name of the document to get the objects from.
include_screenshot: Whether to return a screenshot of the document (default True).
Set to False to save tokens when only the object data is needed.
view_name: The view orientation of the returned screenshot (default "Isometric").
Returns:
A list of objects in the document and a screenshot of the document.
Inputs: doc_name (required), view_name, include_screenshot.
get_parts_listB
Get the list of parts in the parts library addon.
Inputs: no named parameters.
get_rpc_statusA
Get RPC and FreeCAD GUI-dispatch health.
This tool does not use FreeCAD's GUI thread, so it remains available after
a GUI operation times out. A ``stuck`` state identifies the operation that
is still running and indicates that FreeCAD may need to be restarted.
``version_check`` is "ok" or says whether the addon or the server needs
updating.
Inputs: no named parameters.
get_viewB
Get a screenshot of the active view.
Args:
view_name: The name of the view to get the screenshot of.
The following views are available:
- "Isometric"
- "Front"
- "Top"
- "Right"
- "Back"
- "Left"
- "Bottom"
- "Dimetric"
- "Trimetric"
width: The width of the screenshot in pixels. If not specified, uses the viewport width.
height: The height of the screenshot in pixels. If not specified, uses the viewport height.
focus_object: The name of the object to focus on. If not specified, fits all objects in the view.
Returns:
A screenshot of the active view.
Inputs: view_name (required), width, height, focus_object.
insert_part_from_libraryA
Insert a part from the parts library addon.
Args:
relative_path: The relative path of the part to insert.
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when visual feedback is not needed,
e.g. for intermediate steps in a longer sequence of changes.
view_name: The view orientation of the returned screenshot (default "Isometric").
Pick the view that best shows the change being made.
Returns:
A message indicating the success or failure of the part insertion and a screenshot of the object.
Inputs: relative_path (required), view_name, include_screenshot.
inspect_partA
Inspect world-space valid geometry, planar faces and cylindrical hole candidates.
Start here before assembly work. Face names are temporary references; define_interface
binds them to geometry fingerprints. Does not move parts or change the camera.
Faces are paginated (1..500 per type); follow next_plane_offset/next_cylinder_offset
when present. feature_counts gives full totals.
Inputs: part (required), doc_name (required), plane_offset, feature_limit, +1 more.
inspect_regionA
See 1..6 focused views of selected parts, with world-geometry fingerprints.
Default Isometric/Top/Right. Produces native MCP PNG images, temporarily hides other
objects and restores camera/visibility. Requested document must be active in 3D.
size is square pixels (256..1536). Visual evidence supplements check_assembly.
Inputs: parts (required), doc_name (required), size, views.
list_documentsB
Get the list of open documents in FreeCAD.
With include_status=true, also return labels, file paths, GUI modified flags,
needs_save and needs_recompute. Default preserves the list of names.
Returns:
A list of document names, or a structured status snapshot.
Inputs: include_status.
plan_alignmentA
Plan rigid placement matching ordered holes and opposing mounting faces. No mutation.
Positive gap follows the fixed face outward normal. Checks all hole matches, refuses
stale geometry and degenerate patterns. Collision scope during apply is the fixed
part plus explicitly named obstacles; include nearby parts. No correspondence guessing.
Review this plan, then apply_alignment. Handles expire after FreeCAD restart/code update.
Inputs: fixed_interface (required), moving_interface (required), gap_mm, obstacles, +3 more.
preview_alignmentA
See the proposed placement without changing the document: cyan ghost + green/orange axes.
Produces native PNGs and removes all temporary scene-graph overlays afterwards.
The plan must be fresh and unapplied. Does not add document objects or move parts.
Inputs: plan_id (required), size.
reload_documentA
Close and re-open a document to pick up external file changes.
Use this AFTER the document's .FCStd file has been modified by
something outside of FreeCAD's GUI process — for example, a
headless `freecadcmd` script that edited and saved the file. The
open GUI document is otherwise unaware of on-disk changes; this
tool closes the stale in-memory copy and reopens the file from
disk so the GUI shows current geometry.
Args:
doc_name: The name of the open document to reload. Must match
the name shown by ``list_documents``.
Returns:
A message confirming the document was reloaded, or describing
the failure (document not loaded, no associated file, etc).
FreeCAD names the reopened document after the file stem, which
can differ from ``doc_name`` ("HandleConcept3D" saved as
handle-concept-3d.FCStd reopens as handle_concept_3d); the reply
names the document you should use from then on.
Examples:
```json
{
"doc_name": "chassis"
}
```
Inputs: doc_name (required).
run_fem_analysisA
Run the CalculiX solver on an existing Fem::FemAnalysis container and return summary results.
Prerequisites in the document:
- A Part-derived solid (e.g. Part::Box, PartDesign::Body) acting as the geometry.
- A Fem::AnalysisPython container created via `create_object`.
- A Fem::MaterialCommon assigned to the geometry, added to the analysis.
- A Fem::FemMeshGmsh referencing the geometry, added to the analysis (the
mesh is generated automatically when created via `create_object`).
- At least one Fem::ConstraintFixed and one Fem::ConstraintForce (or
ConstraintPressure) bound to faces of the geometry, added to the analysis.
A SolverCcxTools is auto-created if the analysis has none.
The solver runs synchronously on the FreeCAD GUI thread and blocks all
other RPC calls for its duration; do not fan out parallel requests.
Returns max von Mises stress (MPa), max/min displacement (mm), node count,
and the working directory CalculiX wrote to. On failure, returns the
prerequisite-check or solver error along with the working directory for
triage.
Args:
doc_name: Name of the FreeCAD document.
analysis_name: Name of the Fem::AnalysisPython object.
timeout: Seconds to wait for the solver (default 600).
include_screenshot: Whether to return a screenshot of the model (default True).
Set to False to save tokens when only the numeric results are needed.
view_name: The view orientation of the returned screenshot (default "Isometric").
Inputs: doc_name (required), analysis_name (required), timeout, view_name, +1 more.
start_assembly_operationA
Submit a native CAD job immediately; keep request_id to retry the SAME request safely.
Allowed operations are reported by get_assembly_capabilities. No arbitrary Python.
Returns job_id; poll get_assembly_job. Reusing request_id with different args fails.
Idempotency lasts while the job is retained in addon history; jobs survive MCP restart,
but not FreeCAD exit. Use this for long operations instead of waiting on a tool call.
Inputs: arguments (required), operation (required), request_id (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 31 tools
Most tools target distinct FreeCAD resources or workflow stages, but several clusters overlap: execute_code/execute_code_async/execute_code_headless, get_async_status/get_assembly_job, and the numerous assembly inspection/planning/checking tools. Detailed descriptions help, but an agent can still misselect among the code-execution and job-polling variants.
Names are overwhelmingly snake_case with a predictable verb_noun pattern: get_*, create_*, list_*, inspect_*, plan_*, apply_*, start_*, cancel_*. Minor deviations like get_parts_list, get_async_status, and execute_code_headless keep it from being perfectly consistent.
With 31 tools, the surface is heavy for an MCP server and exceeds the typical well-scoped range. Multiple specialized tools are useful for FreeCAD, but several could be consolidated, especially the three execute_code variants and separate job-status pollers.
The surface covers document lifecycle, object CRUD, viewing, parts library, FEM, assembly/alignment, and async job management, with execute_code serving as a broad fallback for missing operations. Minor gaps remain, such as explicit save/export/close document tools, but agents can work around them via code execution.
Related MCP Connectors
Parametric 3D CAD for AI agents: build print-ready parts, check them, export STL, 3MF or STEP.
Browser CAD for AI: model parts and joints, check motion, export STEP, STL or robot files
CAD in ChatGPT and Claude: editable parts, STEP/STL/drawings, in-chat 3D, automatic checks.
Turn agent intent into physical parts: engineering review, measured geometry, calibrated pricing.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI assistants to build and edit native CAD parts and assemblies, inspect saved geometry and measurements, retain revisions, run mechanism and interference checks, and export STEP/STL/GLB artifacts through MCP tools.MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents on Windows to build parts from JSON recipes, create and verify whole assemblies in a single call, check mass, center of mass, mates and interference, produce drawings with BOM, balloons and sections, work with sheet metal, and import/export STEP, IGES, PDF and DXF files. All edits run with automatic backups and verified rollback so user files are never left broken.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to drive desktop CAD software through natural language with verified execution, failure recovery, and traceable results across modeling, assemblies, drawings, exports, motion, FEA, and related engineering workflows.1MIT
- FlicenseBqualityCmaintenanceEnables AI agents to drive SolidWorks for parametric modelling, aerospace part generation, sheet metal, weldments, assemblies, drawings, simulation, inspection, and file export. It provides approval-gated operations, verification tools, and journaling for safe, recoverable design automation.94-