Files
kompas3d-mcp/CLAUDE.md
T
mikhail 7087c4fd53 @
docs: актуализация CLAUDE.md под состояние v2

Current state → v1+v2 (28 инструментов, 18 тестов). Добавлены ключевые факты:
выбор граней/рёбер (SelectByPoint/индекс, классификация ksFaceDefinition),
МЦХ через API5 CalcMassInertiaProperties (почему не API7), габариты, ось вращения (стиль 3).
Обновлён список «не сделано» и каверза направления операций на грани.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@
2026-05-26 10:10:50 +03:00

9.7 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project goal

Build an MCP (Model Context Protocol) server that lets an LLM drive the CAD system КОМПАС-3D (ASCON). The server exposes КОМПАС operations (create/open documents, build 2D geometry, 3D parts and assemblies, read/write parameters, run macros) as MCP tools.

Authoritative references:

  • Offline SDK docs mirror in this repo: docs/KOMPAS_SDK_ru-RU/ — navigate it with tools/kdoc.py (see below). Prefer this over the web.
  • Online SDK docs: https://help.ascon.ru/KOMPAS_SDK/22/ru-RU/index.html
  • Local SDK install: C:\Program Files\ASCON\KOMPAS-3D v24 Home\SDK

Navigating the SDK docs (tools/kdoc.py)

docs/KOMPAS_SDK_ru-RU/ is a 26 000-page Help&Manual WebHelp export — raw HTML buried under header/footer/JS noise, with cryptic filenames. Do not browse it by hand. Use the helper:

python tools/kdoc.py search "<russian or interface keywords>"   # find pages: prints "file.html\tTitle"
python tools/kdoc.py read <file.html>                           # print clean topic text (no markup)
python tools/kdoc.py build-index                                # regenerate the index (only if docs change)

search does AND-matching over titles + excerpts; read extracts just the topic body (breadcrumb path, data type, Automation/COM syntax, parameters, return value, notes). Example: search Visible IApplicationiapplication_visible.html, then read iapplication_visible.html.

The index lives at docs/kompas_sdk_index.tsv (filename<TAB>title<TAB>excerpt) and can also be searched with the Grep tool directly — handy for fanning out over many interface names at once.

The docs contain two parallel mirrors of the same interfaces:

  • «API интерфейсов. Версия 7» — filenames without prefix (iapplication_*, idocuments_*). This is the COM API7/API5 reference — the one this project uses.
  • «API интерфейсов. KsAPI»ksapi_*-prefixed filenames: the cross-platform Qt/C++ KsAPI flavour. Same concepts, different (non-COM) binding — ignore unless explicitly working with KsAPI.

Current state

v1 + v2 implemented and working (full sketch→feature→inspect loop validated end-to-end). Stack: .NET 8 (net8.0-windows, x64), C#, MCP via the official ModelContextProtocol SDK over stdio. 28 MCP tools, 18 tests green. v2 added: sketch-on-face (by point and by index), revolve (boss/cut + sketch axis), fillet/chamfer (edge-by-point), and Query tools get_part_info (МЦХ), get_bounding_box, list_faces. See README.md and docs/ARCHITECTURE.md; design decisions/caveats in docs/OPEN_QUESTIONS.md.

Layout: src/Kompas.Mcp.Core (COM layer), src/Kompas.Mcp.Host (MCP stdio server + tools), tests/Kompas.Mcp.Tests (unit + integration), libs/kompas-interop/*.dll (vendored КОМПАС interop assemblies from SDK Samples/Common, referenced via Directory.Build.propsKompasInteropDir).

dotnet build -c Release                          # build
dotnet test  --filter "Category=Unit"            # unit tests (no COM)
dotnet test  --filter "Category=Integration"     # integration (requires running КОМПАС)
dotnet run --project src/Kompas.Mcp.Host         # start the MCP server (stdio)

Key implementation facts (don't relearn):

  • All COM calls run on one dedicated STA thread (KompasDispatcher.InvokeAsync); КОМПАС is single-instance STA. Services never touch COM off that thread.
  • Connection goes through API5 (KOMPAS.Application.5KompasObject) then ksGetApplication7()IApplication; the API5 root is needed for ksPart 3D-building and ksDocument3D snapshots.
  • 3D is built via API5 ksPart (NewEntity(o3d_sketch/o3d_bossExtrusion/o3d_bossRotated/o3d_fillet/o3d_chamfer/...), ksBossExtrusionDefinition/ksCutExtrusionDefinition/ksBossRotatedDefinition/ksFilletDefinition/ksChamferDefinition); cut-through holes use dtBoth + etThroughAll. API7 is used for app/documents.
  • Face/edge selection: ksPart.EntityCollection(o3d_face|o3d_edge)SelectByPoint(x,y,z) (world mm) filters to objects through the point, then GetByIndex(0); or by stable index from list_faces. ksFaceDefinition.IsPlanar/IsCylinder/... + GetArea(ST_MIX_MM) classify faces. Sketch axis = line with system style 3 (осевая).
  • МЦХ / mass props: use API5 ksPart.CalcMassInertiaProperties(ST_MIX_MM|ST_MIX_KG)ksMassInertiaParam (v/m/F/xc/yc/zc), computed on demand. Do NOT use API7 IMassInertiaParam7.Calculate() — its Actual flag sticks after the first calc and won't refresh on API5 geometry changes (stale volume). Bounding box: ksPart.GetGabarit(full:false, ...).
  • Snapshot: ksDocument3D.SaveAsToRasterFormat(file, ksRasterFormatParam) renders to a temp file (the in-memory resultArrayBytes stays empty when a filename is given); read bytes back. Return to MCP via ImageContentBlock.FromBytes(bytes, mime)not Data = bytes (Data holds base64 bytes).
  • Logs go to stderr (stdout is the MCP channel). Integration tests reuse one КОМПАС via KompasFixture; artifacts land in gitignored .scratch/.
  • Not yet done (next): patterns/arrays, list_bodies/list_edges, variables/properties (IVariable7), 2D drawing, assemblies, a proper in-process MCP-client test. Known caveat: boss/cut direction on a selected face depends on face-normal orientation (forward may need flipping — agent picks via snapshot). See docs/OPEN_QUESTIONS.md → «Ревью v2».

КОМПАС-3D API architecture (the critical context)

КОМПАС-3D is automated via a COM Automation API, Windows-only. КОМПАС-3D must be installed and running/launchable on the same machine — the MCP server is a COM client, not a standalone CAD engine. There are two coexisting API generations:

Entry point Namespace (C#) Style Use when
API5 (legacy) KompasObject Kompas6API5 procedural, flat older features, 2D primitives, bootstrapping
API7 (modern, preferred) IApplication / _Application KompasAPI7 OOP, interface-based everything new — documents, 3D, parameters

Constants live in separate libraries: Kompas6Constants, Kompas6Constants3D (C#), or ksConstants.h / ksConstants3D.h (C++).

Connection pattern (verified from Samples/CSharp.zip)

  1. Get the КОМПАС root object by COM ProgID. Verified on this machine (v24 Home): KOMPAS.Application.7 and KOMPAS.Application.5 are registered; KOMPASLT.* is absent — the Home edition uses the regular (non-LT) ProgIDs. Resolution order:
    • KOMPAS.Application.7 — direct API7 IApplication (preferred)
    • KOMPAS.Application.5 — API5 KompasObject, then ksGetApplication7()
    • KOMPASLT.Application.5 — fallback for other installations
    • New instance: Activator.CreateInstance(Type.GetTypeFromProgID(progId))
    • Attach to a running instance: Marshal.GetActiveObject(progId)
  2. If you entered via API5, obtain the modern application: IApplication appl = (IApplication)kompas.ksGetApplication7(); (via KOMPAS.Application.7 you already hold IApplication).
  3. Set appl.Visible = true to show the КОМПАС window; drive documents via API7 interfaces (IKompasDocument2D, IKompasDocument3D, …).

The SDK C# samples are mostly КОМПАС plugin libraries (DLLs loaded into КОМПАС as ActiveX, entry methods like ExternalRunCommand/ExternalMenuItem, registered via [ComRegisterFunction]). For an MCP server we want the opposite direction: a standalone external automation client that connects out-of-process via the ProgID pattern above. Read the samples for API usage, not for the plugin packaging/registration boilerplate.

SDK layout (read-only reference, not part of this repo)

Under C:\Program Files\ASCON\KOMPAS-3D v24 Home\SDK:

  • lib\*.tlb — COM type libraries to reference / generate interop from: kAPI5.tlb, kAPI7.tlb, ksConstants.tlb, ksConstants3D.tlb, kAPI2D5COM.tlb, kAPI3D5COM.tlb.
  • lib64\ — 64-bit import libs (kAPI7.lib, kAPI5.lib, …) and .a for C++/Builder.
  • Include\ — C++/Pascal headers (Ks_TLB.h, kAPI2D5COM.h, LDefin2D.pas, …).
  • KsAPI\ — the KsAPI (Qt/C++ cross-platform flavour): Include\KsAPI.h, ksConstants*.h, Lib64\ksAPI.lib, plus Help\С чего начать.pdf and a Linux/Debian 12 build guide.
  • Samples\ — zipped examples per language: CSharp.zip, C++.zip, Pascal.zip, Basic.zip. Inside CSharp.zip, the Step1Step12 and Step2_API7_2D / Step2_API7_3D projects are the progressive tutorial; Gayka, SlideWrk, EventsAuto are larger feature demos.
  • Help\KOMPAS_SDK_ru-RU.zip and KsAPI\Help\KsAPI_Help.zip — offline copy of the docs.

To inspect a sample without unpacking the whole archive: unzip -p "<path>\Samples\CSharp.zip" "Automation/Step2_API7_3D/Step2_API7_3D.cs". Note the .cs sample sources are Windows-1251 encoded (Cyrillic comments appear garbled in UTF-8 tools).

Conventions / gotchas

  • Windows-only & 64-bit: target x64 to match the installed КОМПАС; mixing bitness breaks COM activation. КОМПАС v24 Home is the installed edition — some full-edition API features may be unavailable.
  • Encoding: SDK source samples are CP1251. New project files should be UTF-8.
  • COM lifetime: release COM objects (Marshal.ReleaseComObject) / scope them; a leaked reference keeps the КОМПАС process alive.
  • API choice: prefer API7 for new tool implementations; drop to API5 only for things API7 doesn't expose.