diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e767dff..708fa134 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Sketch essentials** (queue item 32): six sketch tools agents reach + for next, 151 tools in all. `add_sketch_fillet` and `add_sketch_chamfer` + round or bevel corners picked by their points (a rectangle's corners have + no ids of their own); `add_slot` draws a straight or arc slot and gives + its area; `sketch_trim` and `sketch_extend` cut back or lengthen an entity + at a point; `set_construction_geometry` makes entities construction + geometry, or normal again, by id. `add_arc` takes `kind` (`center`, + `three_point`, `tangent`) and `add_rectangle` takes `from_center`. Demo: + a slotted bracket plate, on the demos page. - **Equations and global variables** (queue item 29): `list_equations`, `set_equation` and `delete_equation`. One value (`"Width" = 60mm`) can drive several dimensions (`"D1@Sketch1" = "Width" / 2`); `set_equation` @@ -219,6 +228,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`construction` is honoured on SolidWorks**: `add_line`, `add_circle` + and `add_rectangle` accepted `construction` but drew normal geometry, while + the reply said `"construction": true`. The tools now set it on the new + entity. - **`create_cut_extrude` with `both_directions` on a Blind cut** cut one way only, so a slot meant to straddle its sketch plane came out beside it. It is now a mid-plane cut, `depth` in total, as `create_extrusion` does. diff --git a/README.md b/README.md index 0e403a90..78ee9960 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![SolidWorks](https://img.shields.io/badge/tested%20on-SolidWorks%202026-red)](https://www.solidworks.com/) [![Coverage](https://codecov.io/gh/andrewbartels1/SolidworksMCP-python/branch/main/graph/badge.svg)](https://codecov.io/gh/andrewbartels1/SolidworksMCP-python) -Python MCP server for SolidWorks automation with 145 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 151 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. [![115 MCP tools by support level (the 8 deprecated ones not counted), and how much of the core SolidWorks COM API they reach](docs/assets/progress/progress.svg)](https://andrewbartels1.com/SolidworksMCP-python/progress/) @@ -367,7 +367,7 @@ It works only with the circuit-breaker adapter wrapper (the default for real Sol ### A shorter tool list -All 145 tools cost about 59,000 tokens a turn. `SOLIDWORKS_MCP_TOOL_MODE=search` lists four instead (about 900 tokens); `SOLIDWORKS_MCP_TOOLSETS=core,drawing` lists only those groups. See [Choose which tools a client sees](https://andrewbartels1.com/SolidworksMCP-python/getting-started/installation/#4-choose-which-tools-a-client-sees). +All 151 tools cost about 63,000 tokens a turn. `SOLIDWORKS_MCP_TOOL_MODE=search` lists four instead (about 900 tokens); `SOLIDWORKS_MCP_TOOLSETS=core,drawing` lists only those groups. See [Choose which tools a client sees](https://andrewbartels1.com/SolidworksMCP-python/getting-started/installation/#4-choose-which-tools-a-client-sees). ## Teach your agent the workflow diff --git a/docs/assets/demos/sketch-essentials/test_a_slotted_bracket_plate-motion.gif b/docs/assets/demos/sketch-essentials/test_a_slotted_bracket_plate-motion.gif new file mode 100644 index 00000000..558b3ced Binary files /dev/null and b/docs/assets/demos/sketch-essentials/test_a_slotted_bracket_plate-motion.gif differ diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index 7d398c70..4be4322f 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,8 +1,8 @@ { "tools": { - "total": 145, + "total": 151, "by_level": { - "stable": 137, + "stable": 143, "beta": 0, "experimental": 0, "planned": 0, @@ -28,7 +28,7 @@ "family": "sketching", "level": "stable", "reason": "", - "summary": "Draw a circular arc in the open sketch from its centre, start point and end point, in mm." + "summary": "Draw a circular arc in the open sketch: from its centre, through three points, or tangent." }, { "name": "add_centerline", @@ -149,6 +149,13 @@ "reason": "", "summary": "Draw a closed, axis-aligned rectangle in the open sketch from two opposite corners, in mm." }, + { + "name": "add_sketch_chamfer", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Bevel corners of the open sketch, picking each corner by its point." + }, { "name": "add_sketch_constraint", "family": "sketching", @@ -163,6 +170,13 @@ "reason": "", "summary": "Add a driving dimension to sketch entities: linear, angular, radial, diameter or an ellipse axis." }, + { + "name": "add_sketch_fillet", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Round corners of the open sketch to a radius, picking each corner by its point." + }, { "name": "add_sketch_text", "family": "sketching", @@ -170,6 +184,13 @@ "reason": "", "summary": "Write text in the open sketch, at a point or centred on one, to deboss or emboss it." }, + { + "name": "add_slot", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Draw a slot in the open sketch: straight between two centres, or along an arc." + }, { "name": "add_spline", "family": "sketching", @@ -891,6 +912,13 @@ "reason": "", "summary": "Fix or float a component of the active assembly, or make a sub-assembly rigid or flexible." }, + { + "name": "set_construction_geometry", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Make sketch entities construction geometry, or normal again, by id." + }, { "name": "set_custom_property", "family": "engineering_data", @@ -961,6 +989,13 @@ "reason": "", "summary": "Copy model edges, or a face's whole outline, into the open sketch (Convert Entities)." }, + { + "name": "sketch_extend", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Lengthen a sketch entity from its end nearest a point until it meets the next entity." + }, { "name": "sketch_linear_pattern", "family": "sketching", @@ -982,6 +1017,13 @@ "reason": "", "summary": "Offset sketch entities by a distance in mm, outward or inward, e.g. for a wall or a clearance." }, + { + "name": "sketch_trim", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Trim away the piece of a sketch entity at a point, back to where it meets others." + }, { "name": "sketch_tutorial_simple_hole", "family": "sketching", @@ -1029,11 +1071,11 @@ "com": { "type_library": "83A33D31-27C5-11CE-BFD4-00400513BB57x0x34x0", "core": { - "covered": 255, + "covered": 266, "total": 2838 }, "api": { - "covered": 298, + "covered": 308, "total": 5985 }, "interfaces": [ @@ -1078,6 +1120,7 @@ "AddRelation", "AddVerticalDimension2", "ClearSelection2", + "Create3PointArc", "CreateArc", "CreateCenterLine", "CreateCircleByRadius", @@ -1086,6 +1129,7 @@ "CreateLine", "CreateLinearSketchStepAndRepeat", "CreatePoint", + "CreateTangentArc", "DeleteConfiguration2", "EditDelete", "EditRebuild3", @@ -1147,6 +1191,7 @@ "SketchAddConstraints", "SketchMirror", "SketchOffset2", + "SketchTrim", "SketchUseEdge", "ViewZoomtofit", "ViewZoomtofit2" @@ -1270,19 +1315,27 @@ { "name": "ISketchManager", "covered": [ + "Create3PointArc", "CreateArc", "CreateCenterLine", + "CreateCenterRectangle", + "CreateChamfer", "CreateCircleByRadius", "CreateCircularSketchStepAndRepeat", "CreateCornerRectangle", "CreateEllipse", + "CreateFillet", "CreateLine", "CreateLinearSketchStepAndRepeat", "CreatePoint", "CreatePolygon", + "CreateSketchSlot", "CreateSpline2", + "CreateTangentArc", "InsertSketch", + "SketchExtend", "SketchOffset2", + "SketchTrim", "SketchUseEdge", "SketchUseEdge3" ], diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index a6383ccf..57862d4b 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,7 +21,7 @@ -MCP tools: 137 +MCP tools: 143 100% work on SolidWorks today @@ -33,7 +33,7 @@ -stable 137 +stable 143 beta 0 @@ -43,13 +43,13 @@ deprecated 8 Core SolidWorks COM API (12 interfaces) -255 of 2,838 methods ยท 9.0% +266 of 2,838 methods ยท 9.4% - - - + + + -Whole API: 298 of 5,985 method names (5.0%), counted by a text scan of the adapters. +Whole API: 308 of 5,985 method names (5.1%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index 023369c2..31159b5c 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -4,7 +4,7 @@ activate_configurationfile_managementstableMake a configuration of the active model the active one, and rebuild. activate_documentfile_managementstableMake an already-open document the active one, so the next tools act on it. -add_arcsketchingstableDraw a circular arc in the open sketch from its centre, start point and end point, in mm. +add_arcsketchingstableDraw a circular arc in the open sketch: from its centre, through three points, or tangent. add_centerlinesketchingstableDraw a centreline (construction line) in the open sketch, in mm. add_chamfermodelingstableBevel edges of the active part with a chamfer: `distance` along one face at `angle` (45 by default). add_circlesketchingstableDraw a circle in the open sketch from its centre and radius, in mm. @@ -22,9 +22,12 @@ add_notedrawingstablePlace a text note on the active drawing sheet at a position in millimetres. add_polygonsketchingstableDraw a regular polygon (e.g. a hexagon) in the open sketch from its centre, radius and number of sides. add_rectanglesketchingstableDraw a closed, axis-aligned rectangle in the open sketch from two opposite corners, in mm. +add_sketch_chamfersketchingstableBevel corners of the open sketch, picking each corner by its point. add_sketch_constraintsketchingstableAdd a geometric relation between sketch entities: horizontal, vertical, parallel, perpendicular, tangent, coincident, concentric, equal, symmetric, collinear or fix. add_sketch_dimensionsketchingstableAdd a driving dimension to sketch entities: linear, angular, radial, diameter or an ellipse axis. +add_sketch_filletsketchingstableRound corners of the open sketch to a radius, picking each corner by its point. add_sketch_textsketchingstableWrite text in the open sketch, at a point or centred on one, to deboss or emboss it. +add_slotsketchingstableDraw a slot in the open sketch: straight between two centres, or along an arc. add_splinesketchingstableDraw a smooth spline through a list of points in the open sketch, in mm. arrange_dimensionsdrawing_automationstableMove drawing dimensions out of their views into tidy rows so nothing overlaps, then check the sheet. auto_center_marksdrawingstableInsert centre marks on the holes, slots and (optionally) fillets of one drawing view. @@ -128,6 +131,7 @@ select_face_edgesmodelingstableSelect every edge of one face of the active part, ready for `add_fillet` or `add_chamfer` with no edge names. select_featuremodelingstableSelect a feature, sketch, plane or component by name in the active document. set_component_statemodelingstableFix or float a component of the active assembly, or make a sub-assembly rigid or flexible. +set_construction_geometrysketchingstableMake sketch entities construction geometry, or normal again, by id. set_custom_propertyengineering_datastableCreate or overwrite one text custom property on the active document, e.g. PartNo or DrawnBy. set_dimensionmodelingstableChange one length dimension of the active model, in mm, and rebuild. set_equationequationsstableAdd or change an equation or global variable, so one value drives others (a parametric part). @@ -138,9 +142,11 @@ set_unitsmodelingstableSet the active document's length units: mm, cm, m, in or ft. sketch_circular_patternsketchingstableRepeat sketch entities around the sketch origin, e.g. a bolt circle. sketch_convert_entitiessketchingstableCopy model edges, or a face's whole outline, into the open sketch (Convert Entities). +sketch_extendsketchingstableLengthen a sketch entity from its end nearest a point until it meets the next entity. sketch_linear_patternsketchingstableRepeat sketch entities in a straight line at a fixed spacing. sketch_mirrorsketchingstableMirror sketch entities about a centreline in the open sketch. sketch_offsetsketchingstableOffset sketch entities by a distance in mm, outward or inward, e.g. for a wall or a clearance. +sketch_trimsketchingstableTrim away the piece of a sketch entity at a point, back to where it meets others. sketch_tutorial_simple_holesketchingdeprecated
no replacement.Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch. suppress_featuremodelingstableSuppress or unsuppress a feature of the active model; suppressed features stay in the tree but are not built. undomodelingstableUndo the last operations in the active model (Edit > Undo). @@ -156,13 +162,13 @@ InterfaceMethods calledOfCalled ISldWorks23330
7.0%ActivateDoc3, CloseDoc, Frame, GetConfigurationNames, GetCurrentLanguage, GetDocuments, GetExecutablePath, GetExportFileData, GetMassProperties, GetMathUtility, GetOpenDocumentByName, GetProcessID, GetUserPreferenceStringValue, GetUserPreferenceToggle, NewAssembly, NewDocument, NewDrawing2, NewPart, OpenDoc6, RevisionNumber, RunMacro2, SetUserPreferenceIntegerValue, SetUserPreferenceToggle
-IModelDoc281758
10.7%AddConfiguration2, AddDiameterDimension2, AddDimension, AddDimension2, AddHorizontalDimension2, AddRadialDimension2, AddRelation, AddVerticalDimension2, ClearSelection2, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, DeleteConfiguration2, EditDelete, EditRebuild3, EditSketch, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetEquationMgr, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertSketch, InsertSketchForEdgeFlange, InsertSketchText, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
+IModelDoc284758
11.1%AddConfiguration2, AddDiameterDimension2, AddDimension, AddDimension2, AddHorizontalDimension2, AddRadialDimension2, AddRelation, AddVerticalDimension2, ClearSelection2, Create3PointArc, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreateTangentArc, DeleteConfiguration2, EditDelete, EditRebuild3, EditSketch, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetEquationMgr, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertSketch, InsertSketchForEdgeFlange, InsertSketchText, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchTrim, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
IModelDocExtension18337
5.3%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetMassProperties, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, SaveAs, SaveAs2, SaveAs3, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
IPartDoc12167
7.2%ExportToDWG2, FeatureByName, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureRevolve2, FirstFeature, GetBodies2, GetMaterialPropertyName2, GetPartBox, InsertMirrorFeature, SetMaterialPropertyName2
IAssemblyDoc11198
5.6%AddComponent4, AddComponent5, AddMate5, CompConfigProperties5, FeatureByName, FixComponent, GetBox, GetComponentByName, GetComponentCount, GetComponents, UnfixComponent
IDrawingDoc16272
5.9%ActivateView, AutoDimension, Create1stAngleViews2, Create3rdAngleViews2, CreateDetailViewAt4, CreateDrawViewFromModelView3, CreateSectionViewAt5, EditSheet, EditSketch, EditTemplate, FeatureByName, GetCurrentSheet, GetFirstView, GetViews, InsertModelAnnotations3, SetupSheet5
IFeatureManager27268
10.1%CreateCustomBendAllowance, CreateDefinition, CreateFeature, CreateSaveBodyFeature, FeatureCircularPattern5, FeatureCut3, FeatureCut4, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureFillet3, FeatureLinearPattern5, FeatureRevolve2, GetFeatureCount, GetFlatPatternFolder, HoleWizard5, InsertCosmeticThread3, InsertFeatureChamfer, InsertMirrorFeature, InsertMultiFaceDraft, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRefPlane, InsertReferencePoint, InsertRib, InsertSheetMetalBaseFlange2, InsertSheetMetalEdgeFlange2
-ISketchManager1583
18.1%CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateCornerRectangle, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreatePolygon, CreateSpline2, InsertSketch, SketchOffset2, SketchUseEdge, SketchUseEdge3
+ISketchManager2383
27.7%Create3PointArc, CreateArc, CreateCenterLine, CreateCenterRectangle, CreateChamfer, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateCornerRectangle, CreateEllipse, CreateFillet, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreatePolygon, CreateSketchSlot, CreateSpline2, CreateTangentArc, InsertSketch, SketchExtend, SketchOffset2, SketchTrim, SketchUseEdge, SketchUseEdge3
ISelectionMgr461
6.6%CreateSelectData, GetSelectedObject6, GetSelectedObjectCount2, GetSelectedObjectType3
IComponent220147
13.6%CustomPropertyManager, FeatureByName, FirstFeature, GetBodies2, GetBox, GetChildren, GetConfigurationNames, GetID, GetModelDoc2, GetPathName, GetSuppression2, GetType, GetXform, IsEnvelope, IsFixed, IsSuppressed, Select, Select2, Select4, SetSuppression2
IFeature22115
19.1%GetBox, GetChildren, GetDefinition, GetErrorCode2, GetFaces, GetFirstDisplayDimension, GetFirstSubFeature, GetID, GetNameForSelection, GetNextDisplayDimension, GetNextFeature, GetNextSubFeature, GetParents, GetSpecificFeature2, GetTypeName2, IsSuppressed, IsSuppressed2, ModifyDefinition, Parameter, Select, Select2, SetSuppression2
diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index ba7076cb..43b3ebb5 100644 --- a/docs/assets/progress/tool-list-size.md +++ b/docs/assets/progress/tool-list-size.md @@ -1,11 +1,11 @@ | `SOLIDWORKS_MCP_TOOLSETS` | `SOLIDWORKS_MCP_TOOL_MODE` | Tools listed | Size | Tokens (estimate) | Of the full list | | --- | --- | ---: | ---: | ---: | ---: | -| `all` | `list` | 145 | 235 KB | 60,126 | 100% | -| `core` | `list` | 105 | 159 KB | 40,683 | 68% | -| `drawing` | `list` | 21 | 38 KB | 9,616 | 16% | -| `automation` | `list` | 3 | 6 KB | 1,556 | 3% | +| `all` | `list` | 151 | 245 KB | 62,704 | 100% | +| `core` | `list` | 111 | 169 KB | 43,262 | 69% | +| `drawing` | `list` | 21 | 38 KB | 9,616 | 15% | +| `automation` | `list` | 3 | 6 KB | 1,556 | 2% | | `vba` | `list` | 10 | 17 KB | 4,356 | 7% | -| `docs` | `list` | 6 | 15 KB | 3,914 | 7% | -| `core,drawing` | `list` | 126 | 196 KB | 50,299 | 84% | -| `all` | `search` | 4 | 4 KB | 908 | 2% | -| `core` | `search` | 4 | 4 KB | 908 | 2% | +| `docs` | `list` | 6 | 15 KB | 3,914 | 6% | +| `core,drawing` | `list` | 132 | 207 KB | 52,877 | 84% | +| `all` | `search` | 4 | 4 KB | 908 | 1% | +| `core` | `search` | 4 | 4 KB | 908 | 1% | diff --git a/docs/demos.md b/docs/demos.md index 72c9ccac..6667c379 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -995,6 +995,53 @@ keeps its old text and the wrench stays at 19 mm. 11. `create_configuration({"name": "8 mm"})`, `set_equation({"name": "Size", "expression": "8mm", "configurations": ["8 mm"]})`, `activate_configuration({"name": "8 mm"})`, `verify_model`, `set_sketch_text` 12. `activate_configuration({"name": "Default"})`, `set_sketch_text`, then `set_equation({"name": "Size", "expression": "\"Nut\" * 2"})`, refused on purpose +## Sketching {#sketching} + +Source: [`tests/live/test_live_sw_sketch_essentials.py`](https://github.com/andrewbartels1/SolidworksMCP-python/blob/main/tests/live/test_live_sw_sketch_essentials.py). + +### A slotted bracket plate {#bracket-plate} + +![A bracket plate drawn from its centre, then a straight slot, an arc slot, a keyhole made by extending and trimming, and a window from a tangent and a three-point arc are cut; its corners are filleted and chamfered last](assets/demos/sketch-essentials/test_a_slotted_bracket_plate-motion.gif) + +> *Example prompt:* Make a 120 x 80 mm bracket plate, 8 mm thick, centred on +> the origin. Cut a straight adjustment slot and an arc slot, a keyhole, and +> a rounded window. Round the left corners R10 and chamfer the right ones +> 10 mm, as the last features. + +**What it shows.** Every new sketch operation in one part, with the +volume checked against the hand calculation after each step: + +| Step | Tools | Expected, mmยณ | Measured, mmยณ | +| --- | --- | --- | --- | +| A 120 x 80 plate drawn from its centre, extruded 8 mm | `add_rectangle` `from_center` | 76,800.00 | 76,800.00 | +| A straight slot and an arc slot, with two construction lines across them | `add_slot`, `add_line` `construction`, `set_construction_geometry` | 71,358.94 | 71,359.18 | +| A keyhole: two lines extended up to a circle, the arc between them trimmed, the neck's corners rounded and bevelled | `sketch_extend`, `sketch_trim`, `add_sketch_fillet`, `add_sketch_chamfer` | 68,938.11 | 68,938.53 | +| A window from a line, a tangent arc, a line and a three-point arc | `add_arc` `kind` | 65,909.79 | 65,910.22 | +| Last: two corners filleted R10, two chamfered 10 mm | `add_fillet`, `add_chamfer` | 64,766.42 | 64,766.85 | + +The plate is built sharp and its corners are treated last: fillets and +chamfers on a solid belong at the end of the feature tree, where a later cut +can't break them. The sketch fillet and chamfer round and bevel corners of a +2D outline, here the keyhole's neck. + +The construction lines cross both slots; had either been normal geometry, +the cut would have removed a different volume. The first call fails **on +purpose**: a rectangle drawn from its centre has a centre point, and a +fillet there is refused as `invalid_input` ("it isn't where two entities +meet"). + +**Tool calls** + +1. `create_part`, `create_sketch({"plane": "Top"})`, `add_rectangle({"x1": 0, "y1": 0, "x2": 60, "y2": 40, "from_center": true})` +2. `add_sketch_fillet({"corners": [[0, 0]], "radius": 5})`, refused on purpose +3. `exit_sketch`, `create_extrusion({"depth": 8})` +4. `add_slot({"start": [-40, -15], "end": [-40, 15], "width": 10})` and `add_slot({"kind": "arc", "center": [25, 0], "start": [39.142, -14.142], "end": [39.142, 14.142], "width": 8})` +5. `add_line({..., "construction": true})`, `add_line`, `set_construction_geometry({"entities": ["Line_4"]})`, then `create_cut_extrude({"end_condition": "ThroughAllBoth"})` +6. `add_circle`, three `add_line`, `sketch_extend({"point": [-3, -0.5]})` and at `[3, -0.5]`, `sketch_trim({"point": [0, 2]})`, `add_sketch_fillet({"corners": [[-3, -15]], "radius": 1.5})`, `add_sketch_chamfer({"corners": [[3, -15]], "distance": 1.5})`, cut through +7. `add_line`, `add_arc({"kind": "tangent", ...})`, `add_line`, `add_arc({"kind": "three_point", ..., "through_x": -25, "through_y": 30})`, cut through +8. `add_fillet({"radius": 10, "edge_names": [two corner edges]})`, `add_chamfer({"distance": 10, "edge_names": [two corner edges]})` +9. `verify_model({"volume_mm3": ...})` after each step + ## Run a demo yourself The demos need Windows, SolidWorks open and idle, and the project's `.venv`. diff --git a/docs/index.md b/docs/index.md index 0b990e1a..a626b6b4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -13,7 +13,7 @@ An MCP server that lets AI agents drive SolidWorks: describe a part, and the agent builds it with the server's 123 tools and checks what SolidWorks reports back. -๐Ÿš€ **145 Tools** | ๐Ÿค– **Agent-Ready Workflows** | โšก **Automatic COM/VBA Routing** | ๐Ÿงช **Schema-Validated Prompt Runs** +๐Ÿš€ **151 Tools** | ๐Ÿค– **Agent-Ready Workflows** | โšก **Automatic COM/VBA Routing** | ๐Ÿงช **Schema-Validated Prompt Runs** ## Overview @@ -43,7 +43,7 @@ The project emphasizes an inspect -> classify -> delegate loop instead of blind ### 2) Broad Tool Surface with Practical Coverage -- 145 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 151 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery - one server API surface for both simple operations and advanced workflows ### 3) Reliable Execution Path for Complex Operations diff --git a/docs/llms.txt b/docs/llms.txt index ac508eb1..981cc90f 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -36,7 +36,7 @@ ## Tool Catalog -- [Tool Catalog โ€” All 145 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **140 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. +- [Tool Catalog โ€” All 151 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **151 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. - [Modeling Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/modeling/): Create and manipulate SolidWorks parts, assemblies, and drawings. These are the foundational tools for any CAD workflow โ€” opening files, creating features (extrude, revolve), and querying/setting driven dimensions. - [Equation Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/equations/): Read, add, change and delete a part's or assembly's equations and global variables, so one value drives several dimensions and the model stays consistent when it changes. - [Sketching Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/sketching/): Build 2-D sketch geometry (lines, circles, arcs, splines, polygons) and apply geometric constraints and driven dimensions. Sketches are the prerequisite for every extrusion, revolve, sweep, and loft feature. diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index 8fd4ef6d..cb12986a 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,6 +1,6 @@ -# Tool Catalog โ€” All 145 Tools +# Tool Catalog โ€” All 151 Tools -This reference documents all **140 MCP tools** registered by the SolidWorks MCP server. +This reference documents all **151 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. ![Tool categories overview โ€” 109 tools across 12 functional areas](../../assets/images/tool-categories-overview.svg) @@ -11,7 +11,7 @@ Each section covers one functional category with parameter tables and copy-paste |----------|-------|-------------| | [Modeling Tools](modeling.md) | 42 | Parts, assemblies and drawings: extrusions, revolves, sweeps, lofts, cuts, Hole Wizard holes, cosmetic threads, shells, drafts, ribs, sheet metal (flanges, bends, the flat pattern), fillets, chamfers, patterns, reference geometry, mates, dimensions, feature renaming and the document unit system. | | [Equation Tools](equations.md) | 3 | Equations and global variables: one value driving several dimensions, in all configurations or chosen ones. | -| [Sketching Tools](sketching.md) | 21 | Sketches on a plane or a flat face: lines, circles, arcs, splines, polygons, text, relations, dimensions, offsets, mirrors and patterns. | +| [Sketching Tools](sketching.md) | 27 | Sketches on a plane or a flat face: lines, circles, arcs, slots, splines, polygons, text, fillets, chamfers, trim and extend, construction geometry, relations, dimensions, offsets, mirrors and patterns. | | [Drawing Tools](drawing.md) | 13 | Drawings from a model: standard, section and detail views, dimensions, notes, centre marks, the sheet format and title block, and a drawing check. | | [Drawing Analysis Tools](drawing-analysis.md) | 1 | Compare two versions of a drawing file. | | [Drawing Automation Tools](drawing-automation.md) | 7 | Model dimensions laid out without overlaps, datum tags, tolerances, BOM tables, sheet scale and complete A3 drawings. | diff --git a/docs/user-guide/tool-catalog/sketching.md b/docs/user-guide/tool-catalog/sketching.md index 4e063d8f..6bcbad32 100644 --- a/docs/user-guide/tool-catalog/sketching.md +++ b/docs/user-guide/tool-catalog/sketching.md @@ -126,6 +126,7 @@ Draw a closed, axis-aligned rectangle in the open sketch from two opposite corne | `corner2_x` | `float?` | โ€” | `None` | Corner 2 X alias | | `corner2_y` | `float?` | โ€” | `None` | Corner 2 Y alias | | `construction` | `bool` | โ€” | `False` | Construction geometry flag | +| `from_center` | `bool` | โ€” | `False` | `x1`, `y1` is the centre and `x2`, `y2` a corner (`CreateCenterRectangle`) | **Sample call:** @@ -156,20 +157,25 @@ Close the open sketch so a feature can use it. ### `add_arc` -Draw a circular arc in the open sketch from its centre, start point and end point, in mm. +Draw a circular arc in the open sketch: from its centre, through three points, or tangent. **Prerequisite:** Active sketch edit mode +**SolidWorks automation note:** `kind` picks the call: `center` is `ISketchManager.CreateArc`, counter-clockwise from start to end; `three_point` is `Create3PointArc` from start to end through `through_x`, `through_y`; `tangent` is `CreateTangentArc` (`swForward`), which starts at the end of an existing entity and leaves tangent to it. + **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `center_x` | `float` | โœ… | `` | Arc center X coordinate in mm | -| `center_y` | `float` | โœ… | `` | Arc center Y coordinate in mm | +| `kind` | `str` | โ€” | `center` | `center`, `three_point` or `tangent` | +| `center_x` | `float?` | for `center` | `None` | Arc center X coordinate in mm | +| `center_y` | `float?` | for `center` | `None` | Arc center Y coordinate in mm | | `start_x` | `float` | โœ… | `` | Arc start point X coordinate in mm | | `start_y` | `float` | โœ… | `` | Arc start point Y coordinate in mm | | `end_x` | `float` | โœ… | `` | Arc end point X coordinate in mm | | `end_y` | `float` | โœ… | `` | Arc end point Y coordinate in mm | +| `through_x` | `float?` | for `three_point` | `None` | X of a point the arc passes through | +| `through_y` | `float?` | for `three_point` | `None` | Y of a point the arc passes through | **Sample call:** @@ -335,6 +341,147 @@ Rewrite the text in a sketch and rebuild, so debossed lettering shows it. --- +### `add_sketch_fillet` + +Round corners of the open sketch to a radius, picking each corner by its point. + +**Prerequisite:** Active sketch edit mode, with entities meeting at each corner + +**SolidWorks automation note:** Each corner is found among the open sketch's points (`ISketch.GetSketchPoints2`, within 0.01 mm), selected alone, and rounded with `ISketchManager.CreateFillet` (constrained corners kept, so no dialog opens). The lines either side are trimmed back to the arc, as in SolidWorks. Corners are points, not ids, because a rectangle or polygon registers as one id with no id per corner. Every corner is found before any is rounded: a corner with no sketch point fails as `invalid_input` and nothing changes. A sketch point that isn't where two entities meet (a centre rectangle's centre point) is refused by SolidWorks, also as `invalid_input`. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `corners` | `list[list[float]]` | โœ… | | Corners, each `[x, y]` in sketch mm | +| `radius` | `float` | โœ… | | Fillet radius in mm | + +**Sample call:** + +```json +{"corners": [[-60, -40], [-60, 40]], "radius": 10} +``` + +--- + +### `add_sketch_chamfer` + +Bevel corners of the open sketch, picking each corner by its point. + +**Prerequisite:** Active sketch edit mode, with entities meeting at each corner + +**SolidWorks automation note:** Corners are found as for `add_sketch_fillet`, then `ISketchManager.CreateChamfer`: `distance` alone is equal distances (`swSketchChamfer_DistanceEqual`), `distance2` two distances, `angle` a distance and an angle. Giving both `distance2` and `angle` is `invalid_input`. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `corners` | `list[list[float]]` | โœ… | | Corners, each `[x, y]` in sketch mm | +| `distance` | `float` | โœ… | | Distance along each side in mm | +| `distance2` | `float?` | โ€” | `None` | A different distance along the second side, mm | +| `angle` | `float?` | โ€” | `None` | Angle from the first side in degrees, with `distance` | + +**Sample call:** + +```json +{"corners": [[60, -40], [60, 40]], "distance": 10} +``` + +--- + +### `add_slot` + +Draw a slot in the open sketch: straight between two centres, or along an arc. + +**Prerequisite:** Active sketch edit mode + +**SolidWorks automation note:** `ISketchManager.CreateSketchSlot`, length centre to centre, no dimensions added. A straight slot (`swSketchSlotCreationType_line`) runs between its end centres `start` and `end`. An arc slot (`swSketchSlotCreationType_arc`) follows the arc about `center` from `start` to `end`, counter-clockwise. The reply's `area` is the centreline's length times the width plus one circle of the width's diameter (the two rounded ends). + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `kind` | `str` | โ€” | `straight` | `straight`, or `arc` | +| `width` | `float` | โœ… | | Slot width in mm | +| `start` | `list[float]` | โœ… | | `[x, y]` mm: first end centre (straight), or start on the arc (arc) | +| `end` | `list[float]` | โœ… | | `[x, y]` mm: second end centre (straight), or end on the arc (arc) | +| `center` | `list[float]?` | โ€” | `None` | `[x, y]` mm: the arc's centre (arc) | + +**Sample call:** + +```json +{"start": [-40, -15], "end": [-40, 15], "width": 10} +``` + +--- + +### `sketch_trim` + +Trim away the piece of a sketch entity at a point, back to where it meets others. + +**Prerequisite:** Active sketch edit mode, with an entity at the point + +**SolidWorks automation note:** The point is mapped from the sketch into model space (the inverse of `ISketch.ModelToSketchTransform`), the entity there is selected (`SelectByID2`, `SKETCHSEGMENT`), and `ISketchManager.SketchTrim` with `swSketchTrimClosest` removes the piece nearest the point. An entity that meets nothing is removed whole. The reply gives the sketch's segment count before and after; a trimmed entity's id may no longer name a whole segment. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `point` | `list[float]` | โœ… | | `[x, y]` in sketch mm on the piece to remove | + +**Sample call:** + +```json +{"point": [0, 2]} +``` + +--- + +### `sketch_extend` + +Lengthen a sketch entity from its end nearest a point until it meets the next entity. + +**Prerequisite:** Active sketch edit mode, with an entity at the point and another in its way + +**SolidWorks automation note:** The entity at the point is selected as for `sketch_trim`, then `ISketchManager.SketchExtend` lengthens it from the end nearer the point. Nothing at the point, or nothing to reach, fails as `invalid_input` and the sketch is unchanged. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `point` | `list[float]` | โœ… | | `[x, y]` in sketch mm on the entity, near the end to lengthen | + +**Sample call:** + +```json +{"point": [-3, -0.5]} +``` + +--- + +### `set_construction_geometry` + +Make sketch entities construction geometry, or normal again, by id. + +**Prerequisite:** Active sketch edit mode, with ids from the sketch tools + +**SolidWorks automation note:** Sets `ISketchSegment.ConstructionGeometry` on every segment of each id (a rectangle's or polygon's id holds four or more) and reads it back. The property is set, not toggled (`CreateConstructionGeometry` toggles), so a repeated call changes nothing. `construction` on `add_line`, `add_circle` and `add_rectangle` uses this after drawing. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `entities` | `list[str]` | โœ… | | Entity ids, e.g. `Line_3` | +| `construction` | `bool` | โ€” | `True` | `true` for construction geometry, `false` for normal | + +**Sample call:** + +```json +{"entities": ["Line_3"]} +``` + +--- + ### `add_sketch_constraint` Add a geometric relation between sketch entities: horizontal, vertical, parallel, perpendicular, tangent, coincident, concentric, equal, symmetric, collinear or fix. diff --git a/docs/user-guide/tools-overview.md b/docs/user-guide/tools-overview.md index cd3c5fac..96890764 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -67,9 +67,9 @@ These read SolidWorks' installed files and never start it --- - Sketches on a plane or a flat face: lines, arcs, circles, rectangles, polygons, splines, relations, dimensions, offsets, mirrors, patterns and edges converted from the model. + Sketches on a plane or a flat face: lines, arcs, circles, rectangles, slots, polygons, splines, fillets, chamfers, trim and extend, construction geometry, relations, dimensions, offsets, mirrors, patterns and edges converted from the model. - [**21 tools available** :octicons-arrow-right-24:](tool-catalog/sketching.md) + [**27 tools available** :octicons-arrow-right-24:](tool-catalog/sketching.md) - :material-technical-draw:{ .lg .middle } **Drawing Tools** @@ -185,7 +185,7 @@ These read SolidWorks' installed files and never start it -**Total: 145 Tools** +**Total: 151 Tools** ## Deprecated tools diff --git a/openspec/changes/sketch-essentials/.openspec.yaml b/openspec/changes/sketch-essentials/.openspec.yaml new file mode 100644 index 00000000..ce56180a --- /dev/null +++ b/openspec/changes/sketch-essentials/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-19 diff --git a/openspec/changes/sketch-essentials/design.md b/openspec/changes/sketch-essentials/design.md new file mode 100644 index 00000000..7e1045ba --- /dev/null +++ b/openspec/changes/sketch-essentials/design.md @@ -0,0 +1,129 @@ +## Context + +Sketch tools live in `adapters/solidworks/sketch.py` (one `__impl` +per tool, run through `_handle_com_operation`) and `tools/sketching.py` +(the inputs and the tools). Entities are registered in +`adapter._sketch_entities` under ids such as `Line_1`; a rectangle or +polygon registers as one id holding its segments. Coordinates are sketch +coordinates in mm. `_to_sketch_space` already maps a model point into the +open sketch with the sketch's `ModelToSketchTransform`. + +The COM signatures and enum values below were read from this machine's +SolidWorks 2026 type library (`lookup_api_method`, `get_api_enum`). + +## Goals / Non-Goals + +**Goals:** the sketch operations agents need next, each one tool call with +the arguments an agent already has (the points and ids it drew); construction +geometry that works on SolidWorks. + +**Non-goals:** 3D sketches, sketch blocks, splines by equation, conics and +the other `ISketchManager` members; selecting a slot as a pattern or mirror +seed (a later item if needed). + +## Decisions + +### 1. Corners are picked by point, not by entity id + +A rectangle or polygon registers as one id, so there is no id for "the +top-left corner". The agent does know the corner's coordinates: it drew +them. `add_sketch_fillet` and `add_sketch_chamfer` take `corners`, a list of +`[x, y]` in sketch mm, and find the open sketch's point at each +(`ISketch.GetSketchPoints2`, X and Y within 0.01 mm). Each corner is +selected alone (`ISketchPoint.Select4`) and filleted or chamfered by its own +call, so each gets its own id in the reply. A corner with no sketch point +fails as `invalid_input` naming it, before anything changes. + +`CreateFillet(Radius, ConstrainedCorners)`: `ConstrainedCorners` is +`swConstrainedCornerKeepGeometry` (1). `swConstrainedCornerInteract` (0) +can open a dialog, which stalls an automated run. + +`CreateChamfer(Type, Distance, AngleORdist)`, `swSketchChamferType_e`: +`distance` alone is equal distances (2); with `distance2`, two distances +(1); with `angle` (degrees), distance and angle (0). Giving both +`distance2` and `angle` is `invalid_input`. + +Alternative considered: two entity ids per corner. Rejected: it can't +name a rectangle's corners and makes the agent find ids it never saw. + +### 2. Slots + +`CreateSketchSlot(SlotCreationType, SlotLengthType, Width, X1..Z3, +CenterArcDirection, AddDimension)`, length type +`swSketchSlotLengthType_CenterCenter` (0), no dimensions added: + +- `kind: "straight"`: `swSketchSlotCreationType_line` (0), point 1 and 2 the + arc centres (`start`, `end`), point 3 the end again. +- `kind: "arc"`: `swSketchSlotCreationType_arc` (2), point 1 the arc's + centre (`center`), 2 and 3 the slot's centreline start and end; + `CenterArcDirection` 1, counter-clockwise from start to end. + +Which point is which, and the direction's sign, are taken from the API +help and checked in the live demo, whose cut volume would differ if they +were wrong. The reply gives the id, the centres, the width and the area +(straight: `length * width + pi * (width / 2) ** 2`; arc: the centreline arc +length times width plus the same end circles). + +### 3. Trim and extend at a point + +`SketchTrim(Option, X, Y, Z)` and `SketchExtend(X, Y, Z)` take a pick point +in **model** space (recorded macros pass model coordinates), with the entity +selected first. The tools take `point`, `[x, y]` in sketch mm, as every other +sketch tool does. A new `_to_model_space` maps it through the inverse of +`ModelToSketchTransform`; the entity under it is selected with +`SelectByID2("", "SKETCHSEGMENT", ...)` (a null `VT_DISPATCH` callout, +runbook item 11), then `SketchTrim(swSketchTrimClosest (0), ...)` removes the +piece nearest the point, back to the nearest intersections, or +`SketchExtend` lengthens the entity from its end nearest the point to the +next entity it meets. `False` from either, or nothing under the point, fails +as `invalid_input` and the sketch is unchanged. + +The reply gives the sketch's segment count before and after. A trimmed +entity's id may name a segment SolidWorks has split or deleted; the reply +says so instead of guessing new ids. + +### 4. Construction geometry by property + +`set_construction_geometry(entities, construction=True)` sets +`ISketchSegment.ConstructionGeometry` on each segment of each id, then reads +it back. Setting the property is idempotent; the toggle +`CreateConstructionGeometry` would flip entities already set. An unknown id +fails before anything changes. + +The `construction` fix reuses it: after `add_line`, `add_circle` or +`add_rectangle` draws with `construction` on, the tool calls +`set_construction_geometry` on the new id. It sits in the tool, not in each +adapter method, so every adapter gets it with no signature change. + +### 5. `add_arc` kinds and `add_rectangle` `from_center` + +- `add_arc` `kind`: `center` (default; `CreateArc`, today), `three_point` + (`start`, `end` and `through_x`/`through_y`; `Create3PointArc`), `tangent` + (`start` must be the end of an existing entity, `end` where the arc ends; + `CreateTangentArc(..., swForward (1))`). `center_*` is required only for + `center`, `through_*` only for `three_point`; a missing field is + `invalid_input`. +- `add_rectangle` `from_center`: `x1`, `y1` the centre, `x2`, `y2` a corner + (`CreateCenterRectangle`). The reply's `corner1`/`corner2` are the real + opposite corners and `width`/`height` the full size, so it reads the same + as a corner rectangle. + +### 6. Where the code goes + +The new COM code goes in `adapters/solidworks/sketch.py`, already 2,900 +lines. Splitting it is queue item 40 (structure review); this change adds +its functions at the end in one block and doesn't reorganise the file. +Each new adapter method is added to `base.py`, `circuit_breaker.py`, +`connection_pool.py` and the mock, as today. Item 40 will look at +replacing those per-method forwards with one path. + +## Risks / Trade-offs + +- [Slot point order or arc direction differs from the help] โ†’ the live + demo's volume check catches it; fix and rerun before sign-off. +- [Pick points in model space are wrong for a sketch not on the Front + plane] โ†’ the demo's sketches are on the Top plane, where sketch Y is model + -Z, so a wrong mapping fails there. +- [A corner point shared by several entities, e.g. a polygon vertex on a + construction line] โ†’ the fillet uses SolidWorks' own choice of the two + segments at that point, the same as clicking it. diff --git a/openspec/changes/sketch-essentials/proposal.md b/openspec/changes/sketch-essentials/proposal.md new file mode 100644 index 00000000..cad4c547 --- /dev/null +++ b/openspec/changes/sketch-essentials/proposal.md @@ -0,0 +1,74 @@ +## Why + +An agent can draw lines, arcs, circles, rectangles and polygons, but not the +sketch operations almost every real part needs next: a rounded or bevelled +corner, a slot, trimming a profile back to where two shapes meet, or turning +a line into construction geometry. Without them an agent fakes a rounded +corner from lines and a hand-placed arc, then fights the dimensions, and a +slot takes six entities. This is the first of the COM-coverage packages +(queue item 32, the user's choice 2026-11-19): it fills the gaps in +`ISketchManager` an agent hits first. + +It also fixes a fault found while planning: `add_line`, `add_circle` and +`add_rectangle` accept `construction`, but on SolidWorks the flag is dropped +and the reply still says `"construction": true`. Only the mock honours it. + +## What Changes + +- **`add_sketch_fillet`**: rounds sketch corners, picked by their points in + sketch coordinates, to a radius (`ISketchManager.CreateFillet`). The + lines either side are trimmed back, as in SolidWorks. +- **`add_sketch_chamfer`**: bevels sketch corners picked the same way: an + equal distance, two distances, or a distance and an angle + (`CreateChamfer`). +- **`add_slot`**: a straight slot from its two arc centres and width, or an + arc slot from a centre, start and end and width (`CreateSketchSlot`). + Returns one id for the slot, with its centres, width and area. +- **`sketch_trim`** and **`sketch_extend`**: trim the piece of an entity + nearest a point back to where it meets other geometry, or extend an + entity from the end nearest a point to the next geometry it meets + (`SketchTrim`, `SketchExtend`). +- **`set_construction_geometry`**: makes sketch entities construction + geometry, or normal again, by id (`ISketchSegment.ConstructionGeometry`). +- **`add_arc`** gains `kind`: `center` (today's, the default), + `three_point` (start, end and a point the arc passes through, + `Create3PointArc`) and `tangent` (from the end of the last entity, tangent + to it, `CreateTangentArc`). +- **`add_rectangle`** gains `from_center`: the first point is the centre and + the second a corner (`CreateCenterRectangle`). +- **Fix:** `construction` on `add_line`, `add_circle` and `add_rectangle` + makes construction geometry on SolidWorks, as the reply already says. +- Six new tools: 145 to 151. + +## Capabilities + +### New Capabilities + +- `tools/sketch-corners`: `add_sketch_fillet` and `add_sketch_chamfer` + round or bevel sketch corners picked by point. +- `tools/sketch-slots`: `add_slot` draws a straight or arc slot. +- `tools/sketch-trim-extend`: `sketch_trim` and `sketch_extend` cut back + or lengthen sketch entities at a point. +- `tools/sketch-construction`: `set_construction_geometry`, and + `construction` honoured on `add_line`, `add_circle` and `add_rectangle`. +- `tools/sketch-arcs-and-rectangles`: `add_arc` `kind` (centre, + three-point, tangent) and `add_rectangle` `from_center`. + +### Modified Capabilities + +None. No existing spec covers the basic sketch tools; the two changed tools +keep their current behaviour by default. + +## Impact + +- `adapters/solidworks/sketch.py` (the COM calls), `adapters/base.py`, + `circuit_breaker.py`, `connection_pool.py`, `mock_adapter.py` (the new + methods), `tools/sketching.py` (inputs and tools), `tools/tool_hints.py`, + `tools/support_levels.py`, the toolset table. +- Docs: the sketching catalog page, tool counts (README, index, catalog + index, tools overview), progress files, `llms.txt`, CHANGELOG. +- A live demo, `tests/live/test_live_sw_sketch_essentials.py`, recorded as + a GIF: one part built with every new operation, its volume checked + against the hand calculation. +- No new dependency. No breaking change: both changed tools default to + today's behaviour. diff --git a/openspec/changes/sketch-essentials/specs/tools/sketch-arcs-and-rectangles/spec.md b/openspec/changes/sketch-essentials/specs/tools/sketch-arcs-and-rectangles/spec.md new file mode 100644 index 00000000..22baf099 --- /dev/null +++ b/openspec/changes/sketch-essentials/specs/tools/sketch-arcs-and-rectangles/spec.md @@ -0,0 +1,31 @@ +## ADDED Requirements + +### Requirement: Three ways to draw an arc +`add_arc` SHALL take `kind`: `center` (the default: `center`, `start` and +`end`, as today), `three_point` (`start`, `end`, and `through_x`/`through_y`, +a point the arc passes through) or `tangent` (`start`, the end of an +existing entity, and `end`; the arc leaves tangent to that entity). It +SHALL reply with the arc's id and points. + +#### Scenario: A stadium window from lines and arcs +- **WHEN** a line runs from `[-20, 25]` to `[10, 25]`, a tangent arc from + `[10, 25]` to `[10, 35]`, a line back to `[-20, 35]`, and a three-point + arc from `[-20, 35]` to `[-20, 25]` through `[-25, 30]` +- **THEN** the profile is closed, and cutting it through an 8 mm plate + removes `8 * (30 * 10 + pi * 25)` mmยณ + +#### Scenario: A missing field +- **WHEN** `kind` is `three_point` and `through_x` is missing +- **THEN** it fails with `invalid_input` naming `through_x` + +### Requirement: A rectangle from its centre +`add_rectangle` with `from_center` on SHALL take `x1`, `y1` as the centre +and `x2`, `y2` as a corner, and draw the rectangle centred there. The reply's +`corner1` and `corner2` SHALL be its real opposite corners and `width` and +`height` its full size. + +#### Scenario: A plate centred on the origin +- **WHEN** `add_rectangle` is called with `from_center`, `x1` 0, `y1` 0, + `x2` 60, `y2` 40 +- **THEN** the rectangle runs from `[-60, -40]` to `[60, 40]`, and the reply + gives width 120 and height 80 diff --git a/openspec/changes/sketch-essentials/specs/tools/sketch-construction/spec.md b/openspec/changes/sketch-essentials/specs/tools/sketch-construction/spec.md new file mode 100644 index 00000000..8beb1036 --- /dev/null +++ b/openspec/changes/sketch-essentials/specs/tools/sketch-construction/spec.md @@ -0,0 +1,28 @@ +## ADDED Requirements + +### Requirement: Make entities construction geometry, or normal again +`set_construction_geometry` SHALL take `entities` (sketch entity ids) and +`construction` (default on). It SHALL set every segment of every entity to +construction geometry, or back to normal, read each back, and reply with the +ids and their state. Setting an entity to the state it is already in SHALL +succeed and change nothing. + +#### Scenario: A reference line left out of a cut +- **WHEN** a line across the plate is made construction geometry and the + sketch is cut through the plate +- **THEN** the cut uses only the closed profiles, and the plate loses only + their area times its thickness + +#### Scenario: Unknown id +- **WHEN** an id was never returned by a sketch tool +- **THEN** it fails with `invalid_input` naming the id, and no entity + changes + +### Requirement: `construction` is honoured when drawing +`add_line`, `add_circle` and `add_rectangle` with `construction` on SHALL +draw construction geometry on SolidWorks, as their replies say. + +#### Scenario: A construction line from add_line +- **WHEN** `add_line` is called with `construction` on and the sketch is + cut +- **THEN** the line is construction geometry and doesn't change the cut diff --git a/openspec/changes/sketch-essentials/specs/tools/sketch-corners/spec.md b/openspec/changes/sketch-essentials/specs/tools/sketch-corners/spec.md new file mode 100644 index 00000000..c8e9c7b1 --- /dev/null +++ b/openspec/changes/sketch-essentials/specs/tools/sketch-corners/spec.md @@ -0,0 +1,42 @@ +## ADDED Requirements + +### Requirement: Round or bevel sketch corners picked by point +`add_sketch_fillet` SHALL take `corners` (one or more `[x, y]` in sketch mm) +and `radius` (mm, above 0). `add_sketch_chamfer` SHALL take `corners` and +`distance` (mm, above 0), with either `distance2` (two distances) or `angle` +(degrees, distance and angle), not both; `distance` alone SHALL make equal +distances. With a sketch open, each tool SHALL find the sketch point at +each corner (within 0.01 mm), round or bevel that corner on its own, trim +the entities either side back to it, and reply with one id per corner. + +#### Scenario: A rectangle's corners rounded +- **WHEN** a 120 x 80 mm rectangle centred on the origin is drawn and + `add_sketch_fillet` is called with `corners` `[[-60, -40], [-60, 40]]` + and `radius` 10 +- **THEN** both corners become 10 mm arcs, two ids are returned, and an + 8 mm extrusion of the profile is `8 * (9600 - 2 * 100 * (1 - pi / 4))` + mmยณ + +#### Scenario: Equal-distance chamfer +- **WHEN** `add_sketch_chamfer` is called on a rectangle corner with + `distance` 10 +- **THEN** the corner is cut by a line 10 mm along each side, removing + 50 mmยฒ from the profile + +### Requirement: A corner that isn't there changes nothing +Each tool SHALL fail with `invalid_input` when no sketch is open, when a +corner has no sketch point, when SolidWorks refuses a point that isn't where +two entities meet, or when `distance2` and `angle` are both given, naming the +corner or the fields; the sketch SHALL be unchanged. + +#### Scenario: A point off the profile +- **WHEN** `add_sketch_fillet` is called with a corner at `[0, 0]` inside + the rectangle +- **THEN** it fails with `invalid_input` naming `[0, 0]`, and no corner is + rounded + +#### Scenario: A sketch point that isn't a corner +- **WHEN** the rectangle was drawn from its centre, so `[0, 0]` is its + centre point, and `add_sketch_fillet` is called there +- **THEN** SolidWorks refuses it, the tool fails with `invalid_input` saying + the point isn't where two entities meet, and the part is unchanged diff --git a/openspec/changes/sketch-essentials/specs/tools/sketch-slots/spec.md b/openspec/changes/sketch-essentials/specs/tools/sketch-slots/spec.md new file mode 100644 index 00000000..08977a1c --- /dev/null +++ b/openspec/changes/sketch-essentials/specs/tools/sketch-slots/spec.md @@ -0,0 +1,31 @@ +## ADDED Requirements + +### Requirement: Straight and arc slots +`add_slot` SHALL take `kind` (`straight`, the default, or `arc`) and +`width` (mm, above 0). A straight slot SHALL take `start` and `end`, its two +arc centres as `[x, y]` in sketch mm. An arc slot SHALL take `center`, the +centre of the arc it follows, and `start` and `end` on that arc, going +counter-clockwise. With a sketch open, it SHALL draw the slot as one closed +profile and reply with its id, centres, width and area. + +#### Scenario: A straight slot cut through a plate +- **WHEN** a straight slot from `[-40, -15]` to `[-40, 15]`, 10 mm wide, + is cut through an 8 mm plate +- **THEN** the plate loses `8 * (30 * 10 + pi * 25)` mmยณ, and the reply's + area is `30 * 10 + pi * 25` + +#### Scenario: An arc slot +- **WHEN** an arc slot about `[25, 0]` from `[39.142, -14.142]` to + `[39.142, 14.142]`, 8 mm wide, is cut through the plate +- **THEN** the plate loses 8 mm times the slot's area: the centreline's arc + length (a quarter of a 20 mm radius circle) times 8, plus a 4 mm radius + circle for the two rounded ends + +### Requirement: Missing points fail +`add_slot` SHALL fail with `invalid_input` when no sketch is open, when a +point its `kind` needs is missing, or when `start` and `end` are the same, +and nothing SHALL be drawn. + +#### Scenario: An arc slot without its centre +- **WHEN** `add_slot` is called with `kind` `arc` and no `center` +- **THEN** it fails with `invalid_input` naming `center` diff --git a/openspec/changes/sketch-essentials/specs/tools/sketch-trim-extend/spec.md b/openspec/changes/sketch-essentials/specs/tools/sketch-trim-extend/spec.md new file mode 100644 index 00000000..2d5cb0d3 --- /dev/null +++ b/openspec/changes/sketch-essentials/specs/tools/sketch-trim-extend/spec.md @@ -0,0 +1,33 @@ +## ADDED Requirements + +### Requirement: Trim the piece nearest a point +`sketch_trim` SHALL take `point`, `[x, y]` in sketch mm on the piece of an +entity to remove. With a sketch open, it SHALL remove that piece back to the +nearest places it meets other entities (the whole entity when it meets +none), and reply with the sketch's segment count before and after. + +#### Scenario: A keyhole's inner arc trimmed +- **WHEN** a circle of radius 8 at `[0, 10]` meets two vertical lines at + x = -3 and x = 3, and `sketch_trim` is called at `[0, 2]` +- **THEN** the circle's arc between the two lines is removed, and the + sketch closes into one keyhole profile + +### Requirement: Extend an entity to the next one +`sketch_extend` SHALL take `point`, `[x, y]` in sketch mm near the end of an +entity to lengthen. It SHALL extend that entity from its end nearest the +point until it meets the next entity, and reply with the segment counts. + +#### Scenario: Lines extended up to a circle +- **WHEN** a vertical line from `[-3, -15]` to `[-3, 0]` stops below a + circle of radius 8 at `[0, 10]`, and `sketch_extend` is called at + `[-3, -0.5]` +- **THEN** the line ends on the circle, at y = 10 - sqrt(55) + +### Requirement: Nothing under the point changes nothing +Both tools SHALL fail with `invalid_input` when no sketch is open or no +entity is at the point, or when SolidWorks refuses the trim or extension, +naming the point; the sketch SHALL be unchanged. + +#### Scenario: Empty space +- **WHEN** `sketch_trim` is called at a point no entity passes through +- **THEN** it fails with `invalid_input` naming the point diff --git a/openspec/changes/sketch-essentials/tasks.md b/openspec/changes/sketch-essentials/tasks.md new file mode 100644 index 00000000..b7beb4c0 --- /dev/null +++ b/openspec/changes/sketch-essentials/tasks.md @@ -0,0 +1,33 @@ +## 1. Adapter (COM) in `adapters/solidworks/sketch.py` + +- [x] 1.1 `_corner_points` (the open sketch's point within 0.01 mm of each sketch-mm corner, all found before any change) and `_to_model_space` (sketch mm to model metres, the inverse of `ModelToSketchTransform`) +- [x] 1.2 `_add_sketch_fillet_impl` and `_add_sketch_chamfer_impl`: every corner found before any change, then one `CreateFillet` (keep constrained corners) or `CreateChamfer` per corner; one registered id per corner +- [x] 1.3 `_add_slot_impl`: `CreateSketchSlot`, straight (line, centre-to-centre) and arc (centre, start, end, counter-clockwise); registered id; area +- [x] 1.4 `_sketch_trim_impl` and `_sketch_extend_impl`: point to model space, select the segment there (null callout), `SketchTrim(closest)` / `SketchExtend`; segment counts before and after; nothing selected or `False` is an error +- [x] 1.5 `_set_construction_geometry_impl`: ids checked first, `ConstructionGeometry` set on every segment and read back +- [x] 1.6 `_add_arc_impl` takes `kind` (`Create3PointArc`, `CreateTangentArc` forward) and `_add_rectangle_impl` takes `from_center` (`CreateCenterRectangle`), both defaulting to today's call +- [x] 1.7 Mixin methods for each; unit tests in `test_sketch.py` with fake COM objects (success, each failure, nothing changed on failure) + +## 2. Adapter wrappers and mock + +- [x] 2.1 `base.py`, `circuit_breaker.py`, `connection_pool.py`: the six new methods and the new `add_arc` / `add_rectangle` arguments; tests beside each +- [x] 2.2 `mock_adapter.py`: the six methods (plausible ids, areas and counts; the same input errors) and the new arguments; tests + +## 3. Tools in `tools/sketching.py` + +- [x] 3.1 Inputs: `AddSketchFilletInput`, `AddSketchChamferInput` (`distance2` or `angle`, not both), `AddSlotInput` (points by `kind`), `SketchPointInput` (trim, extend), `SetConstructionGeometryInput`; `AddArcInput` `kind` and `through_x`/`through_y`; `AddRectangleInput` `from_center` +- [x] 3.2 The six tools, descriptions to the standard (Use it for / Needs / Changes / Returns), replies as in the specs +- [x] 3.3 `construction` on `add_line`, `add_circle`, `add_rectangle` calls `set_construction_geometry` on the new id +- [x] 3.4 `tool_hints.py`, `support_levels.py` (stable after the live demo; beta until then), `test_all_endpoints_harness.py` entries; tests in `test_sketching.py` + +## 4. Docs + +- [x] 4.1 Catalog `sketching.md`: the six tools, and `add_arc` `kind` / `add_rectangle` `from_center`; tool counts to 151 (README, docs index, catalog index, tools overview) +- [x] 4.2 Progress files and `llms.txt` regenerated; CHANGELOG +- [x] 4.3 Unit suite at 100% coverage, ruff, mypy, mkdocs strict, link check + +## 5. Live demo and sign-off + +- [x] 5.1 `tests/live/test_live_sw_sketch_essentials.py`: a slotted bracket plate, built sharp: a centre rectangle extruded 8 mm (a sketch fillet at its centre point refused); straight and arc slots cut with two construction lines in the sketch; a keyhole (lines extended to a circle, the arc between trimmed, the neck's corners rounded and bevelled in the sketch); a stadium window (tangent and three-point arcs); then, last in the tree (the user's rule), the plate's corner edges filleted and chamfered. The volume checked against the hand calculation after each step. Live finds so far: a centre rectangle has a centre point (a refused corner is now `invalid_input`); `SketchTrim` returns False after trimming, so trim and extend are judged by the sketch's segment length +- [x] 5.2 The user runs the demo (passed 2026-11-19, final volume 64,766.85 mmยณ against 64,766.42 expected); fix anything it finds; record the GIF; demos page section and README tile if the user wants one +- [x] 5.3 Promote the six tools to stable; commit; ask before pushing diff --git a/openspec/queue.md b/openspec/queue.md index ad12a0c1..3dad2ab9 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -6,7 +6,7 @@ reviewed, then implemented, signed off live where it touches SolidWorks, and archived after its PR merges. Update this file when an item is done or the order changes. -Last updated 2026-11-16. +Last updated 2026-11-19. | # | Item | Issue | OpenSpec change | State | | --- | --- | --- | --- | --- | @@ -39,9 +39,18 @@ Last updated 2026-11-16. | 26 | `execute_macro` runs VBA source text (a `generate_vba_*` result, or the agent's own), saved as a `.swb` and run with the dialog watchdog. Opt-in (`SOLIDWORKS_MCP_ALLOW_VBA_SOURCE`), the user's choice 2026-11-17 | #96 | `macro-from-vba-source` (archived) | Done 2026-11-17 (#246), checked live | | 27 | `save_body_as_part` leaves an extra unsaved assembly open (the Save Bodies feature's create-assembly option) | #101 | `save-body-no-stray-assembly` (archived) | Done 2026-11-17 (#247), checked live: the stray `Assem` is closed | | 28 | Restricted VBA source: `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE` = off / restricted / full; `restricted` checks the source against the SolidWorks type library and a blocklist before it runs, with every default and option disclosed in the docs (the user's choice 2026-11-17) | none | `vba-source-restricted` (archived) | Done 2026-11-17 (#248), checked live: restricted source runs, a `Shell` line is refused, `off` refuses | -| 29 | Equations and global variables: `list_equations`, `set_equation` (add or change, in all configurations by default) and `delete_equation`, so one value drives several dimensions. The base for macro-driven parametric features | none | `equations-and-global-variables` | Built, unit-tested; live check pending (`tests/live/test_live_sw_equations.py`) | +| 29 | Equations and global variables: `list_equations`, `set_equation` (add or change, in all configurations by default) and `delete_equation`, so one value drives several dimensions. The base for macro-driven parametric features | none | `equations-and-global-variables` | Done 2026-11-18 (#250): all three live tests passed; the wrench demo recorded. Archive after the user signs off the two small demos (task 4.4) | | 30 | Build a part from an engineering drawing (image or PDF): research first, then an OpenSpec change for a first version | #249 | not yet written | Research to do (the user's request 2026-11-17) | -| 31 | `generate_drawing_package` fits every title-block field the sheet format fills from a property, not just DWG NO. and TITLE | #158 (part) | `title-block-fit-every-field` | Built, unit-tested; checked live 2026-11-18 (`test_live_sw_drawing_package_tools.py::test_generate_drawing_package_on_a_block`) | +| 31 | `generate_drawing_package` fits every title-block field the sheet format fills from a property, not just DWG NO. and TITLE | #158 (part) | `title-block-fit-every-field` | Done 2026-11-19 (#251), checked live | +| 32 | Sketch essentials: sketch fillet and chamfer, slots, trim and extend, tangent and 3-point arcs, centre rectangle, construction geometry on and off (ISketchManager; the user's choice 2026-11-19, first of the COM-coverage packages) | none | `sketch-essentials` | Built; live demo passed 2026-11-19 (`tests/live/test_live_sw_sketch_essentials.py`); the six tools stable | +| 33 | Assembly depth and a ballooned drawing: exploded view, component patterns, mirror and replace components, hide/show/transparency, `AutoBalloon` on the drawing | #23 (part) | not yet written | Planned | +| 34 | Helix and swept cuts: helix/spiral, a swept cut (`create_sweep` only adds material), thicken; springs and modelled threads | none | not yet written | Planned | +| 35 | Multi-body tools: combine (add, subtract, common), split, move/copy, delete/keep a body, scale | none | not yet written | Planned | +| 36 | Appearance and colour: set a part's, body's or face's colour and read it back | none | not yet written | Planned (small; may ride with another item) | +| 37 | Drawing sheets and callouts: new and active sheet, auxiliary, break and broken-out views, hole callouts, ordinate dimensions, surface finish, revision table | #158 (part) | not yet written | Planned | +| 38 | Weldments: structural members, trim/extend, end caps, gussets, cut list | none | not yet written | Planned (needs live probes: the profile library location varies) | +| 39 | Reference and analysis extras: coordinate system, bounding box, centre-of-mass point, section properties; wrap (text on a curved face) | none | not yet written | Planned | +| 40 | Structure review (the user's request 2026-11-19), not a rewrite: the adapter wrappers (`base`, `circuit_breaker`, `connection_pool`, each about 2,500 lines of near-identical per-tool methods) repeat every adapter method, and the largest modules (`mock_adapter` 4,900, `io` 4,000, `features` 3,800, `modeling` 3,200, `sketch` 2,900 lines) should split by topic, as `adapters/solidworks/` already does. Measure the repetition, propose a SOLID structure (one generic forwarding path; one module per topic), and move to it in steps that keep every test passing | none | not yet written | Planned (last) | ## Removed tools (item 10, release 2.1.0) 33 tools were registered but never implemented: every call returned diff --git a/src/solidworks_mcp/adapters/base.py b/src/solidworks_mcp/adapters/base.py index 06ce2409..086ca7fe 100644 --- a/src/solidworks_mcp/adapters/base.py +++ b/src/solidworks_mcp/adapters/base.py @@ -737,15 +737,16 @@ async def add_circle( @abstractmethod async def add_rectangle( - self, x1: float, y1: float, x2: float, y2: float + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False ) -> AdapterResult[str]: """Add a rectangle to the current sketch. Args: - x1 (float): The x1 value. - y1 (float): The y1 value. + x1 (float): The x1 value (the centre's, with ``from_center``). + y1 (float): The y1 value (the centre's, with ``from_center``). x2 (float): The x2 value. y2 (float): The y2 value. + from_center (bool): ``x1``/``y1`` is the centre, ``x2``/``y2`` a corner. Returns: AdapterResult[str]: The result produced by the operation. @@ -760,6 +761,8 @@ async def add_arc( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: """Add an arc to the current sketch. @@ -770,6 +773,8 @@ async def add_arc( start_y (float): The start y value. end_x (float): The end x value. end_y (float): The end y value. + kind (str): ``center``, ``three_point`` or ``tangent``. + through (tuple[float, float] | None): A point on a three-point arc. Returns: AdapterResult[str]: The result produced by the operation. @@ -905,6 +910,119 @@ async def set_sketch_text( error="set_sketch_text is not implemented by this adapter", ) + async def add_sketch_fillet( + self, corners: list[list[float]], radius: float + ) -> AdapterResult[dict[str, Any]]: + """Round sketch corners picked by point. + + Args: + corners (list[list[float]]): ``[x, y]`` sketch mm, one per corner. + radius (float): Fillet radius in mm. + + Returns: + AdapterResult[dict[str, Any]]: ``ids`` (one per corner) and ``corners``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="add_sketch_fillet is not implemented by this adapter", + ) + + async def add_sketch_chamfer( + self, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Bevel sketch corners picked by point. + + Args: + corners (list[list[float]]): ``[x, y]`` sketch mm, one per corner. + distance (float): Distance along the first side, mm. + distance2 (float | None): Distance along the second side, mm. + angle (float | None): Angle from the first side, degrees. + + Returns: + AdapterResult[dict[str, Any]]: ``ids`` (one per corner) and ``corners``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="add_sketch_chamfer is not implemented by this adapter", + ) + + async def add_slot( + self, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, + ) -> AdapterResult[str]: + """Draw a straight or arc slot. + + Args: + kind (str): ``straight`` or ``arc``. + width (float): Slot width, mm. + start (list[float]): Straight: first arc centre; arc: start on the arc. + end (list[float]): Straight: second arc centre; arc: end on the arc. + center (list[float] | None): Arc slot: the arc's centre. + + Returns: + AdapterResult[str]: The slot's id. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="add_slot is not implemented by this adapter", + ) + + async def sketch_trim(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Trim the piece of a sketch entity nearest a point. + + Args: + point (list[float]): ``[x, y]`` sketch mm on the piece to remove. + + Returns: + AdapterResult[dict[str, Any]]: ``point``, ``segments_before`` and + ``segments_after``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="sketch_trim is not implemented by this adapter", + ) + + async def sketch_extend(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Extend a sketch entity from its end nearest a point. + + Args: + point (list[float]): ``[x, y]`` sketch mm near the end to extend. + + Returns: + AdapterResult[dict[str, Any]]: ``point``, ``segments_before`` and + ``segments_after``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="sketch_extend is not implemented by this adapter", + ) + + async def set_construction_geometry( + self, entities: list[str], construction: bool = True + ) -> AdapterResult[dict[str, Any]]: + """Make sketch entities construction geometry, or normal again. + + Args: + entities (list[str]): Sketch entity ids. + construction (bool): ``True`` for construction, ``False`` for normal. + + Returns: + AdapterResult[dict[str, Any]]: ``entities`` (id to state) and + ``construction``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="set_construction_geometry is not implemented by this adapter", + ) + async def add_sketch_constraint( self, entity1: str, diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index 4e66f2ad..80bba1a9 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -1362,7 +1362,7 @@ async def add_circle( ) async def add_rectangle( - self, x1: float, y1: float, x2: float, y2: float + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False ) -> AdapterResult[str]: """Add rectangle through circuit breaker. @@ -1371,14 +1371,21 @@ async def add_rectangle( y1 (float): The y1 value. x2 (float): The x2 value. y2 (float): The y2 value. + from_center (bool): ``x1``/``y1`` is the centre, ``x2``/``y2`` a corner. Returns: AdapterResult[str]: The result produced by the operation. """ return await self._execute_with_circuit_breaker( "add_rectangle", - lambda: self.adapter.add_rectangle(x1, y1, x2, y2), - input_dict={"x1": x1, "y1": y1, "x2": x2, "y2": y2}, + lambda: self.adapter.add_rectangle(x1, y1, x2, y2, from_center), + input_dict={ + "x1": x1, + "y1": y1, + "x2": x2, + "y2": y2, + "from_center": from_center, + }, ) async def add_arc( @@ -1389,6 +1396,8 @@ async def add_arc( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: """Add arc through circuit breaker. @@ -1399,6 +1408,8 @@ async def add_arc( start_y (float): Arc start Y coordinate. end_x (float): Arc end X coordinate. end_y (float): Arc end Y coordinate. + kind (str): ``center``, ``three_point`` or ``tangent``. + through (tuple[float, float] | None): A point on a three-point arc. Returns: AdapterResult[str]: The result produced by the operation. @@ -1412,6 +1423,8 @@ async def add_arc( start_y, end_x, end_y, + kind, + through, ), input_dict={ "center_x": center_x, @@ -1495,6 +1508,63 @@ async def set_sketch_text( "set_sketch_text", lambda: self.adapter.set_sketch_text(sketch_name, text) ) + async def add_sketch_fillet( + self, corners: list[list[float]], radius: float + ) -> AdapterResult[dict[str, Any]]: + """Round sketch corners through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "add_sketch_fillet", lambda: self.adapter.add_sketch_fillet(corners, radius) + ) + + async def add_sketch_chamfer( + self, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Bevel sketch corners through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "add_sketch_chamfer", + lambda: self.adapter.add_sketch_chamfer( + corners, distance, distance2, angle + ), + ) + + async def add_slot( + self, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, + ) -> AdapterResult[str]: + """Draw a slot through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "add_slot", lambda: self.adapter.add_slot(kind, width, start, end, center) + ) + + async def sketch_trim(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Trim a sketch entity through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "sketch_trim", lambda: self.adapter.sketch_trim(point) + ) + + async def sketch_extend(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Extend a sketch entity through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "sketch_extend", lambda: self.adapter.sketch_extend(point) + ) + + async def set_construction_geometry( + self, entities: list[str], construction: bool = True + ) -> AdapterResult[dict[str, Any]]: + """Set construction geometry through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "set_construction_geometry", + lambda: self.adapter.set_construction_geometry(entities, construction), + ) + async def sketch_linear_pattern( self, entities: list[str], diff --git a/src/solidworks_mcp/adapters/connection_pool.py b/src/solidworks_mcp/adapters/connection_pool.py index 7edbbc00..5e7cc297 100644 --- a/src/solidworks_mcp/adapters/connection_pool.py +++ b/src/solidworks_mcp/adapters/connection_pool.py @@ -1187,7 +1187,7 @@ async def add_circle( ) async def add_rectangle( - self, x1: float, y1: float, x2: float, y2: float + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False ) -> AdapterResult[str]: """Add rectangle using pool. @@ -1196,12 +1196,14 @@ async def add_rectangle( y1 (float): The y1 value. x2 (float): The x2 value. y2 (float): The y2 value. + from_center (bool): ``x1``/``y1`` is the centre, ``x2``/``y2`` a corner. Returns: AdapterResult[str]: The result produced by the operation. """ return await self._execute_with_pool( - "add_rectangle", lambda adapter: adapter.add_rectangle(x1, y1, x2, y2) + "add_rectangle", + lambda adapter: adapter.add_rectangle(x1, y1, x2, y2, from_center), ) async def add_arc( @@ -1212,6 +1214,8 @@ async def add_arc( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: """Add arc using pool. @@ -1222,6 +1226,8 @@ async def add_arc( start_y (float): Arc start Y coordinate. end_x (float): Arc end X coordinate. end_y (float): Arc end Y coordinate. + kind (str): ``center``, ``three_point`` or ``tangent``. + through (tuple[float, float] | None): A point on a three-point arc. Returns: AdapterResult[str]: The result produced by the operation. @@ -1235,6 +1241,8 @@ async def add_arc( start_y, end_x, end_y, + kind, + through, ), ) @@ -1348,6 +1356,65 @@ async def set_sketch_text( lambda adapter: adapter.set_sketch_text(sketch_name, text), ) + async def add_sketch_fillet( + self, corners: list[list[float]], radius: float + ) -> AdapterResult[dict[str, Any]]: + """Round sketch corners using pool.""" + return await self._execute_with_pool( + "add_sketch_fillet", + lambda adapter: adapter.add_sketch_fillet(corners, radius), + ) + + async def add_sketch_chamfer( + self, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Bevel sketch corners using pool.""" + return await self._execute_with_pool( + "add_sketch_chamfer", + lambda adapter: adapter.add_sketch_chamfer( + corners, distance, distance2, angle + ), + ) + + async def add_slot( + self, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, + ) -> AdapterResult[str]: + """Draw a slot using pool.""" + return await self._execute_with_pool( + "add_slot", + lambda adapter: adapter.add_slot(kind, width, start, end, center), + ) + + async def sketch_trim(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Trim a sketch entity using pool.""" + return await self._execute_with_pool( + "sketch_trim", lambda adapter: adapter.sketch_trim(point) + ) + + async def sketch_extend(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Extend a sketch entity using pool.""" + return await self._execute_with_pool( + "sketch_extend", lambda adapter: adapter.sketch_extend(point) + ) + + async def set_construction_geometry( + self, entities: list[str], construction: bool = True + ) -> AdapterResult[dict[str, Any]]: + """Set construction geometry using pool.""" + return await self._execute_with_pool( + "set_construction_geometry", + lambda adapter: adapter.set_construction_geometry(entities, construction), + ) + async def sketch_linear_pattern( self, entities: list[str], diff --git a/src/solidworks_mcp/adapters/mock_adapter.py b/src/solidworks_mcp/adapters/mock_adapter.py index edab95c9..54d3d68b 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -1878,6 +1878,8 @@ async def add_arc( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: """Mock adding a circular arc to sketch. @@ -1888,6 +1890,8 @@ async def add_arc( start_y (float): Arc start point Y. end_x (float): Arc end point X. end_y (float): Arc end point Y. + kind (str): ``center``, ``three_point`` or ``tangent``. + through (tuple[float, float] | None): A point on a three-point arc. Returns: AdapterResult[str]: The result produced by the operation. @@ -1896,6 +1900,11 @@ async def add_arc( return AdapterResult( status=AdapterResultStatus.ERROR, error="No active sketch" ) + if kind == "three_point" and through is None: + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="A three_point arc needs a through point", + ) await asyncio.sleep(self._delays["sketch_operation"] / 2) self._operation_count += 1 @@ -1910,7 +1919,7 @@ async def add_arc( ) async def add_rectangle( - self, x1: float, y1: float, x2: float, y2: float + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False ) -> AdapterResult[str]: """Mock adding a rectangle to sketch. @@ -1919,6 +1928,7 @@ async def add_rectangle( y1 (float): The y1 value. x2 (float): The x2 value. y2 (float): The y2 value. + from_center (bool): ``x1``/``y1`` is the centre. Returns: AdapterResult[str]: The result produced by the operation. @@ -2033,6 +2043,159 @@ async def set_sketch_text( data={"sketch": sketch_name, "before": [], "after": [text]}, ) + def _no_sketch(self) -> AdapterResult[Any] | None: + """The "No active sketch" error, or ``None`` with a sketch open.""" + if self._current_sketch: + return None + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def _corner_ids(self, prefix: str, corners: list[list[float]]) -> list[str]: + """One new registered id per corner.""" + ids = [f"{prefix}_{random.randint(1000, 9999)}" for _ in corners] + self._sketch_entity_ids.update(ids) + self._operation_count += 1 + return ids + + async def add_sketch_fillet( + self, corners: list[list[float]], radius: float + ) -> AdapterResult[dict[str, Any]]: + """Mock rounding sketch corners: one id per corner. + + Args: + corners (list[list[float]]): ``[x, y]`` sketch mm. + radius (float): Fillet radius in mm. + + Returns: + AdapterResult[dict[str, Any]]: ``ids`` and ``corners``. + """ + if error := self._no_sketch(): + return error + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"ids": self._corner_ids("Fillet", corners), "corners": corners}, + ) + + async def add_sketch_chamfer( + self, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Mock bevelling sketch corners: one id per corner. + + Args: + corners (list[list[float]]): ``[x, y]`` sketch mm. + distance (float): Distance along the first side, mm. + distance2 (float | None): Distance along the second side, mm. + angle (float | None): Angle from the first side, degrees. + + Returns: + AdapterResult[dict[str, Any]]: ``ids`` and ``corners``. + """ + if error := self._no_sketch(): + return error + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"ids": self._corner_ids("Chamfer", corners), "corners": corners}, + ) + + async def add_slot( + self, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, + ) -> AdapterResult[str]: + """Mock drawing a slot: a new id; an arc slot needs its centre. + + Args: + kind (str): ``straight`` or ``arc``. + width (float): Slot width, mm. + start (list[float]): First centre (straight) or start (arc). + end (list[float]): Second centre (straight) or end (arc). + center (list[float] | None): The arc's centre (arc). + + Returns: + AdapterResult[str]: The slot's id. + """ + if error := self._no_sketch(): + return error + if kind == "arc" and center is None: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="An arc slot needs its center" + ) + slot_id = f"Slot_{random.randint(1000, 9999)}" + self._sketch_entity_ids.add(slot_id) + self._operation_count += 1 + return AdapterResult(status=AdapterResultStatus.SUCCESS, data=slot_id) + + async def _change_at(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Mock trim or extend: the segment count, unchanged.""" + if error := self._no_sketch(): + return error + self._operation_count += 1 + count = len(self._sketch_entity_ids) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"point": point, "segments_before": count, "segments_after": count}, + ) + + async def sketch_trim(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Mock trimming at a point. + + Args: + point (list[float]): ``[x, y]`` sketch mm. + + Returns: + AdapterResult[dict[str, Any]]: ``point`` and the segment counts. + """ + return await self._change_at(point) + + async def sketch_extend(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + """Mock extending at a point. + + Args: + point (list[float]): ``[x, y]`` sketch mm. + + Returns: + AdapterResult[dict[str, Any]]: ``point`` and the segment counts. + """ + return await self._change_at(point) + + async def set_construction_geometry( + self, entities: list[str], construction: bool = True + ) -> AdapterResult[dict[str, Any]]: + """Mock setting construction geometry: known ids only. + + Args: + entities (list[str]): Sketch entity ids. + construction (bool): Construction or normal. + + Returns: + AdapterResult[dict[str, Any]]: ``entities`` and ``construction``. + """ + if error := self._no_sketch(): + return error + unknown = [e for e in entities if e not in self._sketch_entity_ids] + if unknown: + return AdapterResult( + status=AdapterResultStatus.ERROR, + error=( + f"Unknown sketch entity '{unknown[0]}'. Use the ids the " + "sketch tools returned." + ), + ) + self._operation_count += 1 + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={ + "entities": dict.fromkeys(entities, construction), + "construction": construction, + }, + ) + async def add_polygon( self, center_x: float, diff --git a/src/solidworks_mcp/adapters/solidworks/sketch.py b/src/solidworks_mcp/adapters/solidworks/sketch.py index 96aa934f..aa54f843 100644 --- a/src/solidworks_mcp/adapters/solidworks/sketch.py +++ b/src/solidworks_mcp/adapters/solidworks/sketch.py @@ -10,6 +10,7 @@ from .. import sw_type_info as _sw_type_info from ..base import AdapterResult, AdapterResultStatus from .com_utils import as_list, double_array +from .features import _null_callout # swConstraintType_e values per the official SolidWorks API enum docs # (SolidWorks.Interop.swconst). The legacy IModelDoc2.SketchAddConstraints @@ -30,6 +31,10 @@ "collinear": 27, # swConstraintType_COLINEAR (single-l spelling) } +#: ``swTangentArcTypes_e.swForward``: a tangent arc that carries on in the +#: direction the entity it starts from was going. +_TANGENT_FORWARD = 1 + # Relations that take a third entity (the centerline of symmetry for now). # All other relations reject a non-null ``entity3``. _THREE_ENTITY_RELATIONS: frozenset[str] = frozenset({"symmetric"}) @@ -119,9 +124,9 @@ async def add_circle( return _add_circle_impl(self, center_x, center_y, radius) async def add_rectangle( - self, x1: float, y1: float, x2: float, y2: float + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False ) -> AdapterResult[str]: - return _add_rectangle_impl(self, x1, y1, x2, y2) + return _add_rectangle_impl(self, x1, y1, x2, y2, from_center) async def add_arc( self, @@ -131,8 +136,12 @@ async def add_arc( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: - return _add_arc_impl(self, center_x, center_y, start_x, start_y, end_x, end_y) + return _add_arc_impl( + self, center_x, center_y, start_x, start_y, end_x, end_y, kind, through + ) async def add_spline(self, points: list[dict[str, float]]) -> AdapterResult[str]: return _add_spline_impl(self, points) @@ -233,6 +242,41 @@ async def check_sketch_fully_defined( ) -> AdapterResult[dict[str, Any]]: return _check_sketch_fully_defined_impl(self, sketch_name) + async def add_sketch_fillet( + self, corners: list[list[float]], radius: float + ) -> AdapterResult[dict[str, Any]]: + return _add_sketch_fillet_impl(self, corners, radius) + + async def add_sketch_chamfer( + self, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, + ) -> AdapterResult[dict[str, Any]]: + return _add_sketch_chamfer_impl(self, corners, distance, distance2, angle) + + async def add_slot( + self, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, + ) -> AdapterResult[str]: + return _add_slot_impl(self, kind, width, start, end, center) + + async def sketch_trim(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + return _sketch_trim_impl(self, point) + + async def sketch_extend(self, point: list[float]) -> AdapterResult[dict[str, Any]]: + return _sketch_extend_impl(self, point) + + async def set_construction_geometry( + self, entities: list[str], construction: bool = True + ) -> AdapterResult[dict[str, Any]]: + return _set_construction_geometry_impl(self, entities, construction) + def _select_sketch_plane(adapter: Any, plane: str) -> None: """Select the reference plane a new sketch opens on. @@ -596,12 +640,18 @@ def _circle_operation() -> str: def _add_rectangle_impl( - adapter: Any, x1: float, y1: float, x2: float, y2: float + adapter: Any, + x1: float, + y1: float, + x2: float, + y2: float, + from_center: bool = False, ) -> AdapterResult[str]: - """Add a corner-defined rectangle to the active sketch. + """Add a rectangle to the active sketch, from two corners or its centre. - Calls ``SketchManager.CreateCornerRectangle`` which returns an array of - four line entities. The array is registered as a single composite entity. + Calls ``SketchManager.CreateCornerRectangle`` (or, with ``from_center``, + ``CreateCenterRectangle``), which returns an array of four line + entities. The array is registered as a single composite entity. Args: adapter: A ``PyWin32Adapter`` with an open sketch. @@ -609,6 +659,8 @@ def _add_rectangle_impl( y1: First corner Y coordinate in **millimetres**. x2: Opposite corner X coordinate in **millimetres**. y2: Opposite corner Y coordinate in **millimetres**. + from_center: When true, ``x1``/``y1`` is the centre and ``x2``/``y2`` + a corner. Returns: AdapterResult[str]: On success, ``data`` is the composite entity ID @@ -635,9 +687,12 @@ def _rectangle_operation() -> str: Raises: Exception: If ``CreateCornerRectangle`` returns ``None``. """ - lines = adapter.currentSketchManager.CreateCornerRectangle( - x1 / 1000.0, y1 / 1000.0, 0, x2 / 1000.0, y2 / 1000.0, 0 + create = ( + adapter.currentSketchManager.CreateCenterRectangle + if from_center + else adapter.currentSketchManager.CreateCornerRectangle ) + lines = create(x1 / 1000.0, y1 / 1000.0, 0, x2 / 1000.0, y2 / 1000.0, 0) if not lines: raise Exception("Failed to create rectangle") entity_id = cast(str, adapter._register_sketch_entity("Rectangle", lines)) @@ -646,8 +701,7 @@ def _rectangle_operation() -> str: # geometric centre from later. Stash it now so the rectangle ID is a # valid seed for ``sketch_circular_pattern``. adapter._sketch_entity_centers[entity_id] = ( - (x1 + x2) / 2.0, - (y1 + y2) / 2.0, + (x1, y1) if from_center else ((x1 + x2) / 2.0, (y1 + y2) / 2.0) ) return entity_id @@ -665,12 +719,17 @@ def _add_arc_impl( start_y: float, end_x: float, end_y: float, + kind: str = "center", + through: tuple[float, float] | None = None, ) -> AdapterResult[str]: """Add a circular arc to the active sketch. - Calls ``SketchManager.CreateArc`` with a counter-clockwise direction - flag (``1``). All coordinates must lie in the sketch plane; the Z - component is always forced to ``0``. + ``kind`` picks the call: ``center`` is ``SketchManager.CreateArc`` with a + counter-clockwise direction flag (``1``); ``three_point`` is + ``Create3PointArc`` from start to end through ``through``; ``tangent`` + is ``CreateTangentArc`` from ``start`` (the end of an existing entity) + to ``end``, leaving tangent to that entity (``swForward``, 1). All + coordinates lie in the sketch plane; the Z component is always ``0``. Args: adapter: A ``PyWin32Adapter`` with an open sketch. @@ -680,6 +739,8 @@ def _add_arc_impl( start_y: Arc start point Y in **millimetres**. end_x: Arc end point X in **millimetres**. end_y: Arc end point Y in **millimetres**. + kind: ``center`` (the default), ``three_point`` or ``tangent``. + through: For ``three_point``, a point on the arc, ``(x, y)`` mm. Returns: AdapterResult[str]: On success, ``data`` is the registered entity ID @@ -711,18 +772,21 @@ def _arc_operation() -> str: Raises: Exception: If ``CreateArc`` returns ``None``. """ - arc = adapter.currentSketchManager.CreateArc( - center_x / 1000.0, - center_y / 1000.0, - 0, - start_x / 1000.0, - start_y / 1000.0, - 0, - end_x / 1000.0, - end_y / 1000.0, - 0, - 1, - ) + manager = adapter.currentSketchManager + start = (start_x / 1000.0, start_y / 1000.0, 0) + end = (end_x / 1000.0, end_y / 1000.0, 0) + if kind == "three_point": + if through is None: + raise Exception("A three_point arc needs a through point") + arc = manager.Create3PointArc( + *start, *end, through[0] / 1000.0, through[1] / 1000.0, 0 + ) + elif kind == "tangent": + arc = manager.CreateTangentArc(*start, *end, _TANGENT_FORWARD) + else: + arc = manager.CreateArc( + center_x / 1000.0, center_y / 1000.0, 0, *start, *end, 1 + ) if not arc: raise Exception("Failed to create arc") return adapter._register_sketch_entity("Arc", arc) # type: ignore[no-any-return] @@ -2942,3 +3006,369 @@ def _get_sketch_payload() -> dict[str, Any]: "check_sketch_fully_defined", _get_sketch_payload ), ) + + +# --- Sketch essentials (queue item 32) --------------------------------------- +# Corners, slots, trim and extend, and construction geometry. Coordinates are +# sketch mm, as for every other sketch tool. + +#: How close (mm) a corner given by the agent must be to a sketch point. +_CORNER_TOLERANCE_MM = 0.01 +#: ``swConstrainedCornerAction_e.swConstrainedCornerKeepGeometry``: never ask. +#: ``swConstrainedCornerInteract`` (0) can open a dialog and stall the run. +_KEEP_CONSTRAINED_CORNERS = 1 +#: ``swSketchChamferType_e``. +_CHAMFER_DISTANCE_ANGLE = 0 +_CHAMFER_DISTANCE_DISTANCE = 1 +_CHAMFER_DISTANCE_EQUAL = 2 +#: ``swSketchSlotCreationType_e`` by our ``kind``. +_SLOT_CREATION = {"straight": 0, "arc": 2} +#: ``swSketchSlotLengthType_e.swSketchSlotLengthType_CenterCenter``. +_SLOT_CENTER_TO_CENTER = 0 +#: ``CreateSketchSlot``'s ``CenterArcDirection``: counter-clockwise. +_SLOT_COUNTER_CLOCKWISE = 1 +#: ``swSketchTrimChoice_e.swSketchTrimClosest``. +_TRIM_CLOSEST = 0 + + +def _active_sketch(adapter: Any) -> Any: + """The open sketch, flagged so its zero-argument methods are methods.""" + return _sw_type_info.flagged(adapter.currentSketchManager.ActiveSketch, "ISketch") + + +def _segment_count(adapter: Any) -> int: + """How many segments the open sketch has.""" + sketch = _active_sketch(adapter) + return len(as_list(adapter._attempt(lambda: sketch.GetSketchSegments(), None))) + + +def _to_model_space(adapter: Any, point_mm: list[float]) -> list[float]: + """A point in the open sketch (mm) in model space (metres). + + The inverse of ``ModelToSketchTransform``: ``SketchTrim``, + ``SketchExtend`` and ``SelectByID2`` take model coordinates. + """ + app = _sw_type_info.flagged(adapter.swApp, "ISldWorks") + math_utility = _sw_type_info.flagged(app.GetMathUtility(), "IMathUtility") + point = _sw_type_info.flagged( + math_utility.CreatePoint( + double_array([point_mm[0] / 1000.0, point_mm[1] / 1000.0, 0.0]) + ), + "IMathPoint", + ) + sketch = _active_sketch(adapter) + to_sketch = _sw_type_info.flagged(sketch.ModelToSketchTransform, "IMathTransform") + moved = _sw_type_info.flagged( + point.MultiplyTransform(to_sketch.Inverse()), "IMathPoint" + ) + return [float(v) for v in as_list(moved.ArrayData)[:3]] + + +def _corner_points(adapter: Any, corners: list[list[float]]) -> list[Any]: + """The open sketch's point at each corner, every one found before any change. + + Raises: + Exception: Naming the first corner with no sketch point within + ``_CORNER_TOLERANCE_MM``. + """ + sketch = _active_sketch(adapter) + points = as_list(adapter._attempt(lambda: sketch.GetSketchPoints2(), None)) + found = [] + for corner in corners: + match = next( + ( + point + for point in points + if abs(float(point.X) * 1000.0 - corner[0]) <= _CORNER_TOLERANCE_MM + and abs(float(point.Y) * 1000.0 - corner[1]) <= _CORNER_TOLERANCE_MM + ), + None, + ) + if match is None: + raise Exception( + f"No sketch point at corner [{corner[0]:g}, {corner[1]:g}] mm in " + "the open sketch" + ) + found.append(match) + return found + + +def _select_data(adapter: Any, mark: int = 0) -> Any: + """An ``ISelectData`` carrying ``mark``, for ``Select4``.""" + sel_mgr = adapter.currentModel.SelectionManager + adapter._attempt( + lambda: _sw_type_info.flag_methods(sel_mgr, "ISelectionMgr"), default=0 + ) + data = sel_mgr.CreateSelectData() + data.Mark = mark + return data + + +def _treat_corners( + adapter: Any, + operation: str, + corners: list[list[float]], + prefix: str, + make: Any, +) -> AdapterResult[dict[str, Any]]: + """Fillet or chamfer each corner on its own; one registered id per corner. + + Args: + adapter: A ``PyWin32Adapter`` with an open sketch. + operation: The operation name, for the error boundary and the pause. + corners: ``[x, y]`` sketch mm, each where two entities meet. + prefix: The id prefix, ``Fillet`` or ``Chamfer``. + make: Called with the sketch manager once a corner is selected; + returns the new segment, or nothing when SolidWorks refused. + """ + if not adapter.currentSketchManager: + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def run() -> dict[str, Any]: + points = _corner_points(adapter, corners) + manager = _sw_type_info.flagged(adapter.currentSketchManager, "ISketchManager") + ids = [] + try: + for corner, point in zip(corners, points, strict=True): + adapter.currentModel.ClearSelection2(True) + where = f"[{corner[0]:g}, {corner[1]:g}] mm" + if not point.Select4(False, _select_data(adapter)): + raise Exception(f"Couldn't select the corner at {where}") + segment = make(manager) + if not segment: + # A point need not be a corner: a centre rectangle's + # centre point is a sketch point (seen live, 2026-11-19). + raise Exception( + f"SolidWorks refused the {prefix.lower()} at corner {where}: " + "it isn't where two entities meet" + ) + ids.append(adapter._register_sketch_entity(prefix, segment)) + finally: + adapter.currentModel.ClearSelection2(True) + return {"ids": ids, "corners": corners} + + return cast( + AdapterResult[dict[str, Any]], adapter._handle_com_operation(operation, run) + ) + + +def _add_sketch_fillet_impl( + adapter: Any, corners: list[list[float]], radius: float +) -> AdapterResult[dict[str, Any]]: + """Round each corner to ``radius`` mm (``ISketchManager.CreateFillet``).""" + return _treat_corners( + adapter, + "add_sketch_fillet", + corners, + "Fillet", + lambda manager: manager.CreateFillet( + radius / 1000.0, _KEEP_CONSTRAINED_CORNERS + ), + ) + + +def _add_sketch_chamfer_impl( + adapter: Any, + corners: list[list[float]], + distance: float, + distance2: float | None = None, + angle: float | None = None, +) -> AdapterResult[dict[str, Any]]: + """Bevel each corner (``ISketchManager.CreateChamfer``). + + ``distance`` alone is equal distances; with ``distance2``, two + distances; with ``angle`` (degrees), a distance and an angle. + """ + if angle is not None: + kind, second = _CHAMFER_DISTANCE_ANGLE, math.radians(angle) + elif distance2 is not None: + kind, second = _CHAMFER_DISTANCE_DISTANCE, distance2 / 1000.0 + else: + kind, second = _CHAMFER_DISTANCE_EQUAL, distance / 1000.0 + return _treat_corners( + adapter, + "add_sketch_chamfer", + corners, + "Chamfer", + lambda manager: manager.CreateChamfer(kind, distance / 1000.0, second), + ) + + +def _add_slot_impl( + adapter: Any, + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None = None, +) -> AdapterResult[str]: + """Draw a straight or arc slot (``ISketchManager.CreateSketchSlot``). + + A straight slot runs between its two arc centres, ``start`` and ``end``. + An arc slot follows the arc about ``center`` from ``start`` to ``end``, + counter-clockwise. Length is centre to centre; no dimensions are added. + """ + if not adapter.currentSketchManager: + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def run() -> str: + if kind == "arc": + if center is None: + raise Exception("An arc slot needs its center") + points = (center, start, end) + else: + points = (start, end, end) + manager = _sw_type_info.flagged(adapter.currentSketchManager, "ISketchManager") + coordinates = [c for p in points for c in (p[0] / 1000.0, p[1] / 1000.0, 0.0)] + slot = manager.CreateSketchSlot( + _SLOT_CREATION[kind], + _SLOT_CENTER_TO_CENTER, + width / 1000.0, + *coordinates, + _SLOT_COUNTER_CLOCKWISE, + False, + ) + if not slot: + raise Exception("SolidWorks refused the slot") + return cast(str, adapter._register_sketch_entity("Slot", slot)) + + return cast(AdapterResult[str], adapter._handle_com_operation("add_slot", run)) + + +def _segment_lengths(adapter: Any) -> float: + """The total length (mm) of the open sketch's segments.""" + sketch = _active_sketch(adapter) + segments = as_list(adapter._attempt(lambda: sketch.GetSketchSegments(), None)) + return sum( + float(_sw_type_info.flagged(segment, "ISketchSegment").GetLength()) * 1000.0 + for segment in segments + ) + + +def _change_at_point( + adapter: Any, + operation: str, + point: list[float], + verb: str, + change: Any, + grows: bool, +) -> AdapterResult[dict[str, Any]]: + """Select the sketch entity at ``point`` and trim or extend it there. + + Whether it worked is measured, not read from the call: ``SketchTrim`` + returned ``False`` live (2026-11-19) after trimming correctly, and a + retry then trimmed the next entity too. A trim always shortens the + sketch's total segment length and an extension always lengthens it. + + Args: + adapter: A ``PyWin32Adapter`` with an open sketch. + operation: The operation name. + point: ``[x, y]`` sketch mm on the entity. + verb: ``trim`` or ``extend``, for the messages. + change: Called with the sketch manager and the model-space point + (metres), with the entity selected. + grows: ``True`` when the change adds length (extend). + """ + if not adapter.currentSketchManager: + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def run() -> dict[str, Any]: + where = f"[{point[0]:g}, {point[1]:g}] mm" + before = _segment_count(adapter) + length_before = _segment_lengths(adapter) + model_point = _to_model_space(adapter, point) + manager = _sw_type_info.flagged(adapter.currentSketchManager, "ISketchManager") + adapter.currentModel.ClearSelection2(True) + try: + picked = adapter.currentModel.Extension.SelectByID2( + "", "SKETCHSEGMENT", *model_point, False, 0, _null_callout(), 0 + ) + if not picked: + raise Exception(f"No sketch entity at {where} in the open sketch") + change(manager, model_point) + finally: + adapter.currentModel.ClearSelection2(True) + length_change = _segment_lengths(adapter) - length_before + worked = length_change > 1e-6 if grows else length_change < -1e-6 + if not worked: + raise Exception(f"SolidWorks refused to {verb} at {where}") + return { + "point": point, + "segments_before": before, + "segments_after": _segment_count(adapter), + "length_change_mm": round(length_change, 4), + } + + return cast( + AdapterResult[dict[str, Any]], adapter._handle_com_operation(operation, run) + ) + + +def _sketch_trim_impl( + adapter: Any, point: list[float] +) -> AdapterResult[dict[str, Any]]: + """Remove the piece of an entity nearest ``point`` (``SketchTrim``, closest).""" + return _change_at_point( + adapter, + "sketch_trim", + point, + "trim", + lambda manager, at: manager.SketchTrim(_TRIM_CLOSEST, *at), + grows=False, + ) + + +def _sketch_extend_impl( + adapter: Any, point: list[float] +) -> AdapterResult[dict[str, Any]]: + """Lengthen the entity at ``point`` from its nearer end (``SketchExtend``).""" + return _change_at_point( + adapter, + "sketch_extend", + point, + "extend", + lambda manager, at: manager.SketchExtend(*at), + grows=True, + ) + + +def _set_construction_geometry_impl( + adapter: Any, entities: list[str], construction: bool = True +) -> AdapterResult[dict[str, Any]]: + """Make entities construction geometry, or normal again, and read it back. + + Sets ``ISketchSegment.ConstructionGeometry`` on every segment of every + id (a rectangle's or polygon's id holds several). Setting a property is + idempotent, unlike ``CreateConstructionGeometry``, which toggles. + """ + if not adapter.currentSketchManager: + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def run() -> dict[str, Any]: + for entity_id in entities: + if entity_id not in adapter._sketch_entities: + raise Exception( + f"Unknown sketch entity '{entity_id}'. Use the ids the " + "sketch tools returned." + ) + states = {} + for entity_id in entities: + entity = adapter._sketch_entities[entity_id] + segments = entity if isinstance(entity, (list, tuple)) else [entity] + read = [] + for segment in segments: + segment.ConstructionGeometry = construction + read.append(bool(segment.ConstructionGeometry)) + states[entity_id] = all(read) if construction else any(read) + wrong = [e for e, state in states.items() if state != construction] + if wrong: + kind = "construction" if construction else "normal" + raise Exception( + f"SolidWorks didn't change {', '.join(wrong)} to {kind} geometry" + ) + return {"entities": states, "construction": construction} + + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation("set_construction_geometry", run), + ) diff --git a/src/solidworks_mcp/skills/__init__.py b/src/solidworks_mcp/skills/__init__.py index dc8d4768..5cb1cb4c 100644 --- a/src/solidworks_mcp/skills/__init__.py +++ b/src/solidworks_mcp/skills/__init__.py @@ -24,6 +24,7 @@ `add_circle`, ...), `exit_sketch`, then the feature (`create_extrusion`, \ `create_cut_extrude`, `create_revolve`). Features use the sketch `sketch_name` \ names, or the one you closed last. +- Fillets and chamfers on a solid go last: `add_fillet` and `add_chamfer` after every boss and cut, at the end of the feature tree. - Inputs are millimetres and degrees unless a field says metres. - A tool's success does not prove the geometry is right: finish a build with \ `verify_model`, giving the size, volume or counts you expect. diff --git a/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md b/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md index 0631e67e..4b0d4eb0 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md @@ -43,8 +43,13 @@ A solid feature always comes from a closed sketch: Each takes `sketch_name`; without it, the sketch you closed last is used. `create_revolve` turns about the sketch's centreline, or about the reference axis `axis_entity` names. -6. Then edge treatments: `select_face_edges`, then `add_fillet` or - `add_chamfer` with empty `edge_names`. +6. Last, once every boss and cut is in: edge treatments, + `select_face_edges`, then `add_fillet` or `add_chamfer` with empty + `edge_names`. Fillets and chamfers belong at the end of the feature + tree: a later cut or boss can break them, and rounded edges are harder + to pick. `add_sketch_fillet` and `add_sketch_chamfer` round or bevel a + 2D profile's corners inside a sketch; a solid's edges get `add_fillet` + and `add_chamfer`, last. 7. Finish with `verify_model` (see "Check the result"). 8. `set_material`, then `save_file` with a `file_path`. diff --git a/src/solidworks_mcp/tools/error_classifier.py b/src/solidworks_mcp/tools/error_classifier.py index bfac4f4d..feb7e60c 100644 --- a/src/solidworks_mcp/tools/error_classifier.py +++ b/src/solidworks_mcp/tools/error_classifier.py @@ -240,6 +240,21 @@ def matches(self, message: str, hresult: int | None) -> bool: r"paper_size must be one of", ), ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "Points are [x, y] in sketch mm: a corner where two entities meet " + "(fillet, chamfer), or a point on an entity (trim, extend). Ids are " + "the ones the sketch tools returned in this sketch." + ), + patterns=( + r"No sketch point at corner", + r"SolidWorks refused the (fillet|chamfer) at corner", + r"No sketch entity at \[", + r"SolidWorks refused to (trim|extend) at", + r"Unknown sketch entity '", + ), + ), ErrorRule( error_type="not_found", hint=( diff --git a/src/solidworks_mcp/tools/sketching.py b/src/solidworks_mcp/tools/sketching.py index ee2eae17..db8f56b2 100644 --- a/src/solidworks_mcp/tools/sketching.py +++ b/src/solidworks_mcp/tools/sketching.py @@ -4,10 +4,11 @@ lines, circles, rectangles, arcs, and constraints. """ -from typing import Any, TypeVar +import math +from typing import Annotated, Any, Literal, TypeVar from fastmcp import FastMCP -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, model_validator from ..adapters.base import SolidWorksAdapter from .input_compat import CompatInput @@ -149,6 +150,7 @@ class AddRectangleInput(CompatInput): Attributes: construction (bool): The construction value. + from_center (bool): ``x1``/``y1`` is the centre, ``x2``/``y2`` a corner. corner1_x (float | None): The corner1 x value. corner1_y (float | None): The corner1 y value. corner2_x (float | None): The corner2 x value. @@ -176,6 +178,11 @@ class AddRectangleInput(CompatInput): corner2_x: float | None = Field(default=None, description="Corner 2 X alias") corner2_y: float | None = Field(default=None, description="Corner 2 Y alias") construction: bool = Field(default=False, description="Construction geometry flag") + from_center: bool = Field( + default=False, + description="x1, y1 is the centre and x2, y2 a corner (a rectangle centred " + "there)", + ) def model_post_init(self, __context: Any) -> None: """Provide model post init support for the add rectangle input. @@ -205,20 +212,52 @@ class AddArcInput(BaseModel): """Input schema for adding an arc to sketch. Attributes: - center_x (float): The center x value. - center_y (float): The center y value. + kind (str): ``center``, ``three_point`` or ``tangent``. + center_x (float | None): The center x value (``center``). + center_y (float | None): The center y value (``center``). end_x (float): The end x value. end_y (float): The end y value. start_x (float): The start x value. start_y (float): The start y value. + through_x (float | None): A point on the arc, x (``three_point``). + through_y (float | None): A point on the arc, y (``three_point``). """ - center_x: float = Field(description="Arc center X coordinate in mm") - center_y: float = Field(description="Arc center Y coordinate in mm") + kind: Literal["center", "three_point", "tangent"] = Field( + default="center", + description="center: centre, start and end; three_point: start, end and a " + "point it passes through; tangent: from the end of an existing entity, " + "tangent to it", + ) + center_x: float | None = Field( + default=None, description="Arc center X in mm (kind center)" + ) + center_y: float | None = Field( + default=None, description="Arc center Y in mm (kind center)" + ) start_x: float = Field(description="Arc start point X coordinate in mm") start_y: float = Field(description="Arc start point Y coordinate in mm") end_x: float = Field(description="Arc end point X coordinate in mm") end_y: float = Field(description="Arc end point Y coordinate in mm") + through_x: float | None = Field( + default=None, description="X of a point the arc passes through (three_point)" + ) + through_y: float | None = Field( + default=None, description="Y of a point the arc passes through (three_point)" + ) + + @model_validator(mode="after") + def _points_for_kind(self) -> "AddArcInput": + """Each kind needs its own points.""" + needed = { + "center": ("center_x", "center_y"), + "three_point": ("through_x", "through_y"), + "tangent": (), + }[self.kind] + missing = [name for name in needed if getattr(self, name) is None] + if missing: + raise ValueError(f"a {self.kind} arc needs {' and '.join(missing)}") + return self class AddSplineInput(BaseModel): @@ -371,6 +410,150 @@ def model_post_init(self, __context: Any) -> None: raise ValueError("each point must be [x, y, z] in mm") +#: A point in the open sketch, ``[x, y]`` in mm. +SketchPoint = Annotated[list[float], Field(min_length=2, max_length=2)] + + +class AddSketchFilletInput(CompatInput): + """Input schema for rounding sketch corners. + + Attributes: + corners (list[list[float]]): Corners, ``[x, y]`` sketch mm. + radius (float): Fillet radius in mm. + """ + + corners: list[SketchPoint] = Field( + min_length=1, + description="Corners to round, each [x, y] in sketch mm where two " + "entities meet, e.g. a rectangle's corner", + ) + radius: float = Field(gt=0, description="Fillet radius in mm") + + +class AddSketchChamferInput(CompatInput): + """Input schema for bevelling sketch corners. + + Attributes: + corners (list[list[float]]): Corners, ``[x, y]`` sketch mm. + distance (float): Distance along the first side, mm. + distance2 (float | None): Distance along the second side, mm. + angle (float | None): Angle from the first side, degrees. + """ + + corners: list[SketchPoint] = Field( + min_length=1, + description="Corners to bevel, each [x, y] in sketch mm where two entities meet", + ) + distance: float = Field(gt=0, description="Distance along each side in mm") + distance2: float | None = Field( + default=None, gt=0, description="A different distance along the second side" + ) + angle: float | None = Field( + default=None, + gt=0, + lt=90, + description="Angle in degrees from the first side, with `distance`", + ) + + @model_validator(mode="after") + def _one_way(self) -> "AddSketchChamferInput": + """``distance2`` and ``angle`` are two different chamfers: one at most.""" + if self.distance2 is not None and self.angle is not None: + raise ValueError("give distance2 or angle, not both") + return self + + +class AddSlotInput(CompatInput): + """Input schema for drawing a slot. + + Attributes: + kind (str): ``straight`` or ``arc``. + width (float): Slot width in mm. + start (list[float]): Straight: first end's centre; arc: start on the arc. + end (list[float]): Straight: second end's centre; arc: end on the arc. + center (list[float] | None): Arc: the centre of the arc it follows. + """ + + kind: Literal["straight", "arc"] = Field( + default="straight", description="straight, or arc (follows an arc)" + ) + width: float = Field(gt=0, description="Slot width in mm") + start: SketchPoint = Field( + description="[x, y] mm: a straight slot's first end centre, or where an " + "arc slot starts on its arc" + ) + end: SketchPoint = Field( + description="[x, y] mm: a straight slot's second end centre, or where an " + "arc slot ends (counter-clockwise from start)" + ) + center: SketchPoint | None = Field( + default=None, description="[x, y] mm, an arc slot's arc centre" + ) + + @model_validator(mode="after") + def _points(self) -> "AddSlotInput": + """An arc slot needs its centre; the two ends must differ.""" + if self.kind == "arc" and self.center is None: + raise ValueError("an arc slot needs center") + if self.start == self.end: + raise ValueError("start and end must differ") + return self + + +class SketchPointInput(CompatInput): + """Input schema for trimming or extending at a point. + + Attributes: + point (list[float]): ``[x, y]`` sketch mm on the entity. + """ + + point: SketchPoint = Field( + description="[x, y] in sketch mm on the entity: on the piece to remove " + "(trim), or near the end to lengthen (extend)" + ) + + +class SetConstructionGeometryInput(CompatInput): + """Input schema for making entities construction geometry. + + Attributes: + entities (list[str]): Sketch entity ids. + construction (bool): Construction (``True``) or normal (``False``). + """ + + entities: list[Annotated[str, Field(min_length=1)]] = Field( + min_length=1, description="Entity ids from the sketch tools, e.g. Line_3" + ) + construction: bool = Field( + default=True, description="true for construction geometry, false for normal" + ) + + +def slot_area( + kind: str, + width: float, + start: list[float], + end: list[float], + center: list[float] | None, +) -> float: + """A slot's area in mmยฒ: its centreline's length times its width, plus + the two half-circle ends (one circle of the width's diameter). + + An arc slot's centreline runs counter-clockwise about ``center`` from + ``start`` to ``end``. + """ + ends = math.pi * (width / 2.0) ** 2 + if kind == "arc" and center is not None: + radius = math.dist(center, start) + turn = math.atan2(end[1] - center[1], end[0] - center[0]) - math.atan2( + start[1] - center[1], start[0] - center[0] + ) + length = radius * (turn % (2 * math.pi)) + else: + length = math.dist(start, end) + return length * width + ends + + async def register_sketching_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: dict[str, Any] ) -> int: @@ -403,6 +586,17 @@ async def register_sketching_tools( # SolidWorks' name -> the name asked for. names_on_exit: dict[str, str] = {} + async def _honour_construction(entity_id: Any, construction: bool) -> None: + """Make a new entity construction geometry when ``construction`` asks. + + The drawing calls themselves draw normal geometry on SolidWorks, so a + tool's ``construction`` flag is applied afterwards, by id. + """ + if not construction or not entity_id: + return + made = await adapter.set_construction_geometry([str(entity_id)], True) + require_success(made, context="Failed to make it construction geometry") + @mcp.tool() async def create_sketch(input_data: CreateSketchInput) -> dict[str, Any]: """Open a new sketch on a plane or a flat face of the active part, ready for lines, circles and other sketch entities. @@ -506,6 +700,7 @@ async def add_line(input_data: AddLineInput) -> dict[str, Any]: if isinstance(result.data, dict) else result.data ) + await _honour_construction(line_id, input_data.construction) x1, y1 = input_data.x1 or 0.0, input_data.y1 or 0.0 x2, y2 = input_data.x2 or 0.0, input_data.y2 or 0.0 return { @@ -556,6 +751,7 @@ async def add_circle(input_data: AddCircleInput) -> dict[str, Any]: if isinstance(result.data, dict) else result.data ) + await _honour_construction(circle_id, input_data.construction) return { "status": "success", "message": f"Added circle at ({input_data.center_x}, {input_data.center_y}) with radius {input_data.radius}mm", @@ -586,7 +782,15 @@ async def add_rectangle(input_data: AddRectangleInput) -> dict[str, Any]: dict[str, Any]: The rectangle added. """ input_data = normalize_input(input_data, AddRectangleInput) - if hasattr(adapter, "add_sketch_rectangle"): + if input_data.from_center: + result = await adapter.add_rectangle( + input_data.x1, # type: ignore[arg-type] + input_data.y1, # type: ignore[arg-type] + input_data.x2, # type: ignore[arg-type] + input_data.y2, # type: ignore[arg-type] + True, + ) + elif hasattr(adapter, "add_sketch_rectangle"): result = await adapter.add_sketch_rectangle( input_data.x1, input_data.y1, @@ -608,8 +812,12 @@ async def add_rectangle(input_data: AddRectangleInput) -> dict[str, Any]: if isinstance(result.data, dict) else result.data ) + await _honour_construction(rect_id, input_data.construction) rx1, ry1 = input_data.x1 or 0.0, input_data.y1 or 0.0 rx2, ry2 = input_data.x2 or 0.0, input_data.y2 or 0.0 + if input_data.from_center: + # x1, y1 is the centre: the real corners mirror x2, y2 through it. + rx1, ry1 = 2 * rx1 - rx2, 2 * ry1 - ry2 width = abs(rx2 - rx1) height = abs(ry2 - ry1) @@ -618,6 +826,7 @@ async def add_rectangle(input_data: AddRectangleInput) -> dict[str, Any]: "message": f"Added rectangle from ({rx1}, {ry1}) to ({rx2}, {ry2})", "rectangle": { "id": rect_id, + "from_center": input_data.from_center, "corner1": {"x": rx1, "y": ry1}, "corner2": {"x": rx2, "y": ry2}, "construction": input_data.construction, @@ -699,38 +908,61 @@ async def check_sketch_fully_defined( @mcp.tool() async def add_arc(input_data: AddArcInput) -> dict[str, Any]: - """Draw a circular arc in the open sketch from its centre, start point and end point, in mm. - - Use it for rounded ends and curved edges of a profile. Needs: an open sketch - (`create_sketch`). Changes: adds an arc. Returns: `arc` with `id`, `center`, - `start_point` and `end_point`. Its `id` is what `add_sketch_constraint` and + """Draw a circular arc in the open sketch: from its centre, through three points, or tangent. + + Use it for rounded ends and curved edges of a profile. `kind` `center` (the + default) takes the centre, start and end, counter-clockwise; `three_point` + takes start, end and a point the arc passes through (`through_x`, + `through_y`); `tangent` starts at the end of an existing entity (`start`) and + leaves tangent to it. Needs: an open sketch (`create_sketch`). Changes: adds an + arc. Returns: `arc` with `id`, `kind`, `center`, `start_point` and + `end_point`. Its `id` is what `add_sketch_constraint` and `add_sketch_dimension` take. Args: - input_data: The arc. `center_x`, `center_y`, `start_x`, `start_y`, - `end_x` and `end_y` (mm) are all required. + input_data: The arc. `start_x`, `start_y`, `end_x` and `end_y` (mm) are + required; `center_x`, `center_y` for `center`; `through_x`, + `through_y` for `three_point`. Returns: dict[str, Any]: The arc added. """ input_data = normalize_input(input_data, AddArcInput) + through = ( + (input_data.through_x, input_data.through_y) + if input_data.through_x is not None and input_data.through_y is not None + else None + ) result = await adapter.add_arc( - input_data.center_x, - input_data.center_y, + input_data.center_x or 0.0, + input_data.center_y or 0.0, input_data.start_x, input_data.start_y, input_data.end_x, input_data.end_y, + input_data.kind, + through, ) require_success(result, context="Failed to add arc") arc_id = result.data + center = ( + {"x": input_data.center_x, "y": input_data.center_y} + if input_data.kind == "center" + else None + ) return { "status": "success", - "message": f"Added arc centered at ({input_data.center_x}, {input_data.center_y})", + "message": f"Added a {input_data.kind} arc from " + f"({input_data.start_x}, {input_data.start_y}) to " + f"({input_data.end_x}, {input_data.end_y})", "arc": { "id": arc_id, - "center": {"x": input_data.center_x, "y": input_data.center_y}, + "kind": input_data.kind, + "center": center, + "through": ( + {"x": through[0], "y": through[1]} if through is not None else None + ), "start_point": { "x": input_data.start_x, "y": input_data.start_y, @@ -1232,14 +1464,211 @@ async def sketch_convert_entities( "execution_time": result.execution_time, } - # Additional sketch tools can be added here in the future: - # - add_arc (3-point arc, center-point arc) - # - add_spline (free-form curves) - # - add_dimension (dimensional constraints) - # - add_relation (geometric constraints like parallel, perpendicular) - # - add_pattern (circular, linear patterns) - # - trim_entities (trim overlapping geometry) - # - mirror_entities (mirror sketch geometry) + @mcp.tool() + async def add_sketch_fillet(input_data: AddSketchFilletInput) -> dict[str, Any]: + """Round corners of the open sketch to a radius, picking each corner by its point. + + Use it for rounded corners of a 2D profile, such as a cut's outline; round a + solid's edges with `add_fillet` instead, last in the feature tree. Give + each corner's `[x, y]` in sketch mm, where two entities meet (for a rectangle, + its corners). Needs: an open sketch (`create_sketch`) with entities meeting at + each corner. Changes: each corner becomes an arc and the entities either side + are trimmed back to it. Returns: `fillet` with one `id` per corner, the + `corners` and the `radius`. A corner with no sketch point fails as + `invalid_input` and nothing changes. + + Args: + input_data: `corners` (a list of `[x, y]` mm) and `radius` (mm). + + Returns: + dict[str, Any]: The fillets added. + """ + input_data = normalize_input(input_data, AddSketchFilletInput) + result = await adapter.add_sketch_fillet(input_data.corners, input_data.radius) + require_success(result, context="Failed to round the sketch corners") + made: dict[str, Any] = result.data or {} + return { + "status": "success", + "message": f"Rounded {len(input_data.corners)} corner(s) to " + f"R{input_data.radius:g} mm", + "fillet": {**made, "radius": input_data.radius}, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def add_sketch_chamfer(input_data: AddSketchChamferInput) -> dict[str, Any]: + """Bevel corners of the open sketch, picking each corner by its point. + + Use it for bevelled corners of a 2D profile; bevel a solid's edges with + `add_chamfer` instead, last in the feature tree. `distance` alone cuts the same + distance along both sides; add `distance2` for a different second side, or + `angle` (degrees) for a distance and an angle. Needs: an open sketch with + entities meeting at each corner (`[x, y]` in sketch mm). Changes: each corner + becomes a line and the entities either side are trimmed back to it. Returns: + `chamfer` with one `id` per corner, the `corners` and the sizes. A corner + with no sketch point fails as `invalid_input` and nothing changes. + + Args: + input_data: `corners` and `distance` (mm) are required; `distance2` (mm) + or `angle` (degrees), not both. + + Returns: + dict[str, Any]: The chamfers added. + """ + input_data = normalize_input(input_data, AddSketchChamferInput) + result = await adapter.add_sketch_chamfer( + input_data.corners, + input_data.distance, + input_data.distance2, + input_data.angle, + ) + require_success(result, context="Failed to bevel the sketch corners") + made: dict[str, Any] = result.data or {} + return { + "status": "success", + "message": f"Bevelled {len(input_data.corners)} corner(s)", + "chamfer": { + **made, + "distance": input_data.distance, + "distance2": input_data.distance2, + "angle": input_data.angle, + }, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def add_slot(input_data: AddSlotInput) -> dict[str, Any]: + """Draw a slot in the open sketch: straight between two centres, or along an arc. + + Use it for adjustment slots and keyways, then cut it (`create_cut_extrude`). + A straight slot takes its two end centres, `start` and `end`. An arc slot + (`kind` `arc`) takes the `center` of the arc it follows and `start` and `end` + on that arc, counter-clockwise. Needs: an open sketch (`create_sketch`). + Changes: adds one closed slot. Returns: `slot` with its `id`, the points, the + `width` and its `area` (mmยฒ). + + Args: + input_data: `width` (mm), `start` and `end` (`[x, y]` mm) are required; + `kind` is `straight`; `center` for an arc slot. + + Returns: + dict[str, Any]: The slot added. + """ + input_data = normalize_input(input_data, AddSlotInput) + result = await adapter.add_slot( + input_data.kind, + input_data.width, + input_data.start, + input_data.end, + input_data.center, + ) + require_success(result, context="Failed to draw the slot") + area = slot_area( + input_data.kind, + input_data.width, + input_data.start, + input_data.end, + input_data.center, + ) + return { + "status": "success", + "message": f"Drew a {input_data.kind} slot {input_data.width:g} mm wide", + "slot": { + "id": result.data, + "kind": input_data.kind, + "start": input_data.start, + "end": input_data.end, + "center": input_data.center, + "width": input_data.width, + "area": round(area, 4), + }, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def sketch_trim(input_data: SketchPointInput) -> dict[str, Any]: + """Trim away the piece of a sketch entity at a point, back to where it meets others. + + Use it to clean up overlapping shapes into one profile, such as the arc inside + a keyhole. `point` (`[x, y]` sketch mm) is on the piece to remove; an entity + that meets nothing is removed whole. Needs: an open sketch with an entity at + the point. Changes: removes that piece. Returns: `trim` with the `point` and + the sketch's `segments_before` and `segments_after`. A trimmed entity's id may + no longer name a whole segment. Nothing at the point fails as `invalid_input`. + + Args: + input_data: `point`, `[x, y]` in sketch mm. + + Returns: + dict[str, Any]: The trim. + """ + input_data = normalize_input(input_data, SketchPointInput) + result = await adapter.sketch_trim(input_data.point) + require_success(result, context="Failed to trim the sketch") + return { + "status": "success", + "message": f"Trimmed at {input_data.point} mm", + "trim": result.data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def sketch_extend(input_data: SketchPointInput) -> dict[str, Any]: + """Lengthen a sketch entity from its end nearest a point until it meets the next entity. + + Use it to close a gap, such as lines that stop short of a circle. `point` + (`[x, y]` sketch mm) is on the entity, near the end to lengthen. Needs: an + open sketch with an entity at the point and another in its way. Changes: that + end moves to the next entity. Returns: `extend` with the `point` and the + segment counts. Nothing at the point, or nothing to reach, fails as + `invalid_input`. + + Args: + input_data: `point`, `[x, y]` in sketch mm. + + Returns: + dict[str, Any]: The extension. + """ + input_data = normalize_input(input_data, SketchPointInput) + result = await adapter.sketch_extend(input_data.point) + require_success(result, context="Failed to extend the sketch entity") + return { + "status": "success", + "message": f"Extended the entity at {input_data.point} mm", + "extend": result.data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def set_construction_geometry( + input_data: SetConstructionGeometryInput, + ) -> dict[str, Any]: + """Make sketch entities construction geometry, or normal again, by id. + + Use it for reference lines and circles a feature should ignore, such as a + line to dimension from or a bolt circle. Needs: an open sketch and ids the + sketch tools returned. Changes: each entity's construction setting (setting it + to what it already is changes nothing). Returns: `construction_geometry` with + each id's state. An unknown id fails as `invalid_input` and nothing changes. + + Args: + input_data: `entities` (ids) is required; `construction` is on. + + Returns: + dict[str, Any]: The entities' states. + """ + input_data = normalize_input(input_data, SetConstructionGeometryInput) + result = await adapter.set_construction_geometry( + input_data.entities, input_data.construction + ) + require_success(result, context="Failed to set construction geometry") + kind = "construction" if input_data.construction else "normal" + return { + "status": "success", + "message": f"{len(input_data.entities)} entity(ies) now {kind} geometry", + "construction_geometry": result.data, + "execution_time": result.execution_time, + } @mcp.tool() async def sketch_tutorial_simple_hole() -> dict[str, Any]: diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index b132ff4f..1af03008 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -316,6 +316,12 @@ def _deprecated(replacement: str | None) -> Support: "add_ellipse": _STABLE, "add_sketch_text": _STABLE, "set_sketch_text": _STABLE, + "add_sketch_fillet": _STABLE, + "add_sketch_chamfer": _STABLE, + "add_slot": _STABLE, + "sketch_trim": _STABLE, + "sketch_extend": _STABLE, + "set_construction_geometry": _STABLE, "add_line": _STABLE, "add_polygon": _STABLE, "add_rectangle": _STABLE, diff --git a/src/solidworks_mcp/tools/tool_hints.py b/src/solidworks_mcp/tools/tool_hints.py index dbdaffb6..2bd9287e 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -235,6 +235,12 @@ def _discards(title: str) -> ToolHints: "add_ellipse": _adds("Add Sketch Ellipse"), "add_sketch_text": _adds("Add Sketch Text"), "set_sketch_text": _sets("Set Sketch Text"), + "add_sketch_fillet": _adds("Add Sketch Fillet"), + "add_sketch_chamfer": _adds("Add Sketch Chamfer"), + "add_slot": _adds("Add Slot"), + "sketch_trim": _discards("Trim Sketch Entity"), + "sketch_extend": _adds("Extend Sketch Entity"), + "set_construction_geometry": _sets("Set Construction Geometry"), "add_sketch_constraint": _adds("Add Sketch Relation"), "add_sketch_dimension": _adds("Add Sketch Dimension"), "sketch_linear_pattern": _adds("Sketch Linear Pattern"), diff --git a/tests/integration/test_all_endpoints_harness.py b/tests/integration/test_all_endpoints_harness.py index 0348ec2d..c0d4805d 100644 --- a/tests/integration/test_all_endpoints_harness.py +++ b/tests/integration/test_all_endpoints_harness.py @@ -304,6 +304,12 @@ def test_sample_path_env_override_is_prioritized( }, "sketch_mirror": {"entity": "Line1", "mirror_line": "Line2"}, "sketch_offset": {"entity": "Line1", "distance": 5.0}, + "add_sketch_fillet": {"corners": [[-10.0, -10.0]], "radius": 2.0}, + "add_sketch_chamfer": {"corners": [[10.0, 10.0]], "distance": 2.0}, + "add_slot": {"start": [0.0, 0.0], "end": [20.0, 0.0], "width": 6.0}, + "sketch_trim": {"point": [0.0, 5.0]}, + "sketch_extend": {"point": [0.0, 5.0]}, + "set_construction_geometry": {"entities": ["Line1"]}, "sketch_tutorial_simple_hole": { "plane": "Front", "center_x": 0.0, diff --git a/tests/live/test_live_sw_sketch_essentials.py b/tests/live/test_live_sw_sketch_essentials.py new file mode 100644 index 00000000..222f0691 --- /dev/null +++ b/tests/live/test_live_sw_sketch_essentials.py @@ -0,0 +1,344 @@ +"""Sketch essentials (queue item 32), checked on real SolidWorks. + +One slotted bracket plate, built with every new sketch operation; after each +step ``verify_model`` checks the volume against the hand calculation. The +plate is built sharp and its edges are filleted and chamfered last, at the +end of the feature tree (the user's rule, 2026-11-19): + +1. A 120 x 80 mm plate drawn from its centre (``add_rectangle`` + ``from_center``), extruded 8 mm. A sketch fillet at the rectangle's + centre point is refused first: it is a sketch point, not a corner. +2. A straight slot and an arc slot (``add_slot``) cut through, in a sketch + with two lines across the plate made construction geometry, one by + ``add_line``'s ``construction`` (the fix) and one by + ``set_construction_geometry``: if either were normal geometry the cut + would differ. +3. A keyhole: a circle and three lines that stop short of it, the two + sides lengthened to the circle (``sketch_extend``), the circle's arc + between them removed (``sketch_trim``), and the neck's two bottom + corners rounded and bevelled in the sketch (``add_sketch_fillet``, + ``add_sketch_chamfer``: a 2D profile's corners), cut through. +4. A stadium window from a line, a tangent arc, a line and a three-point arc + (``add_arc`` ``kind``), cut through. +5. Last: the plate's two left corner edges filleted R10 and its two right + ones chamfered 10 mm (``add_fillet``, ``add_chamfer``). + +Run it with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_sketch_essentials.py + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows. +""" + +from __future__ import annotations + +import math +from typing import Any + +import pytest + +from tests.live.evidence import evidence, starting +from tests.live.test_live_sw_equations import _tools +from tests.live.test_live_sw_equations_wrench import _frame + +pytestmark = pytest.mark.asyncio + +THICKNESS = 8.0 +#: The least a recording's GIF shows each result caption: long enough to read. +READ_SECONDS = 5.0 +PLATE_MM2 = 120.0 * 80.0 +#: Straight slot, 30 mm centre to centre, 10 wide; arc slot, a quarter turn +#: on a 20 mm radius, 8 wide. Each: centreline x width + one end circle. +STRAIGHT_SLOT_MM2 = 30 * 10 + math.pi * 5**2 +ARC_SLOT_MM2 = 20 * math.pi / 2 * 8 + math.pi * 4**2 +#: Keyhole: a circle r 8 at (0, 10), and a 6 mm wide neck from y = -15 up +#: into it. Circle plus the neck up to the circle's centre line (y = 10), +#: less the neck's part inside the circle's lower half: +#: integral of sqrt(r^2 - x^2) for x from -3 to 3. +_R, _HALF = 8.0, 3.0 +_NECK_INSIDE = _HALF * math.sqrt(_R**2 - _HALF**2) + _R**2 * math.asin(_HALF / _R) +#: The neck's bottom corners in the sketch: one rounded, one bevelled. +NECK_FILLET, NECK_CHAMFER = 1.5, 1.5 +KEYHOLE_MM2 = ( + math.pi * _R**2 + + 2 * _HALF * (10 + 15) + - _NECK_INSIDE + - NECK_FILLET**2 * (1 - math.pi / 4) + - NECK_CHAMFER**2 / 2 +) +#: Stadium window: 30 mm straight, 10 mm wide, two half-circle ends. +WINDOW_MM2 = 30 * 10 + math.pi * 5**2 +#: The plate's corner edges, treated last: two filleted, two chamfered. +EDGE_FILLET, EDGE_CHAMFER = 10.0, 10.0 +EDGES_MM2 = 2 * EDGE_FILLET**2 * (1 - math.pi / 4) + 2 * EDGE_CHAMFER**2 / 2 + + +async def _volume(tools: dict[str, Any], expected_mm3: float) -> dict[str, Any]: + """``verify_model`` on the part's volume; the verdict and what it measured.""" + checked = await tools["verify_model"]( + {"volume_mm3": round(expected_mm3, 3), "solid_body_count": 1} + ) + return { + "verdict": checked["verdict"], + "expected_mm3": round(expected_mm3, 2), + "measured_mm3": checked["measured"].get("volume_mm3"), + } + + +async def _ok(reply: dict[str, Any]) -> dict[str, Any]: + assert reply["status"] == "success", reply + return reply + + +async def _open(tools: dict[str, Any]) -> str: + """Open a sketch on the Top plane; its name as create_sketch gives it.""" + made = await _ok(await tools["create_sketch"]({"plane": "Top"})) + return str(made["sketch"]["name"]) + + +async def _close(tools: dict[str, Any], opened: str) -> str: + """Close the open sketch; its tree name. + + ``exit_sketch`` names the sketch only when one was asked for, so the + name ``create_sketch`` gave is kept otherwise. + """ + closed = await _ok(await tools["exit_sketch"]()) + return str(closed.get("sketch", {"name": opened})["name"]) + + +async def _cut(tools: dict[str, Any], sketch: str) -> None: + await _ok( + await tools["create_cut_extrude"]( + {"sketch_name": sketch, "depth": 1, "end_condition": "ThroughAllBoth"} + ) + ) + + +def _corner_edges(x_mm: float) -> list[str]: + """The plate's two vertical corner edges at ``x_mm``, as ``add_fillet`` points. + + Metres, model space: halfway up the 8 mm plate (it grows +y from the Top + plane), at z = +-40 mm. + """ + y = THICKNESS / 2 / 1000.0 + return [f"{x_mm / 1000.0},{y},{z}" for z in (-0.04, 0.04)] + + +async def test_a_slotted_bracket_plate(scratch: Any) -> None: + """Every sketch-essentials operation in one part, each checked by volume.""" + tools = await _tools(scratch.adapter) + await _ok(await tools["create_part"]({"name": "bracket"})) + + # 1. The plate, drawn from its centre and left sharp; a refused corner. + starting("A 120 x 80 plate drawn from its centre") + opened = await _open(tools) + plate = await _ok( + await tools["add_rectangle"]( + {"x1": 0, "y1": 0, "x2": 60, "y2": 40, "from_center": True} + ) + ) + refused = await tools["add_sketch_fillet"]({"corners": [[0, 0]], "radius": 5}) + outline = await _close(tools, opened) + await _ok( + await tools["create_extrusion"]({"sketch_name": outline, "depth": THICKNESS}) + ) + _frame(scratch.adapter) + plate_volume = PLATE_MM2 * THICKNESS + built = await _volume(tools, plate_volume) + evidence( + "A plate drawn from its centre; a fillet at its centre point refused", + { + "rectangle": { + k: plate["rectangle"][k] + for k in ("corner1", "corner2", "width", "height") + }, + "refused": [ + refused["status"], + refused.get("error_type"), + refused["message"], + ], + "volume": built, + }, + call="add_rectangle(from_center), add_sketch_fillet at [0, 0] (refused), " + "create_extrusion 8", + hold=READ_SECONDS, + ) + assert refused["error_type"] == "invalid_input", refused + assert built["verdict"] == "pass", built + + # 2. Slots, with two construction lines across them. + starting("A straight slot and an arc slot, with two construction lines") + opened = await _open(tools) + straight = await _ok( + await tools["add_slot"]({"start": [-40, -15], "end": [-40, 15], "width": 10}) + ) + quarter = [math.radians(-45), math.radians(45)] + arc = await _ok( + await tools["add_slot"]( + { + "kind": "arc", + "center": [25, 0], + "start": [25 + 20 * math.cos(quarter[0]), 20 * math.sin(quarter[0])], + "end": [25 + 20 * math.cos(quarter[1]), 20 * math.sin(quarter[1])], + "width": 8, + } + ) + ) + across = await _ok( + await tools["add_line"]( + {"x1": -60, "y1": 0, "x2": 60, "y2": 0, "construction": True} + ) + ) + upright = await _ok( + await tools["add_line"]({"x1": 0, "y1": -40, "x2": 0, "y2": 40}) + ) + made = await _ok( + await tools["set_construction_geometry"]({"entities": [upright["line"]["id"]]}) + ) + await _cut(tools, await _close(tools, opened)) + slotted_volume = plate_volume - (STRAIGHT_SLOT_MM2 + ARC_SLOT_MM2) * THICKNESS + slotted = await _volume(tools, slotted_volume) + evidence( + "A straight slot and an arc slot cut; the two lines across are construction", + { + "slot_areas_mm2": [straight["slot"]["area"], arc["slot"]["area"]], + "construction": { + "add_line(construction)": across["line"]["construction"], + "set_construction_geometry": made["construction_geometry"]["entities"], + }, + "volume": slotted, + }, + call="add_slot x 2 (straight, arc), add_line(construction), " + "set_construction_geometry, create_cut_extrude", + hold=READ_SECONDS, + ) + assert straight["slot"]["area"] == pytest.approx(STRAIGHT_SLOT_MM2, abs=1e-3) + assert arc["slot"]["area"] == pytest.approx(ARC_SLOT_MM2, abs=1e-3) + assert slotted["verdict"] == "pass", slotted + + # 3. Keyhole: extend two lines to a circle, trim the arc between them, + # then round and bevel the neck's bottom corners in the sketch. + starting("A keyhole: lines extended to a circle, the arc between trimmed") + opened = await _open(tools) + await _ok(await tools["add_circle"]({"center_x": 0, "center_y": 10, "radius": _R})) + for x in (-_HALF, _HALF): + await _ok(await tools["add_line"]({"x1": x, "y1": -15, "x2": x, "y2": 0})) + await _ok( + await tools["add_line"]({"x1": -_HALF, "y1": -15, "x2": _HALF, "y2": -15}) + ) + extended = [ + await _ok(await tools["sketch_extend"]({"point": [x, -0.5]})) + for x in (-_HALF, _HALF) + ] + trimmed = await _ok(await tools["sketch_trim"]({"point": [0, 10 - _R]})) + rounded = await _ok( + await tools["add_sketch_fillet"]( + {"corners": [[-_HALF, -15]], "radius": NECK_FILLET} + ) + ) + bevelled = await _ok( + await tools["add_sketch_chamfer"]( + {"corners": [[_HALF, -15]], "distance": NECK_CHAMFER} + ) + ) + await _cut(tools, await _close(tools, opened)) + keyhole_volume = slotted_volume - KEYHOLE_MM2 * THICKNESS + keyed = await _volume(tools, keyhole_volume) + evidence( + "A keyhole: lines extended, the arc trimmed, the neck's corners treated", + { + "extend_mm": [e["extend"]["length_change_mm"] for e in extended], + "trim_mm": trimmed["trim"]["length_change_mm"], + "sketch_fillet": rounded["fillet"]["ids"], + "sketch_chamfer": bevelled["chamfer"]["ids"], + "keyhole_mm2": round(KEYHOLE_MM2, 3), + "volume": keyed, + }, + call="add_circle, add_line x 3, sketch_extend x 2, sketch_trim, " + "add_sketch_fillet, add_sketch_chamfer, create_cut_extrude", + hold=READ_SECONDS, + ) + assert keyed["verdict"] == "pass", keyed + + # 4. Stadium window: line, tangent arc, line, three-point arc. + starting("A window from lines, a tangent arc and a three-point arc") + opened = await _open(tools) + await _ok(await tools["add_line"]({"x1": -20, "y1": 25, "x2": 10, "y2": 25})) + tangent = await _ok( + await tools["add_arc"]( + {"kind": "tangent", "start_x": 10, "start_y": 25, "end_x": 10, "end_y": 35} + ) + ) + await _ok(await tools["add_line"]({"x1": 10, "y1": 35, "x2": -20, "y2": 35})) + three = await _ok( + await tools["add_arc"]( + { + "kind": "three_point", + "start_x": -20, + "start_y": 35, + "end_x": -20, + "end_y": 25, + "through_x": -25, + "through_y": 30, + } + ) + ) + await _cut(tools, await _close(tools, opened)) + windowed_volume = keyhole_volume - WINDOW_MM2 * THICKNESS + windowed = await _volume(tools, windowed_volume) + evidence( + "A stadium window from a tangent arc and a three-point arc", + { + "arcs": [tangent["arc"]["id"], three["arc"]["id"]], + "window_mm2": round(WINDOW_MM2, 3), + "volume": windowed, + }, + call="add_line, add_arc(tangent), add_line, add_arc(three_point), " + "create_cut_extrude", + hold=READ_SECONDS, + ) + assert windowed["verdict"] == "pass", windowed + + # 5. Last in the tree: the plate's corner edges. + starting("Last: the plate's corners filleted and chamfered") + filleted = await _ok( + await tools["add_fillet"]( + {"radius": EDGE_FILLET, "edge_names": _corner_edges(-60)} + ) + ) + chamfered = await _ok( + await tools["add_chamfer"]( + {"distance": EDGE_CHAMFER, "edge_names": _corner_edges(60)} + ) + ) + final_volume = windowed_volume - EDGES_MM2 * THICKNESS + finished = await _volume(tools, final_volume) + evidence( + "Last in the tree: two corners filleted R10, two chamfered 10 mm", + { + "fillet": filleted.get("message"), + "chamfer": chamfered.get("message"), + "volume": finished, + }, + call="add_fillet R10 x 2 edges, add_chamfer 10 x 2 edges", + hold=READ_SECONDS, + ) + assert finished["verdict"] == "pass", finished + evidence( + "Sketch essentials demo done", + { + "tools": [ + "add_slot", + "set_construction_geometry", + "sketch_extend", + "sketch_trim", + "add_sketch_fillet", + "add_sketch_chamfer", + ], + "volume_mm3": finished["measured_mm3"], + }, + call="add_rectangle(from_center), add_arc(tangent, three_point), " + "add_line(construction); fillets and chamfers last", + hold=READ_SECONDS, + ) diff --git a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py index b2bf876f..061f871c 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py @@ -3002,3 +3002,389 @@ async def test_the_mixin_passes_set_sketch_text_on() -> None: result = await adapter.set_sketch_text("Sketch12", "b") assert result.data["after"] == ["b"] + + +# --- Sketch essentials: corners, slots, trim and extend, construction ------ + + +class _Corner: + """An ISketchPoint at ``x``, ``y`` mm whose ``Select4`` answers ``ok``.""" + + def __init__(self, x: float, y: float, ok: bool = True) -> None: + self.X = x / 1000.0 + self.Y = y / 1000.0 + self.Z = 0.0 + self._ok = ok + self.selected = 0 + + def Select4(self, _append: bool, _data: object) -> bool: + self.selected += 1 + return self._ok + + +class _Segment: + """An ISketchSegment whose construction setting sticks, unless ``stuck``.""" + + def __init__(self, stuck: bool = False) -> None: + self._value = False + self._stuck = stuck + + @property + def ConstructionGeometry(self) -> bool: + return self._value + + @ConstructionGeometry.setter + def ConstructionGeometry(self, value: bool) -> None: + if not self._stuck: + self._value = value + + +def _essentials_adapter( + corners: tuple[_Corner, ...] = (), + made: object = "segment", + picked: bool = True, + changed: bool = True, +) -> tuple[_FakeSketchAdapter, list[tuple[object, ...]]]: + """An adapter with an open Top-plane sketch; the COM calls made, in order. + + Sketch ``[x, y]`` is model ``(x, 0, -y)``: the inverse transform the + tools use is checked by the coordinates ``SelectByID2`` receives. + ``made`` is what every create call returns, ``picked`` what + ``SelectByID2`` returns, ``changed`` whether trim and extend change the + sketch (their return value is ignored, as on SolidWorks): a trim + removes a 10 mm segment, an extension adds one. + """ + adapter = _FakeSketchAdapter() + calls: list[tuple[object, ...]] = [] + segments = [SimpleNamespace(GetLength=lambda: 0.01) for _ in range(3)] + + def call(name: str, result: object = None) -> object: + def run(*args: object) -> object: + calls.append((name, *args)) + return made if result is None else result + + return run + + def change(name: str) -> object: + def run(*args: object) -> bool: + calls.append((name, *args)) + if changed and name == "SketchTrim": + segments.pop() + elif changed: + segments.append(SimpleNamespace(GetLength=lambda: 0.01)) + return False # SolidWorks returned False even when it trimmed + + return run + + sketch = SimpleNamespace( + GetSketchPoints2=lambda: corners, + GetSketchSegments=lambda: tuple(segments), + ModelToSketchTransform=SimpleNamespace(Inverse=lambda: "to-model"), + ) + adapter.currentSketchManager = SimpleNamespace( + ActiveSketch=sketch, + CreateFillet=call("CreateFillet"), + CreateChamfer=call("CreateChamfer"), + CreateSketchSlot=call("CreateSketchSlot"), + Create3PointArc=call("Create3PointArc"), + CreateTangentArc=call("CreateTangentArc"), + CreateCenterRectangle=call("CreateCenterRectangle", (1, 2, 3, 4)), + SketchTrim=change("SketchTrim"), + SketchExtend=change("SketchExtend"), + ) + + def _select(*args: object) -> bool: + calls.append(("SelectByID2", *args[:5])) + return picked + + adapter.currentModel = SimpleNamespace( + ClearSelection2=lambda *_a: True, + SelectionManager=SimpleNamespace( + CreateSelectData=lambda: SimpleNamespace(Mark=None) + ), + Extension=SimpleNamespace(SelectByID2=_select), + ) + + def _point(data: object) -> SimpleNamespace: + x, y, _z = (float(v) for v in getattr(data, "value", data)) + return SimpleNamespace( + MultiplyTransform=lambda t: SimpleNamespace( + ArrayData=(x, 0.0, -y) if t == "to-model" else (x, y, 0.0) + ) + ) + + adapter.swApp = SimpleNamespace( + GetMathUtility=lambda: SimpleNamespace(CreatePoint=_point) + ) + return adapter, calls + + +def test_each_corner_is_rounded_on_its_own() -> None: + """Every corner is found, then filleted alone, with no dialog asked for.""" + left, top = _Corner(-60, -40), _Corner(-60, 40) + adapter, calls = _essentials_adapter((_Corner(60, 40), left, top)) + + result = sketch._add_sketch_fillet_impl(adapter, [[-60, -40], [-60, 40]], 10) + + assert result.is_success, result.error + assert result.data == { + "ids": ["Fillet_1", "Fillet_2"], + "corners": [[-60, -40], [-60, 40]], + } + assert calls == [("CreateFillet", 0.01, 1), ("CreateFillet", 0.01, 1)] + assert (left.selected, top.selected) == (1, 1) + + +def test_a_corner_that_isnt_there_changes_nothing() -> None: + adapter, calls = _essentials_adapter((_Corner(-60, -40),)) + + result = sketch._add_sketch_fillet_impl(adapter, [[-60, -40], [0, 0]], 10) + + assert result.status == AdapterResultStatus.ERROR + assert "No sketch point at corner [0, 0] mm" in (result.error or "") + assert calls == [] + + +def test_a_corner_that_wont_select_is_an_error() -> None: + adapter, calls = _essentials_adapter((_Corner(5, 5, ok=False),)) + + result = sketch._add_sketch_fillet_impl(adapter, [[5, 5]], 1) + + assert "Couldn't select the corner at [5, 5] mm" in (result.error or "") + assert calls == [] + + +def test_a_refused_fillet_names_the_corner() -> None: + adapter, _calls = _essentials_adapter((_Corner(5, 5),), made=None) + + result = sketch._add_sketch_fillet_impl(adapter, [[5, 5]], 1) + + assert "SolidWorks refused the fillet at corner [5, 5] mm" in (result.error or "") + + +@pytest.mark.parametrize( + ("distance2", "angle", "expected"), + [ + (None, None, (2, 0.01, 0.01)), + (4.0, None, (1, 0.01, 0.004)), + (None, 30.0, (0, 0.01, math.radians(30))), + ], +) +def test_a_chamfer_is_equal_two_distances_or_an_angle( + distance2: float | None, angle: float | None, expected: tuple[float, ...] +) -> None: + adapter, calls = _essentials_adapter((_Corner(60, 40),)) + + result = sketch._add_sketch_chamfer_impl(adapter, [[60, 40]], 10, distance2, angle) + + assert result.data["ids"] == ["Chamfer_1"] + assert calls == [("CreateChamfer", *expected)] + + +def test_a_straight_slot_runs_between_its_centres() -> None: + adapter, calls = _essentials_adapter() + + result = sketch._add_slot_impl(adapter, "straight", 10, [-40, -15], [-40, 15]) + + assert result.data == "Slot_1" + assert calls == [ + ( + "CreateSketchSlot", + 0, + 0, + 0.01, + -0.04, + -0.015, + 0.0, + -0.04, + 0.015, + 0.0, + -0.04, + 0.015, + 0.0, + 1, + False, + ) + ] + + +def test_an_arc_slot_follows_its_arc_counter_clockwise() -> None: + adapter, calls = _essentials_adapter() + + result = sketch._add_slot_impl(adapter, "arc", 8, [45, 0], [25, 20], [25, 0]) + + assert result.is_success, result.error + assert calls[0][:2] == ("CreateSketchSlot", 2) + assert calls[0][4:13] == (0.025, 0.0, 0.0, 0.045, 0.0, 0.0, 0.025, 0.02, 0.0) + + +def test_an_arc_slot_needs_its_centre() -> None: + adapter, calls = _essentials_adapter() + + result = sketch._add_slot_impl(adapter, "arc", 8, [45, 0], [25, 20]) + + assert "An arc slot needs its center" in (result.error or "") + assert calls == [] + + +def test_a_refused_slot_is_an_error() -> None: + adapter, _calls = _essentials_adapter(made=None) + + result = sketch._add_slot_impl(adapter, "straight", 8, [0, 0], [10, 0]) + + assert "SolidWorks refused the slot" in (result.error or "") + + +def test_trim_picks_in_model_space_and_counts_segments() -> None: + """Sketch [0, 2] on the Top plane is model (0, 0, -2) mm.""" + adapter, calls = _essentials_adapter() + + result = sketch._sketch_trim_impl(adapter, [0, 2]) + + assert result.data == { + "point": [0, 2], + "segments_before": 3, + "segments_after": 2, + "length_change_mm": -10.0, + } + assert calls == [ + ("SelectByID2", "", "SKETCHSEGMENT", 0.0, 0.0, -0.002), + ("SketchTrim", 0, 0.0, 0.0, -0.002), + ] + + +def test_a_trim_that_changes_nothing_is_refused() -> None: + adapter, calls = _essentials_adapter(changed=False) + + result = sketch._sketch_trim_impl(adapter, [0, 2]) + + assert "SolidWorks refused to trim at [0, 2] mm" in (result.error or "") + assert [c[0] for c in calls] == ["SelectByID2", "SketchTrim"] + + +def test_extend_lengthens_the_entity_at_the_point() -> None: + adapter, calls = _essentials_adapter() + + result = sketch._sketch_extend_impl(adapter, [-3, -0.5]) + + assert result.data["segments_after"] == 4 + assert result.data["length_change_mm"] == 10.0 + assert calls[-1] == ("SketchExtend", -0.003, 0.0, 0.0005) + + +def test_nothing_at_the_point_changes_nothing() -> None: + adapter, calls = _essentials_adapter(picked=False) + + result = sketch._sketch_trim_impl(adapter, [9, 9]) + + assert "No sketch entity at [9, 9] mm" in (result.error or "") + assert [c[0] for c in calls] == ["SelectByID2"] + + +def test_a_refused_extension_names_the_point() -> None: + adapter, _calls = _essentials_adapter(changed=False) + + result = sketch._sketch_extend_impl(adapter, [1, 2]) + + assert "SolidWorks refused to extend at [1, 2] mm" in (result.error or "") + + +def test_construction_is_set_on_every_segment_and_read_back() -> None: + adapter, _calls = _essentials_adapter() + line, sides = _Segment(), (_Segment(), _Segment()) + adapter._sketch_entities = {"Line_1": line, "Rectangle_2": sides} + + made = sketch._set_construction_geometry_impl(adapter, ["Line_1", "Rectangle_2"]) + again = sketch._set_construction_geometry_impl(adapter, ["Line_1"]) + back = sketch._set_construction_geometry_impl(adapter, ["Rectangle_2"], False) + + assert made.data == { + "entities": {"Line_1": True, "Rectangle_2": True}, + "construction": True, + } + assert again.data["entities"] == {"Line_1": True} + assert back.data == {"entities": {"Rectangle_2": False}, "construction": False} + assert line.ConstructionGeometry and not any(s.ConstructionGeometry for s in sides) + + +def test_an_unknown_id_changes_no_entity() -> None: + adapter, _calls = _essentials_adapter() + line = _Segment() + adapter._sketch_entities = {"Line_1": line} + + result = sketch._set_construction_geometry_impl(adapter, ["Line_1", "Line_9"]) + + assert "Unknown sketch entity 'Line_9'" in (result.error or "") + assert line.ConstructionGeometry is False + + +def test_a_setting_solidworks_ignores_is_an_error() -> None: + adapter, _calls = _essentials_adapter() + adapter._sketch_entities = {"Line_1": _Segment(stuck=True)} + + result = sketch._set_construction_geometry_impl(adapter, ["Line_1"]) + + assert "didn't change Line_1 to construction geometry" in (result.error or "") + + +@pytest.mark.parametrize( + "operation", + [ + lambda a: sketch._add_sketch_fillet_impl(a, [[0, 0]], 1), + lambda a: sketch._add_sketch_chamfer_impl(a, [[0, 0]], 1), + lambda a: sketch._add_slot_impl(a, "straight", 1, [0, 0], [1, 0]), + lambda a: sketch._sketch_trim_impl(a, [0, 0]), + lambda a: sketch._sketch_extend_impl(a, [0, 0]), + lambda a: sketch._set_construction_geometry_impl(a, ["Line_1"]), + ], +) +def test_each_needs_an_open_sketch(operation: object) -> None: + result = operation(_FakeSketchAdapter()) # type: ignore[operator] + + assert result.error == "No active sketch" + + +def test_three_point_and_tangent_arcs() -> None: + adapter, calls = _essentials_adapter() + + three = sketch._add_arc_impl( + adapter, 0, 0, -20, 35, -20, 25, "three_point", (-25, 30) + ) + tangent = sketch._add_arc_impl(adapter, 0, 0, 10, 25, 10, 35, "tangent") + missing = sketch._add_arc_impl(adapter, 0, 0, 1, 1, 2, 2, "three_point") + + assert three.is_success and tangent.is_success + assert calls == [ + ("Create3PointArc", -0.02, 0.035, 0, -0.02, 0.025, 0, -0.025, 0.03, 0), + ("CreateTangentArc", 0.01, 0.025, 0, 0.01, 0.035, 0, 1), + ] + assert "needs a through point" in (missing.error or "") + + +def test_a_rectangle_from_its_centre() -> None: + adapter, calls = _essentials_adapter() + + result = sketch._add_rectangle_impl(adapter, 0, 0, 60, 40, from_center=True) + + assert result.data == "Rectangle_1" + assert calls == [("CreateCenterRectangle", 0.0, 0.0, 0, 0.06, 0.04, 0)] + assert adapter._sketch_entity_centers["Rectangle_1"] == (0, 0) + + +@pytest.mark.asyncio +async def test_the_mixin_passes_sketch_essentials_on() -> None: + adapter, _calls = _essentials_adapter((_Corner(1, 1),)) + adapter._sketch_entities = {"Line_1": _Segment()} + mixin = SolidWorksSketchMixin + + def bound(name: str) -> object: + return getattr(mixin, name).__get__(adapter) + + assert (await bound("add_sketch_fillet")([[1, 1]], 1)).is_success + assert (await bound("add_sketch_chamfer")([[1, 1]], 1)).is_success + assert (await bound("add_slot")("straight", 2, [0, 0], [5, 0])).is_success + assert (await bound("sketch_trim")([0, 0])).is_success + assert (await bound("sketch_extend")([0, 0])).is_success + assert (await bound("set_construction_geometry")(["Line_1"])).is_success + assert (await bound("add_rectangle")(0, 0, 1, 1, True)).is_success + assert (await bound("add_arc")(0, 0, 1, 0, 0, 1, "tangent")).is_success diff --git a/tests/solidworks_mcp/adapters/test_base.py b/tests/solidworks_mcp/adapters/test_base.py index 4daf6ddb..1e5784e1 100644 --- a/tests/solidworks_mcp/adapters/test_base.py +++ b/tests/solidworks_mcp/adapters/test_base.py @@ -138,6 +138,28 @@ async def test_base_default_sketch_helpers_return_error() -> None: result = await adapter.set_sketch_text("Sketch1", "abc") assert result.status == AdapterResultStatus.ERROR + result = await adapter.add_sketch_fillet([[1.0, 2.0]], 3.0) + assert "add_sketch_fillet is not implemented" in (result.error or "") + + result = await adapter.add_sketch_chamfer([[1.0, 2.0]], 3.0, 4.0, None) + assert "add_sketch_chamfer is not implemented" in (result.error or "") + + result = await adapter.add_slot("arc", 8.0, [45.0, 0.0], [25.0, 20.0], [25.0, 0.0]) + assert "add_slot is not implemented" in (result.error or "") + + result = await adapter.sketch_trim( + [0.0, 2.0], + ) + assert "sketch_trim is not implemented" in (result.error or "") + + result = await adapter.sketch_extend( + [-3.0, -0.5], + ) + assert "sketch_extend is not implemented" in (result.error or "") + + result = await adapter.set_construction_geometry(["Line_1"], False) + assert "set_construction_geometry is not implemented" in (result.error or "") + result = await adapter.add_sketch_constraint("e1", None, "coincident") assert result.status == AdapterResultStatus.ERROR diff --git a/tests/solidworks_mcp/adapters/test_circuit_breaker.py b/tests/solidworks_mcp/adapters/test_circuit_breaker.py index 110ae244..ff2364d3 100644 --- a/tests/solidworks_mcp/adapters/test_circuit_breaker.py +++ b/tests/solidworks_mcp/adapters/test_circuit_breaker.py @@ -70,6 +70,24 @@ def cb_with_mock(): inner.set_sketch_text = AsyncMock( return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) ) + inner.add_sketch_fillet = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.add_sketch_chamfer = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.add_slot = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.sketch_trim = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.sketch_extend = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.set_construction_geometry = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) inner.sketch_linear_pattern = AsyncMock( return_value=AdapterResult(status=AdapterResultStatus.SUCCESS) ) @@ -619,7 +637,9 @@ async def add_circle(self, center_x: float, center_y: float, radius: float): """Test helper for add circle.""" return AdapterResult(status=AdapterResultStatus.SUCCESS, data="C1") - async def add_rectangle(self, x1: float, y1: float, x2: float, y2: float): + async def add_rectangle( + self, x1: float, y1: float, x2: float, y2: float, from_center: bool = False + ): """Test helper for add rectangle.""" return AdapterResult(status=AdapterResultStatus.SUCCESS, data="R1") @@ -1163,3 +1183,40 @@ async def test_circuit_breaker_set_sketch_text(cb_with_mock): result = await cb.set_sketch_text("Sketch12", "abc") assert result.status == AdapterResultStatus.SUCCESS inner.set_sketch_text.assert_awaited_once_with("Sketch12", "abc") + + +_ESSENTIALS = [ + ("add_sketch_fillet", ([[1.0, 2.0]], 3.0)), + ("add_sketch_chamfer", ([[1.0, 2.0]], 3.0, 4.0, None)), + ("add_slot", ("arc", 8.0, [45.0, 0.0], [25.0, 20.0], [25.0, 0.0])), + ("sketch_trim", ([0.0, 2.0],)), + ("sketch_extend", ([-3.0, -0.5],)), + ("set_construction_geometry", (["Line_1"], False)), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("method", "args"), _ESSENTIALS) +async def test_circuit_breaker_passes_sketch_essentials_on(cb_with_mock, method, args): + """Each sketch-essentials call routes through the breaker unchanged.""" + cb, inner = cb_with_mock + result = await getattr(cb, method)(*args) + assert result.status == AdapterResultStatus.SUCCESS + getattr(inner, method).assert_awaited_once_with(*args) + + +@pytest.mark.asyncio +async def test_circuit_breaker_passes_arc_kind_and_centre_rectangle_on(cb_with_mock): + cb, inner = cb_with_mock + inner.add_arc = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data="Arc_1") + ) + inner.add_rectangle = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data="R_1") + ) + + await cb.add_arc(0, 0, 1, 0, 0, 1, "three_point", (2.0, 2.0)) + await cb.add_rectangle(0, 0, 5, 5, True) + + inner.add_arc.assert_awaited_once_with(0, 0, 1, 0, 0, 1, "three_point", (2.0, 2.0)) + inner.add_rectangle.assert_awaited_once_with(0, 0, 5, 5, True) diff --git a/tests/solidworks_mcp/adapters/test_connection_pool.py b/tests/solidworks_mcp/adapters/test_connection_pool.py index c1d6be35..b3df5890 100644 --- a/tests/solidworks_mcp/adapters/test_connection_pool.py +++ b/tests/solidworks_mcp/adapters/test_connection_pool.py @@ -1777,6 +1777,14 @@ async def test_connection_pool_forwards_explicit_templates() -> None: ("add_ellipse", (0.0, 0.0, 10.0, 5.0, 15.0)), ("add_sketch_text", ("abc", 1.0, 2.0, 4.0, [60.0, 2.0, 0.0])), ("set_sketch_text", ("Sketch12", "abc")), + ("add_sketch_fillet", ([[1.0, 2.0]], 3.0)), + ("add_sketch_chamfer", ([[1.0, 2.0]], 3.0, 4.0, None)), + ("add_slot", ("arc", 8.0, [45.0, 0.0], [25.0, 20.0], [25.0, 0.0])), + ("sketch_trim", ([0.0, 2.0],)), + ("sketch_extend", ([-3.0, -0.5],)), + ("set_construction_geometry", (["Line_1"], False)), + ("add_arc", (0.0, 0.0, 1.0, 0.0, 0.0, 1.0, "tangent", None)), + ("add_rectangle", (0.0, 0.0, 5.0, 5.0, True)), ("sketch_linear_pattern", (["Arc1"], 1.0, 0.0, 20.0, 3)), ("sketch_circular_pattern", (["Arc1"], 360.0, 4)), ("sketch_mirror", (["Arc1"], "Line1")), diff --git a/tests/solidworks_mcp/adapters/test_mock_adapter.py b/tests/solidworks_mcp/adapters/test_mock_adapter.py index bd9d2a00..edd60b0c 100644 --- a/tests/solidworks_mcp/adapters/test_mock_adapter.py +++ b/tests/solidworks_mcp/adapters/test_mock_adapter.py @@ -545,6 +545,53 @@ async def test_add_sketch_text_gives_an_id_the_text_and_height(self): assert result.data["text"] == "abc" and result.data["height"] == 4.0 assert result.data["id"] in adapter._sketch_entity_ids + @pytest.mark.asyncio + async def test_sketch_essentials_need_an_open_sketch(self): + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + + results = [ + await adapter.add_sketch_fillet([[0, 0]], 1), + await adapter.add_sketch_chamfer([[0, 0]], 1), + await adapter.add_slot("straight", 1, [0, 0], [1, 0]), + await adapter.sketch_trim([0, 0]), + await adapter.sketch_extend([0, 0]), + await adapter.set_construction_geometry(["Line1"]), + ] + + assert {r.error for r in results} == {"No active sketch"} + + @pytest.mark.asyncio + async def test_sketch_essentials_in_an_open_sketch(self): + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + line = (await adapter.add_line(0, 0, 10, 0)).data + + fillet = await adapter.add_sketch_fillet([[0, 0], [10, 0]], 2) + chamfer = await adapter.add_sketch_chamfer([[0, 0]], 2, angle=30) + slot = await adapter.add_slot("straight", 4, [0, 0], [10, 0]) + no_centre = await adapter.add_slot("arc", 4, [0, 0], [10, 0]) + trim = await adapter.sketch_trim([5, 0]) + extend = await adapter.sketch_extend([5, 0]) + made = await adapter.set_construction_geometry([line]) + unknown = await adapter.set_construction_geometry(["Nope_1"]) + arc = await adapter.add_arc(0, 0, 1, 0, 0, 1, "three_point") + centred = await adapter.add_rectangle(0, 0, 5, 5, True) + + assert len(fillet.data["ids"]) == 2 + assert chamfer.data["corners"] == [[0, 0]] + assert slot.data.startswith("Slot_") + assert no_centre.error == "An arc slot needs its center" + assert trim.data["segments_before"] == trim.data["segments_after"] + assert extend.data["point"] == [5, 0] + assert made.data == {"entities": {line: True}, "construction": True} + assert "Unknown sketch entity 'Nope_1'" in (unknown.error or "") + assert arc.error == "A three_point arc needs a through point" + assert centred.is_success + @pytest.mark.asyncio async def test_set_sketch_text_gives_the_text(self): adapter = MockSolidWorksAdapter({}) diff --git a/tests/solidworks_mcp/tools/test_error_classifier.py b/tests/solidworks_mcp/tools/test_error_classifier.py index 7408ffc7..f7c5d79e 100644 --- a/tests/solidworks_mcp/tools/test_error_classifier.py +++ b/tests/solidworks_mcp/tools/test_error_classifier.py @@ -80,6 +80,12 @@ def classifier() -> ErrorClassifier: "invalid_input", ), ("The active part has no solid body faces.", "not_found"), + ( + "Error in add_sketch_fillet: SolidWorks refused the fillet at corner " + "[0, 0] mm: it isn't where two entities meet", + "invalid_input", + ), + ("No sketch point at corner [9, 9] mm in the open sketch", "invalid_input"), ("No view named 'Side'. Views: Front, Top", "not_found"), ("No drawing views found to dimension (pictorial ...)", "not_found"), ( diff --git a/tests/solidworks_mcp/tools/test_sketching.py b/tests/solidworks_mcp/tools/test_sketching.py index 9b9ce854..d376b20d 100644 --- a/tests/solidworks_mcp/tools/test_sketching.py +++ b/tests/solidworks_mcp/tools/test_sketching.py @@ -1,5 +1,6 @@ """Tests for SolidWorks sketching tools.""" +import math from types import SimpleNamespace from unittest.mock import AsyncMock, Mock @@ -137,6 +138,11 @@ async def test_add_construction_line(self, mcp_server, mock_adapter, mock_config is_success=True, data={"entity_id": "Line2"}, execution_time=0.2 ) ) + # The drawing call draws normal geometry on SolidWorks; the tool then + # makes the new line construction geometry by id. + mock_adapter.set_construction_geometry = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) tool_func = None for tool in await mcp_server.list_tools(): @@ -151,6 +157,7 @@ async def test_add_construction_line(self, mcp_server, mock_adapter, mock_config assert result["status"] == "success" assert result["line"]["construction"] is True + mock_adapter.set_construction_geometry.assert_awaited_once_with(["Line2"], True) @pytest.mark.asyncio async def test_add_circle_center_radius( @@ -1391,3 +1398,248 @@ async def test_create_sketch_point_in_the_air_is_invalid_input(mcp_server, mock_ assert reply["error_type"] == "invalid_input" assert "[5.0, 60.0, 5.0]" in reply["message"] assert adapter._current_sketch is None + + +# --- Sketch essentials ------------------------------------------------------ + + +def _essentials_stub(**results: object) -> _SketchAdapterStub: + """A sketch stub whose new methods answer with ``results`` (success by default).""" + adapter = _SketchAdapterStub() + for name in ( + "add_sketch_fillet", + "add_sketch_chamfer", + "add_slot", + "sketch_trim", + "sketch_extend", + "set_construction_geometry", + "add_arc", + "add_rectangle", + "add_circle", + ): + setattr( + adapter, + name, + AsyncMock(return_value=results.get(name, _ok({"ids": ["X_1"]}))), + ) + return adapter + + +@pytest.mark.asyncio +async def test_corners_are_rounded_and_bevelled(mcp_server, mock_config): + adapter = _essentials_stub() + await register_sketching_tools(mcp_server, adapter, mock_config) + fillet = await _tool(mcp_server, "add_sketch_fillet") + chamfer = await _tool(mcp_server, "add_sketch_chamfer") + + rounded = await fillet(input_data={"corners": [[-60, -40]], "radius": 10}) + bevelled = await chamfer( + input_data={"corners": [[60, 40]], "distance": 10, "angle": 30} + ) + both = await chamfer( + input_data={"corners": [[60, 40]], "distance": 10, "distance2": 5, "angle": 30} + ) + no_corner = await fillet(input_data={"corners": [[1, 2, 3]], "radius": 1}) + + adapter.add_sketch_fillet.assert_awaited_once_with([[-60, -40]], 10) + adapter.add_sketch_chamfer.assert_awaited_once_with([[60, 40]], 10, None, 30) + assert rounded["fillet"] == {"ids": ["X_1"], "radius": 10} + assert bevelled["chamfer"]["angle"] == 30 + assert "Rounded 1 corner(s) to R10 mm" == rounded["message"] + assert both["error_type"] == "invalid_input" + assert no_corner["error_type"] == "invalid_input" + + +@pytest.mark.asyncio +async def test_a_corner_that_isnt_there_is_invalid_input(mcp_server, mock_config): + adapter = _essentials_stub( + add_sketch_fillet=AdapterResult( + status=AdapterResultStatus.ERROR, + error="No sketch point at corner [0, 0] mm in the open sketch", + ) + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + + reply = await (await _tool(mcp_server, "add_sketch_fillet"))( + input_data={"corners": [[0, 0]], "radius": 1} + ) + + assert reply["error_type"] == "invalid_input" + assert "sketch mm" in reply["hint"] + + +@pytest.mark.asyncio +async def test_slots_give_their_area(mcp_server, mock_config): + adapter = _essentials_stub(add_slot=_ok("Slot_1")) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "add_slot") + + straight = await tool( + input_data={"start": [-40, -15], "end": [-40, 15], "width": 10} + ) + arc = await tool( + input_data={ + "kind": "arc", + "center": [25, 0], + "start": [45, 0], + "end": [25, 20], + "width": 8, + } + ) + no_centre = await tool( + input_data={"kind": "arc", "start": [1, 0], "end": [0, 1], "width": 1} + ) + same = await tool(input_data={"start": [1, 1], "end": [1, 1], "width": 1}) + + assert straight["slot"]["id"] == "Slot_1" + assert straight["slot"]["area"] == pytest.approx(30 * 10 + math.pi * 25, abs=1e-4) + assert arc["slot"]["area"] == pytest.approx( + 20 * math.pi / 2 * 8 + math.pi * 16, abs=1e-4 + ) + assert adapter.add_slot.await_args_list[1].args == ( + "arc", + 8, + [45, 0], + [25, 20], + [25, 0], + ) + assert no_centre["error_type"] == "invalid_input" + assert same["error_type"] == "invalid_input" + + +@pytest.mark.asyncio +async def test_trim_and_extend_at_a_point(mcp_server, mock_config): + counts = {"point": [0, 2], "segments_before": 4, "segments_after": 4} + adapter = _essentials_stub(sketch_trim=_ok(counts), sketch_extend=_ok(counts)) + await register_sketching_tools(mcp_server, adapter, mock_config) + + trim = await (await _tool(mcp_server, "sketch_trim"))(input_data={"point": [0, 2]}) + extend = await (await _tool(mcp_server, "sketch_extend"))( + input_data={"point": [-3, -0.5]} + ) + + assert trim["trim"] == counts + assert extend["extend"] == counts + adapter.sketch_extend.assert_awaited_once_with([-3, -0.5]) + + +@pytest.mark.asyncio +async def test_construction_geometry_by_id(mcp_server, mock_config): + adapter = _essentials_stub( + set_construction_geometry=_ok( + {"entities": {"Line_1": False}, "construction": False} + ) + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "set_construction_geometry") + + reply = await tool(input_data={"entities": ["Line_1"], "construction": False}) + empty = await tool(input_data={"entities": []}) + + adapter.set_construction_geometry.assert_awaited_once_with(["Line_1"], False) + assert reply["message"] == "1 entity(ies) now normal geometry" + assert empty["error_type"] == "invalid_input" + + +@pytest.mark.asyncio +async def test_arcs_of_each_kind(mcp_server, mock_config): + adapter = _essentials_stub(add_arc=_ok("Arc_1")) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "add_arc") + ends = {"start_x": -20, "start_y": 35, "end_x": -20, "end_y": 25} + + three = await tool( + input_data={"kind": "three_point", "through_x": -25, "through_y": 30, **ends} + ) + tangent = await tool(input_data={"kind": "tangent", **ends}) + missing = await tool(input_data={"kind": "three_point", "through_y": 30, **ends}) + no_centre = await tool(input_data=ends) + + assert three["arc"]["through"] == {"x": -25, "y": 30} + assert three["arc"]["center"] is None + assert tangent["arc"]["kind"] == "tangent" + assert adapter.add_arc.await_args_list[0].args == ( + 0.0, + 0.0, + -20, + 35, + -20, + 25, + "three_point", + (-25, 30), + ) + assert adapter.add_arc.await_args_list[1].args[6:] == ("tangent", None) + assert missing["error_type"] == "invalid_input" + assert "through_x" in missing["message"] + assert no_centre["error_type"] == "invalid_input" + + +@pytest.mark.asyncio +async def test_a_rectangle_from_its_centre_gives_its_real_corners( + mcp_server, mock_config +): + adapter = _essentials_stub(add_rectangle=_ok("Rectangle_1")) + await register_sketching_tools(mcp_server, adapter, mock_config) + + reply = await (await _tool(mcp_server, "add_rectangle"))( + input_data={"x1": 0, "y1": 0, "x2": 60, "y2": 40, "from_center": True} + ) + + adapter.add_rectangle.assert_awaited_once_with(0, 0, 60, 40, True) + assert reply["rectangle"]["corner1"] == {"x": -60, "y": -40} + assert reply["rectangle"]["corner2"] == {"x": 60, "y": 40} + assert (reply["rectangle"]["width"], reply["rectangle"]["height"]) == (120, 80) + + +@pytest.mark.asyncio +async def test_construction_is_honoured_for_circles_and_rectangles( + mcp_server, mock_config +): + adapter = _essentials_stub( + add_rectangle=_ok("Rectangle_1"), add_circle=_ok("Circle_1") + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + + await (await _tool(mcp_server, "add_rectangle"))( + input_data={ + "x1": 0, + "y1": 0, + "x2": 6, + "y2": 4, + "from_center": True, + "construction": True, + } + ) + plain = await (await _tool(mcp_server, "add_circle"))( + input_data={"center_x": 0, "center_y": 0, "radius": 5} + ) + + adapter.set_construction_geometry.assert_awaited_once_with(["Rectangle_1"], True) + assert plain["circle"]["construction"] is False + + +@pytest.mark.asyncio +async def test_a_construction_setting_that_fails_fails_the_drawing( + mcp_server, mock_config +): + adapter = _essentials_stub( + add_rectangle=_ok("Rectangle_1"), + set_construction_geometry=AdapterResult( + status=AdapterResultStatus.ERROR, error="Unknown sketch entity 'R'" + ), + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + + reply = await (await _tool(mcp_server, "add_rectangle"))( + input_data={ + "x1": 0, + "y1": 0, + "x2": 6, + "y2": 4, + "from_center": True, + "construction": True, + } + ) + + assert reply["status"] == "error" + assert "construction geometry" in reply["message"]