28 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:
- SDK knowledge base in this repo:
docs/Kompas3D_SDK/— clean Markdown, one article per COM interface, with YAML tags; search it with Grep/Read (see below). Committed to the repo (canonical), distilled from the КОМПАС SDK help. Prefer this over the web. For non-trivial lookups, delegate to thekompas-sdk-researchskill (Sonnet subagent) to save context. - 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 (docs/Kompas3D_SDK/)
docs/Kompas3D_SDK/ is a structured MD knowledge base distilled from the 26 000-page Help&Manual WebHelp export. One article per COM interface/topic, split into interfaces/, enums/, structures/, guides/ (+ resources/ images), each with YAML frontmatter (type, api, domain, tags, sources); methods/properties are ## headings inside the interface article. Search it directly — do not browse the raw HTML:
- Grep over
docs/Kompas3D_SDK/for an interface/method/property name or Russian keyword (method names are## SetSideParam - …headings, so the name lands you in the right article). - Read the matching
*.md— the interface article holds all its members,Синтаксис Automation:/Синтаксис COM:blocks (in code fences), parameters, notes. docs/Kompas3D_SDK/index.md— table of contents by category. Filter by frontmatter tags, e.g.Grep "type: enum"orGrep "domain: \[.*3d".
The base is committed to the repo (canonical) — no regeneration step. It covers the COM API7/API5 reference this project uses (interfaces named iapplication_*, idocuments_*, …). The cross-platform Qt/C++ KsAPI flavour (ksapi_*, non-COM binding) is intentionally excluded from the base — ignore unless explicitly working with KsAPI.
Current state
v1 + v2 + STEP/assembly + direct B-rep edit + structural model inspection implemented and working (full sketch→feature→inspect→STEP round-trip + move_face + describe_model validated end-to-end). Stack:
.NET 8 (net8.0-windows, x64), C#, MCP via the official ModelContextProtocol SDK over stdio.
70 MCP tools, 119 tests green (69 unit + 50 integration). v2 added: sketch-on-face (by point and by index), revolve (boss/cut + sketch axis), fillet/chamfer (edge-by-point and by index), and Query tools get_part_info (МЦХ), get_bounding_box, list_faces, list_edges. After v2: import_step, export_step (ConversionService, ConversionTools), list_components (assembly traversal via TopPart → IParts7). move_face (FaceEditService, EditTools) — direct B-rep face editing. After move_face: structural model inspection — describe_model, list_features, list_bodies, list_variables, describe_face, describe_edge, measure (ModelInspectionService, InspectionTools). describe_model is the preferred first call over model_snapshot (no token cost for image context; gives feature tree, bodies, variables, topology summary, МЦХ). Package A «richer sketches»: 7 new sketch primitives — sketch_add_arc, sketch_add_arc_3points, sketch_add_ellipse, sketch_add_polyline, sketch_add_polygon, sketch_add_spline, sketch_add_point. PartModeler refactored into partial classes: PartModeler.cs (core), PartModeler.Sketch.cs (2D primitives), PartModeler.Features.cs (extrude/revolve/fillet/chamfer). Static SketchGeometry class in Core/Modeling. Package B «forming ops» complete: shell (оболочка, o3d_shellOperation=43) + rib (ребро жёсткости, o3d_ribOperation=44) + sweep (кинематическая операция, o3d_baseEvolution=45) + loft (по сечениям, o3d_baseLoft=30). Auxiliary geometry (start of package E): sketch_create_on_offset_plane (смещённая плоскость, o3d_planeOffset=14) — unlocked loft. Additional Edit tools: split_solid_by_plane, move_body, boolean_union. Package C «patterns & mirror» complete: linear_pattern (линейный массив, o3d_meshCopy=35) + circular_pattern (круговой массив, o3d_circularCopy=36) + mirror_operation (зеркальная копия операций, o3d_mirrorOperation=48) + mirror_body (зеркало тела, o3d_mirrorAllOperation=49). hole (HoleService, FeatureTools) — цилиндрическое отверстие (сквозное или глухое) через API7 (IModelContainer/IHole3D/IHoleDisposal); первая формообразующая операция на API7 (прецедент ранее только у move_face). hole_counterbore — отверстие с цековкой (ksHTCounterbore, ISpotfacingHoleParameters). hole_countersink — отверстие с зенковкой (ksHTCountersinking, ICountersinkHoleParameters). hole_conic — коническое отверстие (ksHTConic, IConicHoleParameters: ConicType=ksCNAngle, ConicAngle); завершает набор типов отверстий. HoleCore рефакторен: принимает ksHoleTypeEnum holeType + Action<IHole3D> configure (настройка HoleParameters после установки HoleType, т.к. параметрический подынтерфейс недоступен до фиксации типа). Базовый hole = ksHTBase + configure=null. draft (уклон, o3d_incline=42) — наклон граней на угол относительно нейтральной координатной плоскости; реализован через API5 ksInclineDefinition (операция называется Incline в API5, не Draft). Package D «parametrics» started: create_variable, set_variable, delete_variable (VariableService, VariableTools) — CRUD переменных модели через API5. list_variables исправлен (читает ksPart.GetFeature().VariableCollection, а не ksPart.VariableCollection()). Ограничение: переменная управляет геометрией только в параметрической модели (где размеры эскиза связаны с именем переменной); наши эскизы строятся литеральными координатами → set_variable хранит/вычисляет значение, но геометрию не меняет. Связь эскизных размеров с переменными (API2D) — не реализована.
See README.md and docs/ARCHITECTURE.md; design decisions/caveats in
docs/OPEN_QUESTIONS.md.
Principle: MCP = translating SDK capabilities into general tools (not task-specific). On top of MCP — skill .claude/skills/kompas-3d/ with a methodology (playbooks, heuristics, validated in usecases/). Layout: usecases/ (in .gitignore) is the proving ground; proven techniques are promoted to the skill.
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.props → KompasInteropDir).
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.5→KompasObject) thenksGetApplication7()→IApplication; the API5 root is needed forksPart3D-building andksDocument3Dsnapshots. - 3D is built via API5
ksPart(NewEntity(o3d_sketch/o3d_bossExtrusion/o3d_bossRotated/o3d_fillet/o3d_chamfer/o3d_shellOperation=43/o3d_ribOperation=44/o3d_baseEvolution=45/...),ksBossExtrusionDefinition/ksCutExtrusionDefinition/ksBossRotatedDefinition/ksFilletDefinition/ksChamferDefinition/ksShellDefinition/ksRibDefinition/ksBaseEvolutionDefinition); cut-through holes usedtBoth+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, thenGetByIndex(0); or by stable index fromlist_faces/list_edges.ksFaceDefinition.IsPlanar/IsCylinder/...+GetArea(ST_MIX_MM)classify faces.ksEdgeDefinition.IsLineSeg/IsCircle/IsArc/...+GetLength()classify/measure edges. Sketch axis = line with system style 3 (осевая). Fillet/chamfer by edge index viafillet_edge_index/chamfer_edge_index(more reliable than by-point). - МЦХ / 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 API7IMassInertiaParam7.Calculate()— itsActualflag 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-memoryresultArrayBytesstays empty when a filename is given); read bytes back. Return to MCP viaImageContentBlock.FromBytes(bytes, mime)— notData = bytes(Data holds base64 bytes). Usemodel_snapshotonly for visually-spatial questions; preferdescribe_modelfirst. - Logs go to stderr (stdout is the MCP channel). Integration tests reuse one КОМПАС via
KompasFixture; artifacts land in gitignored.scratch/. - Structural model inspection (
ModelInspectionService,InspectionTools):describe_model— one-call structural "passport" (bounding box + МЦХ + bodies + topology summary + feature tree + variables); preferred over snapshot.list_features— feature tree with params (depth/radius/legs).list_bodies— list solid/surface bodies with face count.list_variables— model variables (name/expression/value, external/info flags); reads viaksPart.GetFeature().VariableCollection(all variables, including user-created) with fallback toksPart.VariableCollection()(external-only — bug was fixed).describe_face— drill-down by index (type, area, normal, radius, edge count).describe_edge— drill-down by index (type, length, adjacent faces, vertices).measure— distance/angle between two objects (face|edge|vertex by index, unitST_MIX_MM). - Variable management (package D start,
VariableService,VariableTools):create_variable(name, value, note?, external?)— creates a model variable;set_variable(name, expression)— sets expression (constant"30"or formula"width*2+5");delete_variable(name)— deletes (fails if dependents exist). Key API facts (don't relearn): variable creation MUST useksPart.GetFeature().VariableCollection(property on root ksFeature) — NOTksPart.VariableCollection()(returns external-only). Expression is the leading field; value is derived. Changes applied viaksPart.RebuildModel()(return checked); after rebuild the RCW variable is stale → re-read via fresh collection (ReadValueFresh). Dependent variables recalculate automatically. Deletion fails if dependents exist (RemoveVariable returns FALSE). Geometry limitation: variables control geometry only in a parametric model where sketch dimensions are linked to variable names; our sketches are built with literal coordinates →set_variablestores/computes the value but does NOT change geometry. Linking sketch dimensions to variables (parametric sketches via API2D) is not yet implemented. - Feature tree API (don't relearn): read via API5
ksPart.GetFeature()→(ksFeature).SubFeatureCollection(true,false)→ksFeatureCollection. Cast(ksFeature)partdoes NOT work (RCW QI returns null) — must useGetFeature().ksFeature.typereturns only coarseo3d_entityand does NOT distinguish operations; precise type and params come fromksFeature.GetObject()→ksEntity.GetDefinition()and matching definition type (ksBossExtrusionDefinition.GetSideParam,ksFilletDefinition.radius,ksChamferDefinition.GetChamferParam, …). Node name ("Элемент выдавливания:1", "Скругление:1") is localized by КОМПАС itself. - STEP import/export,
list_components,move_face,split_solid_by_plane,move_body,boolean_union, full inspection layer, richer sketch primitives (package A),shell,rib,sweep,loft(package B complete),sketch_create_on_offset_plane(package E start),linear_pattern,circular_pattern,mirror_operation,mirror_body(package C complete),hole,hole_counterbore,hole_countersink,hole_conic(all API7 viaHoleService;hole_conicusesksHTConic/IConicHoleParameters),draft(API5ksInclineDefinition),create_variable/set_variable/delete_variable(package D start) are done. Not yet done: parametric sketches — investigated, unavailable via COM API (ksCDimWithVariablecannot be constructed from external automation; seedocs/superpowers/specs/2026-05-27-parametric-sketch-findings.md); 2D drawing, assembly building; package E continuation (axis, angle plane). Known caveat: boss/cut direction on a selected face depends on face-normal orientation (forwardmay need flipping — agent picks via snapshot ordescribe_facenormal). Seedocs/OPEN_QUESTIONS.md→ «Ревью v2». - "STEP import without history" detected structurally:
bodyCount > 0 && no formative features && features.Count <= bodyCount+1(only origin + body). STEP with edits (move_face: "Смещённая плоскость", "Разрезать", "Переместить грани", "Булева операция") — that already has history. - Topology/measure API:
ksFaceDefinition.EdgeCollection/GetCylinderParam/GetSurface().GetNormal+normalOrientation;ksEdgeDefinition.GetAdjacentFace(bool)/GetVertex(bool)→ksVertexDefinition.GetPoint; bodies viaksPart.BodyCollection()→ksBody(IsSolid/FaceCollection); all variables viaksPart.GetFeature().VariableCollection→ksVariable(external-only:ksPart.VariableCollection()— do NOT use for reading all variables); measurements viaksPart.GetMeasurer()→ksMeasurer(SetObject1/2,unit=ST_MIX_MM,Calc,distance/MinDistance/anglein degrees /IsAngleValid). - STEP import COM pattern (verified):
IApplication.get_Converter((object)(int)ksConverterFromSTEP=-3)(pass format code, not DLL path) →IConverter.ConverterParameters(cmd)→ setIAdditionConvertParameters.Format=ksConverterFromSTEP→IKompasDocument3D1.ConvertFromAdditionFormat(path, prm). Export:ConvertToAdditionFormatwith format codes for AP203/AP214/AP242. Param co-classes (AdditionConvertParameters etc.) are NOT CoCreatable — only via converter factories. Assembly traversal:IKompasDocument3D.TopPart → IPart7.Parts (IParts7). Extract component:prm.NeedCreateComponentsFiles=true(writes .m3d files next to STEP) +IPart7.OpenSourceDocument. - Direct B-rep face editing (
move_face) (verified on top_spacer, 39.45→41.45 mm height): API7 face object retrieved viaIPart7.FindObjectsByPoint(x,y,z,true)→ cast toKompasAPI7.IFace; containers acquired at runtime via COM-QI:(ISurfaceContainer)part,(IModelContainer)part;FaceMover(SetFaces + Offset + Direction + Update) moves the face. distance>0 = outward (add material), <0 = inward. Works on both parametric and imported B-rep geometry. Full split-reposition workflow (SplitSolids/BodyRepositions) is driveable but not yet exposed as tools. - Shell operation (
shell, package B):ksShellDefinitionviaksPart.NewEntity(o3d_shellOperation=43);thickness(mm) +thinType(bool:true=inward/false=outward; mapping:thinType = !outward) +FaceArray()(open faces, ≥1, by index fromlist_faces). HelperSelectFaceByIndexinPartModeler.cs(analogous toSelectEdgeByIndex, with range check). Validation:thickness>0, dedup viaDistinct, range check before mutation. Transient RCWs inShellAsync/SelectFaceByIndexare intentionally not released (consistent with Fillet/Chamfer pattern). - Rib operation (
rib, package B):ksRibDefinitionviaksPart.NewEntity(o3d_ribOperation=44). Params:sketchId,thickness(mm),side(left|right|up|down→ 0/1/2/3 viaSketchGeometry.RibSide()),symmetric(bool),angle(°).SetSketch(sketch)→ setindex=0,angle,side;SetThinParam(dtBoth, t/2, t/2)whensymmetric=true, elseSetThinParam(dtNormal, t, 0). Empirical: the rib contour must float in the gap (not touch the body at endpoints) — КОМПАС extends the web to the body automatically. - Sweep operation (
sweep, package B):ksBaseEvolutionDefinitionviaksPart.NewEntity(o3d_baseEvolution=45). Params:profileSketchId(closed profile sketch),pathSketchId(open/closed path sketch on a different plane, typically perpendicular).SetSketch(profile)→PathPartArray().Add(path)→sketchShiftType=0→SetThinParam(false)→Create(). Validation:profileSketchId != pathSketchId. Profile and path must be on different (usually perpendicular) planes. - Offset plane (
sketch_create_on_offset_plane, package E start):OpenSketchOnOffsetPlaneAsyncinPartModeler.Sketch.cs.ksPart.NewEntity(o3d_planeOffset=14)→ksPlaneOffsetDefinition(SetPlane(basePlane)+offsetmm +direction) →Create()→ sketch on that plane. Used to place sketches at arbitrary heights — enablesloftwith parallel sections.entity.Create()result is checked (reliability fix applied to allCreateSketchOn*paths). - Loft operation (
loft, package B):ksBaseLoftDefinitionviaksPart.NewEntity(o3d_baseLoft=30). Params:sketchIds[](≥2 closed profile sketches on different parallel planes).Sketchs().Add(each sketch)→SetLoftParam(closed=false, false, true)→SetThinParam(false)→Create(). Requires parallel section sketches at different heights — usesketch_create_on_offset_planefor the non-base sections. - Patterns & mirror (package C):
linear_pattern—ksMeshCopyDefinitionviaksPart.NewEntity(o3d_meshCopy=35);SetAxis1(axis)+SetCopyParamAlongAxis(true,0,count,step,false)+count2=1(disables 2nd direction → 1D linear); features added viaOperationArray()(no Get).circular_pattern—ksCircularCopyDefinitionviaNewEntity(o3d_circularCopy=36);SetAxis(axis); properties set directly:count1=1(radial off),count2=count(ring),step2=angle°between neighbours,factor2=false,inverce=reverse;GetOperationArray().Add(feature).mirror_operation—ksMirrorCopyDefinitionviaNewEntity(o3d_mirrorOperation=48);SetPlane(basePlane)+GetOperationArray().Add(feature).mirror_body—ksMirrorCopyAllDefinitionviaNewEntity(o3d_mirrorAllOperation=49);SetPlane(basePlane);ChooseBodies()does NOT cast toksChooseBodies(returns null) and is not needed —o3d_mirrorAllOperationmirrors all bodies keeping the original (volume doubles). Source features retrieved by id from_featuresregistry via new privateRequireFeaturehelper (analogous toRequireSketch). Newsrc/Kompas.Mcp.Core/Modeling/CoordinateAxis.cs— enumCoordinateAxis {X,Y,Z}+CoordinateAxes.ToObj3dType/Parse(→o3d_axisOX/OY/OZ = 71/72/73), analogous toBasePlane.cs.SketchGeometry.RequireMin(int value, int min, string paramName)— validator forcount>=2. Empirical:countincludes the original instance (count=3 → 3 bodies);count2=1disables 2nd direction for linear;step2is angle° between neighbours for circular. - Hole operations (
hole,hole_counterbore,hole_countersink,hole_conic): all implemented via API7 (not API5 —ksHoleDefinitionabsent in interop). Servicesrc/Kompas.Mcp.Core/Modeling/HoleService.cs.HoleCorehelper is parameterised withksHoleTypeEnum holeType+Action<IHole3D> configurecallback (configure setsHoleParametersafterHoleTypeis assigned, because the type-specific sub-interface — e.g.ISpotfacingHoleParameters— is not accessible until the type is fixed). Basehole=ksHTBase+configure=null.hole_counterbore:ksHTCounterbore+ configure sets(ISpotfacingHoleParameters)hole.HoleParameters(SpotfacingDiameter,SpotfacingDepth); validatesspotDiameter>diameteranddepth>spotDepthfor blind.hole_countersink:ksHTCountersinking+ configure sets(ICountersinkHoleParameters)hole.HoleParameters(CountersinkType=ksCTDiameterAngle,CountersinkDiameter,CountersinkAngle); validatessinkDiameter>diameter,0<sinkAngle<180.hole_conic:ksHTConic+ configure sets(IConicHoleParameters)hole.HoleParameters(ConicType=ksCNAngle,ConicAngle); validates0<conicAngle<180. All four share common placement logic (IHoleDisposal+Points3D, direction selection by volume delta, orphan rollback). None enters the_featuresAPI5 registry → no id returned. - Draft operation (
draft): implemented via API5ksInclineDefinition(operation name in API5 is "Incline", not "Draft" — do NOT search for "Draft" in API5 docs).ksPart.NewEntity(o3d_incline=42)→GetDefinition() as ksInclineDefinition→FaceArray()(add faces by index viaSelectFaceByIndex, range-checked before mutation) →SetPlane(basePlane)→angle(degrees) →direction→Create()→ register in_features. Empirical:direction=false=expanding (outward, adds material),direction=true=tapering (inward) — opposite to the SDK docs → mapping in code:def.direction = !outward. Neutral plane set viaSetPlane(base coordinate plane). Angle validation:RequireDraftAngle(0<angle<90, double.IsFinite). Returns feature id (registered in_features→ patterns/mirror from package C apply). Note:o3d_DraftFromEdges=644/IDraftFromEdgesis a different "draft from edge baseline" operation — not used here. - Richer sketch primitives (package A, ksDocument2D API5 wrappers):
ksArcBy3Points(3-point arc),ksArcByAngle(centre/radius/start-end angles in degrees, counterClockwise flag),ksEllipseviaksEllipseParam— struct obtained viaKompasObject.GetParamStruct(ko_EllipseParam=22); property names areA/B(uppercase) in the interop;ksRegularPolygonviaksRegularPolygonParam(ko_RegularPolygonParam=92) —describe = !inscribed; NURBS spline viaksNurbs(order=4)+ksNurbsPointloop +ksEndObj;ksPoint. Param structs are released after use.PartModelersplit into partial classes:PartModeler.cs(registry/helpers/NewParam/reset),PartModeler.Sketch.cs(all 2D primitives),PartModeler.Features.cs(extrude/revolve/fillet/chamfer). StaticSketchGeometryclass (Core/Modeling) holds enum mappings (ArcDirection,PolygonDescribe) and validators (RequirePositive,RequireVertexCount,RequirePoints). Polyline/spline point lists userecord SketchPoint(X, Y)with JSON namesx/y.
КОМПАС-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)
- Get the КОМПАС root object by COM ProgID. Verified on this machine (v24 Home):
KOMPAS.Application.7andKOMPAS.Application.5are registered;KOMPASLT.*is absent — the Home edition uses the regular (non-LT) ProgIDs. Resolution order:KOMPAS.Application.7— direct API7IApplication(preferred)KOMPAS.Application.5— API5KompasObject, thenksGetApplication7()KOMPASLT.Application.5— fallback for other installations- New instance:
Activator.CreateInstance(Type.GetTypeFromProgID(progId)) - Attach to a running instance:
Marshal.GetActiveObject(progId)
- If you entered via API5, obtain the modern application:
IApplication appl = (IApplication)kompas.ksGetApplication7();(viaKOMPAS.Application.7you already holdIApplication). - Set
appl.Visible = trueto 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.afor 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, plusHelp\С чего начать.pdfand a Linux/Debian 12 build guide.Samples\— zipped examples per language:CSharp.zip,C++.zip,Pascal.zip,Basic.zip. InsideCSharp.zip, theStep1…Step12andStep2_API7_2D/Step2_API7_3Dprojects are the progressive tutorial;Gayka,SlideWrk,EventsAutoare larger feature demos.Help\KOMPAS_SDK_ru-RU.zipandKsAPI\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.