kompas3d
Summary: A local MCP server that lets an AI agent drive KOMPAS-3D through 41 tools — creating, editing, inspecting, and exporting parametric CAD models, assemblies, and drawings via API5/API7.
Connect & documents: connect to/launch KOMPAS-3D, attach to an already-open model, list/open/create/close/save native parts, assemblies, drawings, fragments, specifications, and text documents, and import STEP/IGES/STL.
Sketching & modeling: draw circles, arcs, and polylines on XY/XZ/YZ, offset, or native-face planes; extrude, revolve, and create arbitrary API5 features (shells, lofts, sweeps, ribs, drafts, patterns, mirrors).
Edge treatment: fillet or chamfer selected edges by ID with radius/leg sizes.
Editing: update feature definitions, rename, hide/show, suppress/restore, delete features, and rebuild the model.
Inspection & verification: discover native entities (edges/faces/features) with geometry data, measure bounding box, render PNG previews, and read mass/volume/area properties.
Parametrization: read and set user variables or feature expressions (numeric or native expressions) with rebuild, and assign material plus density to report mass.
Assemblies: insert native part/subassembly occurrences into an assembly with linked placements.
Drawings: create associative standard views, and add native editable lines, circles, linear dimensions, and text.
Export: save editable M3D/A3D and export STEP, STL, or IGES (license/converter dependent).
Blueprint reading: render local PNG/JPEG/TIFF/WebP images or PDF pages (with normalized cropping) for the client model to interpret — no built-in OCR.
SDK access: search and read installed SDK help topics, browse all API5/API7 interfaces, describe interfaces and methods, and look up enum constants.
Advanced COM control: unrestricted low-level calls via
api_invoke, ordered batches up to 100 steps viaapi_batch, and QueryInterface casting viaapi_cast(bypasses typed protections; no rollback).
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., "@kompas3d Create a plate 80×50×8 mm with four Ø6 through holes and export it as STEP."
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.
КОМПАС-3D MCP
Локальный MCP-сервер, с которым ИИ-агент создаёт и редактирует модели в КОМПАС-3D по текстовому описанию, чертежу или PDF. Результат: редактируемая модель с нативными операциями КОМПАС, а также экспорт в STEP, STL и IGES.
41 инструмент, 3 навыка для агента и доступ к API5/API7. Помимо моделирования: параметры и выражения, сборки, чертежи, размеры, материалы и работа с документами. Проверено на Windows, КОМПАС-3D v25 Home и Python 3.12.
Чертёж и описание понимает ИИ-клиент. Сервер выполняет команды в КОМПАС, возвращает измерения и изображения модели. Отдельного OCR или нейросети text-to-3D в сервере нет.
Быстрая установка в Codex
Понадобятся Windows, установленный КОМПАС-3D с действующей лицензией и SDK, а также Codex с поддержкой MCP. КОМПАС должен быть зарегистрирован для COM-автоматизации, как при обычной установке программы. Другие версии и редакции пока не проверены.
На странице этого репозитория нажмите Code → Download ZIP. Распакуйте архив в постоянную папку, например
C:\Tools\Compass3DMCP. Откройте именно папку с файломinstall.ps1.Установите uv из PowerShell:
winget install --id astral-sh.uv --exactЗакройте и снова откройте PowerShell, перейдите в папку проекта и запустите установку:
cd C:\Tools\Compass3DMCP powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1Перезапустите Codex. Попросите: «Подключись к КОМПАС через kompas3d и создай тестовую деталь».
Установщик создаёт окружение Python, устанавливает зависимости, регистрирует сервер kompas3d и копирует три навыка в Codex. uv может загрузить подходящий Python автоматически. Интернет нужен для установки зависимостей; сервер работает локально через stdio, без порта и отдельного API-ключа. ИИ-клиент может использовать облачную модель.
Настройки находятся в %USERPROFILE%\.codex, либо в папке CODEX_HOME, если она задана. Перед изменением существующего конфига создаётся резервная копия. Чужие настройки сохраняются; при конфликтующей записи kompas3d установщик остановится с пояснением.
Не перемещайте и не удаляйте папку проекта после установки: Codex запускает Python из её .venv.
Ручная установка
В PowerShell из папки проекта:
uv sync --locked
uv run python scripts/install.pyОбновление
Обновите файлы проекта в той же папке через git pull либо распакуйте свежий ZIP поверх исходных файлов. Затем выполните:
powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -UpdateSkillsИли вручную:
uv sync --locked
uv run python scripts/install.py --update-skillsИзменённые копии навыков сохраняются в резервную папку перед заменой. Перезапустите Codex.
Related MCP server: CadKitty
Другие MCP-клиенты
Выполните uv sync --locked из папки проекта. Добавьте сервер в конфигурацию своего клиента, заменив путь на абсолютный путь к вашей установке:
{
"mcpServers": {
"kompas3d": {
"command": "C:/Tools/Compass3DMCP/.venv/Scripts/python.exe",
"args": ["-m", "kompas_mcp.server"]
}
}
}Формат настроек зависит от клиента. Транспорт: stdio. Рекомендуемый тайм-аут команды: 180 секунд, запуска: 30 секунд. Ручной запуск сервера: uv run kompas3d-mcp.
Автоустановка навыков рассчитана на Codex. В другом клиенте используйте инструкции из папки skills в поддерживаемом им формате. Для анализа изображений чертежей нужна модель, умеющая читать изображения.
Что можно поручить агенту
Используй $kompas-modeling. Создай пластину 80 × 50 × 8 мм с четырьмя сквозными отверстиями Ø6 мм. Центры отверстий расположи в 10 мм от двух ближайших краёв. Сохрани редактируемую модель и копию STEP в C:\Models.
Используй $kompas-blueprints. Построй модель по приложенному PDF. Составь список размеров и их источников. Если размеры не заданы, сначала уточни их.
Используй $kompas-api. Найди четыре наружных вертикальных ребра этой детали и добавь скругление радиусом 2 мм. Проверь результат измерениями.
Навык | Для чего нужен |
Планирование модели, эскизы и операции, изменение деталей, проверка геометрии | |
Чтение видов и разрезов, российские обозначения на чертежах, учёт размеров и недостающих данных | |
Поиск в установленном SDK, сложные операции, API5/API7, выбор граней и рёбер, диагностика |
Возможности и степень готовности
Область | Возможности |
Моделирование | Эскизы, выдавливание и вырезание, вращение, скругления, фаски, оболочки, сечения и траектории |
Изменение деталей | Поиск граней и рёбер, изменение и подавление операций, линейные массивы, зеркальные копии |
Параметризация | Переменные и выражения, перестроение, материал и плотность; ограничения эскиза через API |
Сборки и документы | Создание и открытие деталей, сборок, чертежей, фрагментов, спецификаций и текстовых документов; вставка компонентов |
Чертежи | Ассоциативные стандартные виды, линии, окружности, линейные размеры и текст |
Проверка и обмен | Объём, площадь, масса, габариты, число тел, PNG-превью, сохранение и экспорт |
Расширенные команды | Поиск справки SDK, просмотр интерфейсов и вызовы COM, последовательности зависимых операций |
Не требуется отдельный MCP-инструмент для каждой кнопки КОМПАС: общие инструменты настраивают нативные операции и вызывают API. На проверенной установке каталог содержит 1 119 интерфейсов SDK. Доступ к интерфейсу сам по себе не означает, что каждый сценарий проверен.
Проверены в живом КОМПАС, в том числе с сохранением и повторным открытием: базовые тела и вырезы, скругления и фаски, оболочки, элемент по сечениям, линейные массивы и зеркальные копии, изменение толщины листовой заготовки, управляющие переменные, отдельные ограничения эскиза, вставка компонента и создание видов чертежа.
Сопряжения сборок, сложные поверхности, гибка и развёртка, расширенные отверстия и резьбы, спецификации с наполнением и дополнительные модули ещё не прошли полную проверку сценариев. Подробное разделение проверенного, доступного через API и непроверенного есть в карте покрытия. Список всех инструментов и технические подробности: English README.
Если что-то не работает
uvне найден: переоткройте терминал после установки. Еслиwingetнедоступен, установите uv по официальной инструкции.SDK не найден: проверьте наличие
SDK/libи архива справки в установленном КОМПАС. Автопоиск используетC:/Program Files/ASCON/KOMPAS*/SDK. Для другого пути задайте переменную средыKOMPAS_SDK_PATH, указывающую на папку SDK, и перезапустите клиент.Ошибка подключения COM: проверьте, что КОМПАС установлен и запускается. При нескольких версиях регистрация COM определяет запускаемую версию и должна соответствовать выбранному SDK.
Файл уже открыт: попросите агента использовать
attach_active_modelи проверить путь активного документа.После перезапуска пропали ссылки на объекты: идентификаторы действуют в рамках сеанса. Нужно заново открыть или подключить документ и найти геометрию.
Команда зависла или истёк тайм-аут: отмена запроса не прерывает уже выполняющуюся операцию КОМПАС. Проверьте состояние документа перед повтором.
Важные ограничения
Все размеры геометрии задаются в миллиметрах, углы в градусах. Эскизы редактируемые, но не получают полный набор ограничений автоматически.
Агент должен проверять размеры и геометрию: правдоподобное изображение не доказывает соответствие чертежу. Неуказанные размеры требуют уточнения или явно обозначенных допущений.
Импорт STEP проверен как твёрдое тело. STL может дать полигональную геометрию без истории операций. Импорт IGES в локальной проверке не сработал.
Операции выполняются последовательно, без автоматического отката. При ошибке часть изменений может сохраниться.
Общие
api_invokeиapi_batchпредоставляют широкий доступ к локальному COM, включая изменение и удаление объектов и запись файлов. Используйте сервер только с доверенным локальным клиентом.
Для разработчиков
uv sync --locked
uv run pytest -q
uv run ruff check src tests scriptsМодульные и протокольные тесты не запускают КОМПАС. Для проверки реальной CAD-автоматизации есть scripts/validate_live.py и тематические scripts/validate_*.py: они запускают приложение и создают тестовые документы. Результаты сохраняются в artifacts, подробности и команды перечислены в English README.
Проект использует установленный SDK АСКОН и MCP Python SDK. КОМПАС-3D и его SDK в репозиторий не входят.
Вопросы, предложения и ошибки
По любым вопросам, идеям и найденным ошибкам создавайте issue в этом репозитории. Для ошибки укажите версию КОМПАС-3D, используемый MCP-клиент, шаги воспроизведения и текст сообщения об ошибке.
Лицензия
Проект распространяется по лицензии MIT. Условия использования КОМПАС-3D и SDK определяются АСКОН.
Available Tools
41 toolsapi_batchA
Execute up to 100 ordered SDK steps; stop on first failure and return partial results.
Targets/arguments support {handle:id}, {ref:prior_step_id}, {constant:enum_name}. Typed arrays: {variant:{type:dispatch_array|int_array|double_array|variant_array,values:[...]}}. Set expect=truthy for BOOL operations or not_null for object creation. No rollback. This has the same unrestricted local COM authority as api_invoke.
Inputs: plan (required).
api_castB
QueryInterface to an additional installed SDK interface, e.g. IPart7 to IModelContainer.
A known type does not guarantee that a given object supports it. COM failure is reported.
Inputs: handle (required), interface (required), library.
api_catalogB
Search/paginate every installed API5/API7 interface by name; discover hidden capabilities.
Inputs: limit, query, offset, library.
api_constantsA
Find installed SDK enum names/values by case-insensitive substring.
Inputs: query (required).
api_describeB
Read generated SDK method signatures and readable/writable properties.
Inputs: handle (required).
api_describe_interfaceB
Get schema for any installed interface without needing an object of that type first.
Inputs: library (required), interface (required).
api_invokeA
Advanced unrestricted local COM access, including mutations and file operations.
Inspect the interface first. Pass COM arguments as {"handle":"..."}. Returned COM objects become session handles. This bypasses typed save/ownership protections. Use only documented SDK members within the user's requested work. False/zero results are returned verbatim and may indicate API failure.
Inputs: handle (required), member (required), value, action, +1 more. Returns: result
attach_active_modelA
Explicitly adopt the active 3D document and return its name/path and stable session ID.
Use when the user requests work on an already-open model. Verify returned identity.
Inputs: no named parameters.
blueprint_viewA
Read local PNG/JPEG/TIFF/WebP or a PDF page (1-based) as an image.
Optional crop is normalized [left,top,right,bottom] in 0..1. Cropping before downsampling helps read small dimensions. Maximum returned dimension is 2400px. This renders input; interpretation/OCR is the MCP client's responsibility.
Inputs: path (required), crop, page.
close_documentA
Close this document only. Refuses unsaved changes unless discard_changes is explicitly true.
Inputs: handle (required), discard_changes.
connectA
Connect to or launch local KOMPAS-3D; return version and application handle.
Inputs: visible.
create_documentA
Create a native part, assembly, drawing, fragment, specification or text document.
Returns API7 handles; use create_part when you need a document_id for typed API5 modeling tools.
Inputs: kind (required), visible.
create_featureA
Create any API5 NewEntity-supported feature using documented definition settings.
entity_type is an o3d_ enum. properties maps writable names to values. calls contain member/arguments/expect and optional via zero-argument getters. References: {entity_id:id} within this document, {handle:id}, {constant:name}. Used for shells, lofts, sweeps, ribs, drafts, patterns, mirrors and more. API7-only operations require api_cast/api_batch. Read SDK first; no universal recipe is implied.
Inputs: settings (required), document_id (required), entity_type (required), name.
create_partB
Create a new native part without replacing the user's open documents.
Inputs: name.
create_sketchA
Draw circles, arcs and polylines on XY/XZ/YZ or offset planes. Geometry is mm.
Revolutions need one open two-point construction polyline as the rotation axis. Sketch coordinates are local to the selected KOMPAS plane, not world XYZ. support_entity_id can select a native face or construction plane instead of plane/offset.
Inputs: spec (required), document_id (required).
create_standard_viewsC
Create associative engineering views from a native model in a drawing. Coordinates/gaps are mm.
Inputs: model_path (required), projections (required), drawing_handle (required), x, +5 more.
delete_featureA
Delete the explicitly selected native feature. Dependents may be affected.
Rejects face/edge/vertex deletion because API5 would silently delete its owner.
Inputs: entity_id (required), document_id (required).
draw_circleB
Draw a native editable circle in a drawing/fragment view; radius in mm.
Inputs: x (required), y (required), radius (required), drawing_handle (required), +2 more.
draw_lineB
Draw a native editable line in a drawing/fragment view; coordinates in mm.
Inputs: x1 (required), x2 (required), y1 (required), y2 (required), +3 more.
draw_linear_dimensionC
Create a native measured 2D linear dimension between points, with chosen text location.
Inputs: x1 (required), x2 (required), y1 (required), y2 (required), +5 more.
draw_textB
Add native editable text to a drawing/fragment view; position mm and angle degrees.
Inputs: x (required), y (required), text (required), drawing_handle (required), +2 more.
export_modelC
Export STEP/STL/IGES. Availability depends on installed KOMPAS license/converters.
Inputs: path (required), document_id (required), overwrite.
extrudeC
Add or cut a finite-depth extrusion from an existing sketch.
Inputs: spec (required), document_id (required).
insert_componentB
Insert a native part/subassembly occurrence in an explicit assembly. Returns placement handle.
Inputs: path (required), assembly_handle (required), linked.
inspect_modelA
Return bounding box (success,x1,y1,z1,x2,y2,z2), entity IDs and COM handles.
Session entities are only those created by typed tools, not the full feature tree. Use the part's EntityCollection through api_invoke for existing model topology.
Inputs: document_id (required).
list_documentsA
List all open native documents with identity, changed/read-only state and typed API7 handles.
Inputs: no named parameters.
list_entitiesA
Discover existing native entities, including imported/reopened models.
kind is an installed o3d_ enum, e.g. o3d_edge, o3d_face, o3d_fillet. Edges include endpoint/bounds/length data; faces include area/surface type/bounds. solid_only defaults true to exclude sketch and datum geometry from edges/faces. Select by geometric evidence. Rediscover topology after modifications.
Inputs: document_id (required), kind, limit, offset, +1 more.
list_variablesA
Read user variables or a specific native feature's driving variables and expressions.
Inputs: document_id (required), feature_id.
model_previewB
Render the document's current view to a PNG image for visual verification.
Inputs: document_id (required).
open_documentC
Open any of the six native document formats with explicit read-only/visibility choices.
Inputs: path (required), visible, read_only.
open_modelA
Open native M3D/A3D or import STEP/IGES/STL, returning an explicit document ID.
Inputs: path (required).
revolveC
Add or cut a revolution. Sketch must contain a profile and construction axis.
Inputs: spec (required), document_id (required).
save_documentB
Save a native API7 document. Enforces matching extension, read-only state and overwrite policy.
Inputs: path (required), handle (required), overwrite.
save_modelA
Save editable native M3D/A3D at an absolute path; no overwrite by default.
Inputs: path (required), document_id (required), overwrite.
sdk_readA
Read an exact SDK HTML topic as text, including linked topics for navigation.
Inputs: topic (required), length, offset.
sdk_searchA
Find installed SDK topics by interface/member/enum filename substring, e.g. fillet.
Inputs: query (required), limit.
set_entity_stateC
Rename, hide/show, or suppress/restore a native entity and rebuild.
Inputs: entity_id (required), document_id (required), name, hidden, +1 more.
set_materialB
Assign a part material and physical density in g/cm³, then report updated mass in kg.
Inputs: name (required), document_id (required), density_g_cm3 (required).
set_variableC
Set one numeric value OR native expression and rebuild. Explicit create enables new user variables.
Inputs: name (required), document_id (required), note, value, +3 more.
treat_edgesB
Fillet or chamfer selected current edges. size is radius or first chamfer leg in mm.
second_size defaults to equal chamfer legs. Edges are IDs from list_entities(o3d_edge).
Inputs: spec (required), document_id (required).
update_featureA
Modify an existing native feature definition and rebuild the model. Partial changes may remain on failure.
Inputs: settings (required), entity_id (required), document_id (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 41 tools
Several tool families overlap in purpose, notably open_model/open_document, create_part/create_document, save_model/save_document, and inspect_model/list_entities. The SDK/API discovery cluster (api_describe_interface, api_describe, api_constants, api_catalog, api_cast, sdk_search, sdk_read) is also very hard to distinguish without reading each description. An agent would frequently need to dig into details before confidently choosing a tool.
Most names use snake_case verb_noun form, and subgroups like draw_*, list_*, and create_*/update_*/delete_* are internally consistent. However, conventions are split across api_*, sdk_*, bare verbs like connect/extrude/revolve, and noun-like names such as blueprint_view. api_describe_interface vs api_describe further blurs the otherwise readable pattern.
At 41 tools this is well above the 25-tool threshold for a coherent server, even considering CAD's broad scope. The count is inflated by a large SDK introspection family and parallel API5/API7 document workflows that could be consolidated. It feels heavy rather than curated.
Core workflows are covered: part modeling, sketch creation, features, document lifecycle, drawing views, import/export, variables, and materials. However, assembly support stops at insert_component with no typed assembly constraints, and 2D drawing annotations are limited to line/circle/linear dimension/text. The unrestricted api_invoke/api_batch tools can fill gaps, but only by leaving the typed, safe surface.
Maintenance
Related MCP Connectors
Parametric 3D CAD for AI agents: build print-ready parts, check them, export STL, 3MF or STEP.
CAD in ChatGPT and Claude: editable parts, STEP/STL/drawings, in-chat 3D, automatic checks.
DXF and PDF/X-4 for AI agents: structured facts, PNG renders, an interactive in-chat viewer.
A browser 3D CAD for your AI: it scripts real-size models, uCAD builds them and returns pictures.
Related MCP Servers
- AlicenseCqualityBmaintenanceEnables AI agents or local operators to inspect, plan, execute, and verify bounded KOMPAS-3D CAD operations, including sketch and feature editing, parametric parts, springs, transmissions, specifications, relinking, quality checks, and safe exports.1182MIT
- 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 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.MIT
- AlicenseNot gradedqualityBmaintenanceEnables an AI assistant to control KOMPAS-3D through its COM API, including opening and saving documents, building parts and assemblies, measuring models, and creating dimensioned drawings.MIT