diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ff2d902..1e767dff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **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` + adds or changes one, in every configuration by default, solves and + rebuilds, and gives the new value. An expression SolidWorks can't use + fails as `equation_refused` and changes nothing. Named configurations + are set one at a time; the reply's `values` gives each one's value. Demo: + one variable sizes a steel combination wrench (13, 19 and 8 mm, 27 + equations) whose handle is lettered with its own size, on the demos page + and in the README. +- **`add_sketch_text`**: writes text in the open sketch at a height, and + with `center_at` centres it on a point (measured from the text's own + edges, since SolidWorks' alignment doesn't centre it). The text can show + a custom property (`$PRP:"Name"`), so an equation-driven part can carry + its size; cut or extrude it like any sketch. +- **`set_sketch_text`**: rewrites the text in a named sketch and rebuilds, + giving the text before and after. SolidWorks doesn't redraw sketch text + when an equation changes the part; writing it again does. 145 tools. +- **`add_ellipse` takes an `angle`**, the degrees its major axis is turned + from +x, and **an ellipse can be dimensioned**: `add_sketch_dimension` + with `major_axis` or `minor_axis` on an ellipse's `id` sizes that axis, + so an equation can drive it. +- **`add_polygon` takes an `angle`**: the degrees its first corner is + turned from +x (0 by default), e.g. two hexagons 30° apart for a + 12-point opening. +- **A polygon can be dimensioned**: a `diameter` dimension + (`add_sketch_dimension`) on a polygon's `id` sizes it by the circle drawn + inside it, across flats for a hexagon, so an equation can drive it. - **`save_body_as_part` leaves no extra assembly open** (queue item 27, #101): a new, unsaved assembly SolidWorks opens alongside Save Bodies is closed, the part is made active again, and the reply's @@ -191,6 +219,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`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. - **`add_fillet` on the current selection** (empty `edge_names`, after `select_face_edges`) built no fillet: reading the volume first rebuilt the part, which cleared the selection. It no longer reads the volume in diff --git a/README.md b/README.md index dc3260db..0e403a90 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 140 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 145 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/) @@ -191,6 +191,7 @@ Each GIF is a live test driving SolidWorks 2026 through the MCP tools, with the A plate of Hole Wizard holes placed from points, a mirror and a ring
A plate of Hole Wizard holes from points, a mirror and a ring +A steel combination wrench sized by one global variable and lettered with its size: 13 mm, then 19 mm, then 8 mm in its own configuration
One variable sizes a combination wrench: equations and configurations @@ -366,7 +367,7 @@ It works only with the circuit-breaker adapter wrapper (the default for real Sol ### A shorter tool list -All 140 tools cost about 55,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 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). ## Teach your agent the workflow diff --git a/docs/agents/com-api-pitfalls.md b/docs/agents/com-api-pitfalls.md index 2fac6e54..072da34c 100644 --- a/docs/agents/com-api-pitfalls.md +++ b/docs/agents/com-api-pitfalls.md @@ -1031,6 +1031,65 @@ The SW version picks only `OptimizeGeometry`, never `Sd`. --- +## 36. `IEquationMgr`: no call that takes configuration names works from Python + +**Symptom:** `Add3` and `SetEquationAndConfigurationOption` return `-1`, `Status` +reads `-1`, and nothing is added or changed, for any equation text. + +**What works** (probed live on SW 2026, 2026-11-17/18): + +| Call | Result | +|---|---| +| `Add3(-1, text, True, option, names)`, names as a `VT_BSTR` array, a `VT_VARIANT` array, a tuple, `None` or `pythoncom.Empty` | always `-1` | +| `SetEquationAndConfigurationOption(i, text, 3, names)`, any array form | `-1` | +| `ISetEquationAndConfigurationOption(i, text, 3, 1, names)` | `Invalid number of parameters` | +| `Add2(-1, text, True)` (or `Add`) | adds in every configuration, returns the index | +| `SetEquationAndConfigurationOption(i, text, 1, None)` with the configuration active | `0`: set in that configuration only | +| `SetEquationAndConfigurationOption(i, text, 2, None)` | `0` on a 2-equation part, `-1` on a 19-equation one, even for the same text | +| `Equation(i)` property put (through `IDispatch.Invoke`, `DISPATCH_PROPERTYPUT`) | changes it in every configuration; a bad text leaves it and sets `Status` to `-1` | +| `EvaluateAll()` | returned `-1` on a part that solved: don't trust its return | + +**Fix:** add with `Add2`; change in every configuration with the property put; set +named configurations one at a time as "this configuration", each made active, then +show the original again. `Value(i)` is in the document's units (`19.0` for `19mm`). + +`adapters/solidworks/equations.py`. + +--- + +## 37. A sketch on a plane at an angle: its x axis may not be the one you expect + +**Symptom:** a rectangle meant to run along the part, on a reference plane made +15° from the Front Plane about the y axis, cut a half-depth groove instead. + +**Cause:** on that plane SolidWorks 2026 put the sketch's **x along the model's y** +(up) and its y along the part. A rectangle spanning sketch x 0..120 covered the upper +half of the thickness; its sketch y ±60 ran along the whole length. + +**Fix:** don't assume an angled plane's sketch axes. Make the profile span both ways +across the direction you don't care about, and check the result (overall size, +volume or body count). The wrench demo's jaw spans sketch x ±60 and picks the sketch-y +side by the measured size. + +`tests/live/test_live_sw_equations_wrench.py`, `_jaw`. + +--- + +## 38. Blind `both_directions` on a cut was one-sided; and patterns of patterns build nothing + +- **`FeatureCut4` mid-plane needs `T1 = swEndCondMidPlane` (6).** The adapter read + `both_directions` only with Through All, so a Blind cut asked for "both directions" + cut one way: a slot meant to straddle its plane came out beside it. Fixed: Blind with + `both_directions` passes `T1 = 6`, `D1` the total depth. +- **A linear pattern that includes a circular pattern built nothing** (no volume + change; the tool removed the empty feature). Draw the second instance instead: the + wrench's 12-point opening is two hexagon cuts, the second from `add_polygon` with + `angle: 30`. + +Found 2026-11-18 building the equations demo. + +--- + ## Adapter wiring traps — not COM, same silent-failure shape These are not SolidWorks issues, but they fail the same way: the code imports, the tests diff --git a/docs/agents/tool-description-standard.md b/docs/agents/tool-description-standard.md index 21e0b41e..d792d9ae 100644 --- a/docs/agents/tool-description-standard.md +++ b/docs/agents/tool-description-standard.md @@ -114,7 +114,7 @@ name and tell two tools apart by name alone. Pick the verb by meaning: | `list_` | reads a collection | | `set_` | changes one value | | `open_`, `save_`, `close_`, `export_` | file operations | -| `activate_`, `delete_` | makes a document or configuration the active one; removes a feature or configuration | +| `activate_`, `delete_` | makes a document or configuration the active one; removes a feature, configuration or equation | | `check_`, `verify_`, `measure_`, `compare_` | read-only checks | `tests/integration/test_tool_descriptions.py` fails on any other name, except diff --git a/docs/assets/demos/equations/test_a_combination_wrench_sized_by_one_variable-motion.gif b/docs/assets/demos/equations/test_a_combination_wrench_sized_by_one_variable-motion.gif new file mode 100644 index 00000000..44a93786 Binary files /dev/null and b/docs/assets/demos/equations/test_a_combination_wrench_sized_by_one_variable-motion.gif differ diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index 176a0ace..7d398c70 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,8 +1,8 @@ { "tools": { - "total": 140, + "total": 145, "by_level": { - "stable": 132, + "stable": 137, "beta": 0, "experimental": 0, "planned": 0, @@ -161,7 +161,14 @@ "family": "sketching", "level": "stable", "reason": "", - "summary": "Add a driving dimension to sketch entities: linear, angular, radial or diameter." + "summary": "Add a driving dimension to sketch entities: linear, angular, radial, diameter or an ellipse axis." + }, + { + "name": "add_sketch_text", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Write text in the open sketch, at a point or centred on one, to deboss or emboss it." }, { "name": "add_spline", @@ -408,6 +415,13 @@ "reason": "", "summary": "Delete a configuration of the active model; not the active one or the only one." }, + { + "name": "delete_equation", + "family": "equations", + "level": "stable", + "reason": "", + "summary": "Delete an equation or global variable of the active part or assembly, by name." + }, { "name": "delete_feature", "family": "modeling", @@ -681,6 +695,13 @@ "reason": "", "summary": "List the views on the active drawing, by name." }, + { + "name": "list_equations", + "family": "equations", + "level": "stable", + "reason": "", + "summary": "List the active part's or assembly's equations and global variables, with their values." + }, { "name": "list_features", "family": "file_management", @@ -884,6 +905,13 @@ "reason": "", "summary": "Change one length dimension of the active model, in mm, and rebuild." }, + { + "name": "set_equation", + "family": "equations", + "level": "stable", + "reason": "", + "summary": "Add or change an equation or global variable, so one value drives others (a parametric part)." + }, { "name": "set_flat_pattern", "family": "modeling", @@ -905,6 +933,13 @@ "reason": "", "summary": "Set the active drawing sheet's scale, e.g. 1:2; views that use the sheet scale follow it." }, + { + "name": "set_sketch_text", + "family": "sketching", + "level": "stable", + "reason": "", + "summary": "Rewrite the text in a sketch and rebuild, so debossed lettering shows it." + }, { "name": "set_units", "family": "modeling", @@ -994,11 +1029,11 @@ "com": { "type_library": "83A33D31-27C5-11CE-BFD4-00400513BB57x0x34x0", "core": { - "covered": 252, + "covered": 255, "total": 2838 }, "api": { - "covered": 278, + "covered": 298, "total": 5985 }, "interfaces": [ @@ -1071,6 +1106,7 @@ "GetActiveSketch2", "GetConfigurationNames", "GetDependencies2", + "GetEquationMgr", "GetFeatureCount", "GetLineCount", "GetMassProperties", @@ -1092,6 +1128,7 @@ "InsertRib", "InsertSketch", "InsertSketchForEdgeFlange", + "InsertSketchText", "Lock", "Parameter", "Save", @@ -1322,7 +1359,8 @@ "GetLineCount", "GetSketchContours", "GetSketchPoints2", - "GetSketchSegments" + "GetSketchSegments", + "GetSketchTextSegments" ], "total": 102 } diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index 19c9e8e7..a6383ccf 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,7 +21,7 @@ -MCP tools: 132 +MCP tools: 137 100% work on SolidWorks today @@ -33,7 +33,7 @@ -stable 132 +stable 137 beta 0 @@ -43,13 +43,13 @@ deprecated 8 Core SolidWorks COM API (12 interfaces) -252 of 2,838 methods · 8.9% +255 of 2,838 methods · 9.0% - - - + + + -Whole API: 278 of 5,985 method names (4.6%), counted by a text scan of the adapters. +Whole API: 298 of 5,985 method names (5.0%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index 1f91af56..023369c2 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -23,7 +23,8 @@ 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_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 or diameter. +add_sketch_dimensionsketchingstableAdd a driving dimension to sketch entities: linear, angular, radial, diameter or an ellipse axis. +add_sketch_textsketchingstableWrite text in the open sketch, at a point or centred on one, to deboss or emboss it. 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. @@ -59,6 +60,7 @@ create_sweepmodelingstableSweep a closed profile sketch along a path sketch to make a solid (Insert > Boss/Base > Sweep). create_technical_drawingdrawingstablePlace a model's three standard views (front, top and side) on the active drawing sheet in one call. delete_configurationfile_managementstableDelete a configuration of the active model; not the active one or the only one. +delete_equationequationsstableDelete an equation or global variable of the active part or assembly, by name. delete_featuremodelingstableDelete a feature or sketch from the active model, along with the features that depend on it. discover_solidworks_docsdocs_discoverystableRebuild the SolidWorks API index on purpose. The lookups don't need it. execute_macromacro_recordingstableRun a SolidWorks macro (.swp, or legacy .swb), or VBA source text, in the running SolidWorks, calling its `main` procedure. @@ -98,6 +100,7 @@ list_componentsmodelingstableList the top-level components of the active assembly by instance name, e.g. "bracket-1". list_configurationsfile_managementstableList the names of the active model's configurations, and which one is active. list_drawing_viewsdrawingstableList the views on the active drawing, by name. +list_equationsequationsstableList the active part's or assembly's equations and global variables, with their values. list_featuresfile_managementstableList the feature tree of the active part or assembly, in order. list_hole_sizesmodelingstableList the Hole Wizard's hole types and sizes for a standard, or one size's dimensions. list_model_dimensionsengineering_datastableList every dimension in the active part or assembly with its full name and value. @@ -127,9 +130,11 @@ set_component_statemodelingstableFix or float a component of the active assembly, or make a sub-assembly rigid or flexible. 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). set_flat_patternmodelingstableFlatten a sheet-metal part to its blank, or fold it back, and measure it. set_materialengineering_datastableAssign a library material to the active part, e.g. "AISI 1020" or "6061-T6 (SS)". set_sheet_scaledrawing_automationstableSet the active drawing sheet's scale, e.g. 1:2; views that use the sheet scale follow it. +set_sketch_textsketchingstableRewrite the text in a sketch and rebuild, so debossed lettering shows it. 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). @@ -151,7 +156,7 @@ 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
-IModelDoc279758
10.4%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, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertSketch, InsertSketchForEdgeFlange, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
+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
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
@@ -161,7 +166,7 @@ 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
-ISketch5102
4.9%AutoDimension, GetLineCount, GetSketchContours, GetSketchPoints2, GetSketchSegments
+ISketch6102
5.9%AutoDimension, GetLineCount, GetSketchContours, GetSketchPoints2, GetSketchSegments, GetSketchTextSegments
diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index 56f813ec..ba7076cb 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` | 140 | 227 KB | 58,160 | 100% | -| `core` | `list` | 100 | 151 KB | 38,717 | 67% | -| `drawing` | `list` | 21 | 38 KB | 9,616 | 17% | +| `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% | | `vba` | `list` | 10 | 17 KB | 4,356 | 7% | | `docs` | `list` | 6 | 15 KB | 3,914 | 7% | -| `core,drawing` | `list` | 121 | 189 KB | 48,333 | 83% | +| `core,drawing` | `list` | 126 | 196 KB | 50,299 | 84% | | `all` | `search` | 4 | 4 KB | 908 | 2% | | `core` | `search` | 4 | 4 KB | 908 | 2% | diff --git a/docs/demos.md b/docs/demos.md index b8129df2..72c9ccac 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -917,6 +917,84 @@ deletes the hole it had started, and the plate's volume doesn't change. 7. `pattern_circular({"features": ["Ø6.0 (6) Diameter Hole1"], "axis": "Axis1", "count": 6})` 8. `create_hole({"face_point": [0, 15, 22], "hole_type": "counterbore", "size": "M6", "end_condition": "blind", "depth": 8, "positions": [[0, 20, -22]]})`, refused on purpose +## Equations {#equations} + +Source: [`tests/live/test_live_sw_equations_wrench.py`](https://github.com/andrewbartels1/SolidworksMCP-python/blob/main/tests/live/test_live_sw_equations_wrench.py). + +### One variable sizes a combination wrench {#wrench} + +![A steel combination wrench driven by one global variable: built at 13 mm, lettered on its handle, regrown to 19 mm by one equation edit, shrunk to 8 mm in its own configuration, and a bad expression refused](assets/demos/equations/test_a_combination_wrench_sized_by_one_variable-motion.gif) + +> *Example prompt:* Make a 13 mm combination wrench in chrome-vanadium +> steel: an open end with its jaw at 15° and a curved jaw bottom, a raised +> 12-point box end, a flat handle, and fillets where the heads meet it. +> Letter "solidworksmcp-python" and the size into both faces of the handle. +> Drive every size from one global variable, `Size`, so I can make a 19 mm +> one by changing one number, then add an 8 mm size as its own +> configuration. + +**What it shows.** A combination wrench in the usual layout (ISO 3318 / +DIN 3113), modelled from photos of a real one: an open end with its jaw at +15° and a curved jaw bottom, a 12-point box end tilted 15° and raised, a +flat handle, fillets where both heads meet the handle, and 1.8159 (51CrV4) +chrome-vanadium steel from the DIN library. It is built first at fixed +13 mm sizes. Then `set_equation` adds a global variable `Size` = 13mm, six +variables computed from it, and an equation on each dimension that sizes +the wrench, including the jaw's ellipse, the ring's lift and the fillet +radii: 25 equations. + +| Variable | Expression | Drives | +| --- | --- | --- | +| `Size` | 13mm | the jaw's width; both hexagons of the 12-point opening, across flats; the ellipse, ring lift and fillets as multiples of it | +| `Length` | `"Size" * 12.8` | the handle bar's length and the box end's pattern spacing (head centre to head centre) | +| `OpenHead` | `"Size" * 2.0` | the open end's diameter | +| `BoxHead` | `"Size" * 1.55` | the box end's diameter | +| `HeadT` | `"Size" * 0.5` | both heads' thickness | +| `HandleW` | `"Size" * 0.9` | the handle's width (the round bar it is cut from) | +| `HandleT` | `"Size" * 0.3` | the handle's thickness (two planes `"HandleT" / 2` either side of the Top Plane) | + +**Lettering that reads its own size.** `add_sketch_text` writes +`solidworksmcp-python $PRP:"WrenchSize" mm` on each face of the handle, +centred on a point; the custom property `WrenchSize` is linked to a +dimension the equations set to `Size`, and the part shows whole +millimetres, so the handle reads "13 mm". The text is cut 0.3 mm deep on a +spare block off the open end and a linear pattern moves it onto the +handle's middle; two more equations keep it there at any size +(`"Size" * 6.48 + 190mm`) and keep the block as thick as the handle. The +block is then cut away. SolidWorks doesn't redraw sketch text when an +equation changes the part, so after each size change `set_sketch_text` +writes the text again, and the handle reads 19 mm, then 8 mm. + +Changing `Size` to 19mm is one call, and the whole wrench regrows. Setting +it to 8mm with `configurations: ["8 mm"]` changes only that configuration, +so the part holds both sizes. After each change, `verify_model` checks the +overall size against the hand calculation: + +| `Size` | Expected size, mm (x, y, z) | Measured | +| --- | --- | --- | +| 13 mm, as built | 189.09 x 11.49 x 26 | pass | +| 19 mm, Default | 276.37 x 16.8 x 38 | 276.366 x 16.7985 x 38.0 | +| 8 mm, configuration "8 mm" | 116.36 x 7.07 x 16 | 116.3646 x 7.0731 x 16.0 | + +The last call fails **on purpose**: `"Nut" * 2` names a variable that +doesn't exist, so SolidWorks refuses it (`equation_refused`), the equation +keeps its old text and the wrench stays at 19 mm. + +**Tool calls** + +1. `create_part`, then the handle: a Right-plane circle sized with `add_sketch_dimension({"dimension_type": "diameter"})`, `create_extrusion` along x, flattened by two `create_reference_plane` offsets and a `ThroughAll` cut from each +2. The box end at the origin: a circle extruded both ways on a plane tilted 15° and lifted `0.13 x Size`, then two `add_polygon({"sides": 6})` cuts, the second with `"angle": 30`, each sized across flats with a `diameter` dimension +3. `create_axis({"reference": "x"})`, then `pattern_linear` of the box-end features to the handle's far end, and a clearance cut that removes the pattern's seed +4. The open end at the origin: a Top-plane circle, `create_extrusion({"both_directions": true})` +5. The jaw: a rectangle on a plane at 15°, `create_cut_extrude({"both_directions": true})`, then the curved bottom: `add_ellipse` with an `angle`, its axes sized with `add_sketch_dimension({"dimension_type": "major_axis"})` and `minor_axis`, cut through +6. `add_fillet` where both heads meet the handle, faces then sides, and `set_material({"material_name": "1.8159 (51CrV4)", "database": "SolidWorks DIN Materials"})` +7. `list_model_dimensions()` to find each dimension's full name +8. `set_equation({"name": "Size", "expression": "13mm"})`, then the six variables, then one `set_equation` per dimension, then `list_equations()` +9. The lettering: `set_custom_property` (`WrenchSize` linked to a Size dimension), `add_sketch_text({"text": "solidworksmcp-python $PRP:\"WrenchSize\" mm", "height": 3.5, "center_at": [...]})` on each face of a spare block, a 0.3 mm cut, `pattern_linear` onto the handle's middle, two `set_equation` calls, and a cut that removes the block +10. `set_equation({"name": "Size", "expression": "19mm"})`, `verify_model`, then `set_sketch_text` on both lettering sketches +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 + ## 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 3a71a2a1..0b990e1a 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. -🚀 **140 Tools** | 🤖 **Agent-Ready Workflows** | ⚡ **Automatic COM/VBA Routing** | 🧪 **Schema-Validated Prompt Runs** +🚀 **145 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 -- 140 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 145 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 3f365e11..ac508eb1 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -36,8 +36,9 @@ ## Tool Catalog -- [Tool Catalog — All 140 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 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. - [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. - [Drawing Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/drawing/): Create and edit 2-D technical drawings: views, section and detail views, notes, centre marks, dimensions by hand or automatically, the title block and sheet format, and a check that the drawing is complete before it is exported. Every position is in sheet millimetres from the sheet's lower-left corner. - [Drawing Analysis Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/drawing-analysis/): Compare two versions of a drawing file on disk. A check of a drawing's contents (`check_drawing`) is planned in the drawing pack. diff --git a/docs/user-guide/tool-catalog/equations.md b/docs/user-guide/tool-catalog/equations.md new file mode 100644 index 00000000..2a42b913 --- /dev/null +++ b/docs/user-guide/tool-catalog/equations.md @@ -0,0 +1,77 @@ +# Equation Tools + +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. + +> **Prerequisite:** an open part or assembly. A number with no unit is in the document's units; write `60mm` or `30deg` to be sure. + +**Total tools in this category: 3** + +A global variable is a named value (`"Width" = 60mm`). A dimension equation sets a dimension from an expression (`"D1@Sketch1" = "Width" / 2`), using the dimension's `full_name` from `list_model_dimensions`. Change `Width` and every dimension that uses it follows on the next rebuild, which `set_equation` does for you. + +--- + +### `list_equations` + +List the active part's or assembly's equations and global variables, with their values. + +Each row has `index`, `name`, `expression`, `kind` (`global_variable`, `dimension` or `other`, such as a suppression equation) and `value` (solved, in the document's units; null when SolidWorks has none). + +**Prerequisite:** Active part or assembly. + +**Parameters:** none. + +**Sample call:** + +```json +{} +``` + +--- + +### `set_equation` + +Add or change an equation or global variable, so one value drives others. + +A `name` with `@` is a dimension of the active document; any other name is a global variable. If the model already has an equation for `name` (case doesn't matter), its expression is replaced; otherwise one is added. The model is solved and rebuilt, and the reply gives the equation, its `value`, `action` (`added` or `changed`) and the `configurations` it applies in. With configuration names, each is made active in turn and set for that configuration only, then the configuration that was active is shown again; the reply's `expression` and `value` are what was set, and `values` gives the solved value in each named configuration. An expression SolidWorks can't use, such as one naming a variable that doesn't exist, fails as `equation_refused` and changes nothing. + +It applies in every configuration by default, as SolidWorks' Equations dialog does; `set_dimension` defaults to the active one only. + +See it drive a whole part: [one variable sizes a combination wrench](../../demos.md#wrench). + +**Prerequisite:** Active part or assembly; for a dimension, the dimension. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | A global variable (e.g. 'Width'), or a dimension of the active document as list_model_dimensions names it (e.g. 'D1@Sketch1'); no quotes | +| `expression` | `str` | ✅ | | The right-hand side, e.g. '60mm' or '"Width" / 2'; names in double quotes | +| `configurations` | `str \| list[str]` | — | `"all"` | 'all', 'this' (the active configuration), or configuration names from `list_configurations` | + +**Sample call:** + +```json +{"name": "D1@Sketch1", "expression": "\"Width\" / 2"} +``` + +--- + +### `delete_equation` + +Delete an equation or global variable of the active part or assembly, by name. + +A dimension the equation drove keeps its last value. An equation that used a deleted global variable stops solving, so check `list_equations` afterwards. + +**Prerequisite:** Active part or assembly with that equation. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | The equation's name as list_equations gives it, e.g. 'Width' | + +**Sample call:** + +```json +{"name": "Width"} +``` diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index c7d3f013..8fd4ef6d 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,4 +1,4 @@ -# Tool Catalog — All 140 Tools +# Tool Catalog — All 145 Tools 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. @@ -10,7 +10,8 @@ Each section covers one functional category with parameter tables and copy-paste | Category | Count | Description | |----------|-------|-------------| | [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. | -| [Sketching Tools](sketching.md) | 19 | Sketches on a plane or a flat face: lines, circles, arcs, splines, polygons, relations, dimensions, offsets, mirrors and patterns. | +| [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. | | [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. | @@ -21,7 +22,7 @@ Each section covers one functional category with parameter tables and copy-paste | [Automation Tools](automation.md) | 1 | A VBA macro skeleton for a described task. | | [VBA Generation Tools](vba-generation.md) | 10 | VBA macro text for steps the tools don't cover. | | [Template Management Tools](template-management.md) | 1 | Compare two template files. | -| [Macro Recording Tools](macro-recording.md) | 1 | Run a binary SolidWorks macro (`.swp`). | +| [Macro Recording Tools](macro-recording.md) | 1 | Run a SolidWorks macro file, or VBA source when the server allows it. | | [Docs Discovery Tools](docs-discovery.md) | 6 | Look up SolidWorks API interfaces, member signatures and enum values, read from the installed SolidWorks type libraries. | | [Server Admin Tools](server-admin.md) | 1 | Reset the circuit breaker the server uses to pause a failing operation. | diff --git a/docs/user-guide/tool-catalog/modeling.md b/docs/user-guide/tool-catalog/modeling.md index 77e6175d..bd70f77e 100644 --- a/docs/user-guide/tool-catalog/modeling.md +++ b/docs/user-guide/tool-catalog/modeling.md @@ -746,7 +746,7 @@ Cut material from the active part with a closed sketch profile: holes, slots, wi | `draft_angle` | `float` | — | `0.0` | Draft angle in degrees | | `reverse_direction` | `bool` | — | `false` | Cut against the sketch normal instead of along it. Usually not needed: if the requested direction finds no material, the cut is retried the other way and the reply sets direction_flipped | | `end_condition` | `str` | — | `"Blind"` | 'Blind' (cut 'depth' mm), 'ThroughAll' (through the body, one way) or 'ThroughAllBoth' (through the body both ways, for a sketch inside the body) | -| `both_directions` | `bool` | — | `false` | With end_condition 'ThroughAll', cut through the body both ways (same as 'ThroughAllBoth') | +| `both_directions` | `bool` | — | `false` | Cut both ways from the sketch plane: with 'Blind', a mid-plane cut 'depth' mm in total, centred on the plane (a slot either side of it); with 'ThroughAll', through the body both ways (same as 'ThroughAllBoth') | | `sketch_name` | `str?` | — | `null` | Sketch to cut from, e.g. 'Sketch3'. If omitted, the sketch most recently created/exited in this session is used, but only if it still exists in the model — there is no other fallback. Pass this explicitly whenever more than one unconsumed sketch could exist, or after any operation that might have changed the active sketch. | **Sample call:** diff --git a/docs/user-guide/tool-catalog/sketching.md b/docs/user-guide/tool-catalog/sketching.md index 3916911f..4e063d8f 100644 --- a/docs/user-guide/tool-catalog/sketching.md +++ b/docs/user-guide/tool-catalog/sketching.md @@ -258,12 +258,14 @@ Draw a centreline (construction line) in the open sketch, in mm. Draw a regular polygon (e.g. a hexagon) in the open sketch from its centre, radius and number of sides. +`angle` turns it: the degrees its first corner is turned from +x (0 by default), so two hexagons 30° apart make a 12-point opening. A `diameter` dimension (`add_sketch_dimension`) on the polygon's `id` sizes it by the circle drawn inside it, so a hexagon is sized across flats and an equation can drive it. + **Prerequisite:** Active sketch edit mode **Sample call:** ```json -{} +{"center_x": 0, "center_y": 0, "radius": 6.5, "sides": 6, "angle": 30} ``` --- @@ -282,6 +284,57 @@ Draw an ellipse in the open sketch from its centre and axis lengths, in mm. --- +### `add_sketch_text` + +Write text in the open sketch, at a point or centred on one, to deboss or emboss it. + +**Prerequisite:** Active sketch edit mode. To read from a face's own side (an underside), open the sketch on that face (`create_sketch` with `face_point`). + +**SolidWorks automation note:** `IModelDoc2.InsertSketchText` at the point, with normal letter spacing; the letter height is the text format's `CharHeight`. `center_at` measures the text from its edges (`ISketchText.GetEdges2`) and moves it (`SetCoordinates`) so its middle is on that model point. `$PRP:"name"` in the text shows a custom property: set one to a dimension's name in quotes (`set_custom_property`, value `"D1@Sketch3"`) and the text follows that dimension, through any equation that drives it. On SolidWorks 2026 a line selected first didn't lay the text along it, centre alignment didn't centre it, and mirrored text couldn't be cut, so the tool uses none of them. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `text` | `str` | ✅ | | The text; `$PRP:"name"` shows a custom property | +| `x` | `float` | — | `0` | Start x in mm, sketch coordinates | +| `y` | `float` | — | `0` | Start y (baseline) in mm | +| `height` | `float` | — | `3.5` | Letter height in mm | +| `center_at` | `list[float]?` | — | `None` | Model point `[x, y, z]` in mm for the text's middle | + +**Sample call:** + +```json +{"text": "solidworksmcp-python $PRP:\"WrenchSize\" mm", "height": 3.5, "center_at": [85, 1.95, 0]} +``` + +Then `create_cut_extrude` on the sketch with a small `depth` debosses it. + +--- + +### `set_sketch_text` + +Rewrite the text in a sketch and rebuild, so debossed lettering shows it. + +**Prerequisite:** A part with a sketch holding text from `add_sketch_text` + +**SolidWorks automation note:** SolidWorks doesn't redraw sketch text when the model rebuilds, not even a `$PRP:` link to a dimension an equation changed (SolidWorks 2026: four rebuild modes, saving, and writing `ISketchText.Text` outside the sketch all left the old lettering). The tool opens the sketch (`EditSketch`), writes `Text`, closes it and rebuilds; written that way, a `$PRP:` link is read again. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `sketch_name` | `str` | ✅ | | The sketch, e.g. `Sketch12` | +| `text` | `str` | ✅ | | The new text; the same `$PRP:"name"` text re-reads the link | + +**Sample call:** + +```json +{"sketch_name": "Sketch12", "text": "solidworksmcp-python $PRP:\"WrenchSize\" mm"} +``` + +--- + ### `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 e0067971..cd3c5fac 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -55,13 +55,21 @@ These read SolidWorks' installed files and never start it [**42 tools available** :octicons-arrow-right-24:](tool-catalog/modeling.md) +- :material-function-variant:{ .lg .middle } **Equation Tools** + + --- + + Equations and global variables: one value drives several dimensions, so the part stays consistent when it changes. + + [**3 tools available** :octicons-arrow-right-24:](tool-catalog/equations.md) + - :material-pencil:{ .lg .middle } **Sketching Tools** --- 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. - [**19 tools available** :octicons-arrow-right-24:](tool-catalog/sketching.md) + [**21 tools available** :octicons-arrow-right-24:](tool-catalog/sketching.md) - :material-technical-draw:{ .lg .middle } **Drawing Tools** @@ -117,7 +125,7 @@ These read SolidWorks' installed files and never start it Open, save, switch and inspect documents; the feature tree, configurations and the current selection; Pack and Go. - [**20 tools available** :octicons-arrow-right-24:](tool-catalog/file-management.md) + [**21 tools available** :octicons-arrow-right-24:](tool-catalog/file-management.md) - :material-code-braces:{ .lg .middle } **VBA Generation** @@ -177,7 +185,7 @@ These read SolidWorks' installed files and never start it -**Total: 140 Tools** +**Total: 145 Tools** ## Deprecated tools diff --git a/mkdocs.yml b/mkdocs.yml index cc202c32..d3e824e6 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -49,6 +49,7 @@ nav: - Tool Catalog: - All Tools: user-guide/tool-catalog/index.md - Modeling: user-guide/tool-catalog/modeling.md + - Equations: user-guide/tool-catalog/equations.md - Sketching: user-guide/tool-catalog/sketching.md - Drawing: user-guide/tool-catalog/drawing.md - Drawing Analysis: user-guide/tool-catalog/drawing-analysis.md diff --git a/openspec/changes/equations-and-global-variables/.openspec.yaml b/openspec/changes/equations-and-global-variables/.openspec.yaml new file mode 100644 index 00000000..bbe8b393 --- /dev/null +++ b/openspec/changes/equations-and-global-variables/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/equations-and-global-variables/design.md b/openspec/changes/equations-and-global-variables/design.md new file mode 100644 index 00000000..c03b2592 --- /dev/null +++ b/openspec/changes/equations-and-global-variables/design.md @@ -0,0 +1,183 @@ +## Context + +SolidWorks keeps a document's equations in one ordered list +(`IModelDoc2.GetEquationMgr()`), each a text like `"Width" = 60mm` or +`"D1@Sketch1" = "Width" / 2`. Global variables are equations whose left +side is a plain name; dimension equations name a dimension the way +`list_model_dimensions` reports `full_name` (`D1@Sketch1`). The 2026 type +library's `IEquationMgr` has `Add3(Index, Equation, Solve, +WhichConfigurations, ConfigNames)`, `SetEquationAndConfigurationOption( +Index, Equation, WhichConfigurations, ConfigNames)`, `Delete(Index)`, +`GetCount()`, `EvaluateAll()`, and the indexed properties `Equation`, +`Value` and `GlobalVariable`. + +## Goals / Non-Goals + +**Goals:** read, add, change and delete equations and global variables, +in chosen configurations, with the solved values in the reply. + +**Non-Goals:** linking equations to an external file +(`LinkToFile`, `UpdateValuesFromExternalEquationFile`); suppression +equations' own tool; equation folders and solve order +(`AutomaticSolveOrder` stays as the document has it). + +## Decisions + +1. **Name and expression, not raw text.** The agent gives `name` and + `expression`; the server writes `"" = `. Getting the + quotes right is the commonest mistake in hand-written equations, and a + `name` lets the tool find an existing equation to change. `name` may + not contain `"`, `=` or a line break; `expression` may not be empty or + contain a line break. +2. **Add or change in one tool, `set_equation`.** "Set Width to 60" is + the same request whether `Width` exists or not, and the verb list's + `set_` is "changes one value". The reply says `added` or `changed`. +3. **Finding an equation.** Walk `Equation(i)` for `i` in + `0..GetCount()-1` and take the text between the first pair of quotes + as its name; compare without case, as SolidWorks does. +4. **The COM calls, as measured on SolidWorks 2026** (live probes, + 2026-11-17/18). Every call that takes an array of configuration names + returns -1 from Python, whatever the array's form (`Add3`, + `SetEquationAndConfigurationOption`, `ISetEquationAndConfiguration + Option`), so none is given names: + - **add:** `Add2(-1, text, True)`, which adds in every configuration + and returns the new index, or -1 when refused; + - **change in every configuration:** write the `Equation(i)` property + (an `IDispatch` property put; pywin32's late binding can't assign an + indexed property). `SetEquationAndConfigurationOption(i, text, 2, + None)` worked on a two-equation part but returned -1 on the wrench's + 19, even for the same text; + - **this configuration:** `SetEquationAndConfigurationOption(i, text, + 1, None)` with the configuration active; it returns 0; + - **named configurations:** each made active in turn and set as "this + configuration", then the one that was active is shown again, + whatever happens; the reply's `values` gives each one's solved value. + + A dimension name is checked with `IModelDoc2.Parameter(name)` before + anything is written. A refusal is the call's -1, `Status` going to -1, + or the stored text not reading back as written (ignoring spaces and + case: SolidWorks respaces it). A refused add is deleted again; a refused + change restores the previous text, so nothing is left half-done. + `EvaluateAll`'s return value isn't used: it returned -1 on a part that + solved. +5. **Configurations default to `all`**, as SolidWorks' Equations dialog + does, unlike `set_dimension` (`this`, as SolidWorks' dimension + dialog). The scope reuses `configuration_scope` from + `adapters/solidworks/configurations.py`, so names are checked the same + way and the same `swInConfigurationOpts_e` values go to COM. +6. **Solve and rebuild.** `EvaluateAll()` then `ForceRebuild3(False)` + after every add, change or delete; the reply's `value` is read after + that. `Value(i)` is expected in the document's units (60 for `60mm` in + an MMGS part); the live test confirms it, and the tool descriptions say + so. +7. **Refusal type.** A new classifier rule, `equation_refused`, appended + to the rule table, matches the adapter's "SolidWorks refused the + equation" message; its hint says to check the names in quotes with + `list_equations` and `list_model_dimensions`. +8. **Where the code lives.** A new tool module `tools/equations.py` and + adapter mixin `adapters/solidworks/equations.py`, mirrored by + `tests/solidworks_mcp/tools/test_equations.py` and + `tests/solidworks_mcp/adapters/solidworks/test_equations.py`. The tools + join the `modeling` toolset. +9. **Mock adapter.** Keeps a list of equations; `value` is a number when + the expression is a number (with an optional `mm`, `in` or `deg`) or a + quoted global variable that has one, otherwise null. An expression + naming a global variable that doesn't exist is refused, so the + `equation_refused` path is exercised without SolidWorks. + +## Risks / Trade-offs + +- **Units of `Value`**: confirmed live as the document's units (`19.0` + for `19mm` in an MMGS part), so the reply passes it through. +- **`Add3` on an assembly** writes the equation on the assembly; an + equation driving a part's dimension inside it needs the + `D1@Sketch1@Part1<1>` form. Out of scope for the live check; the + description says the dimension must be the active document's own. + +## The wrench demo, and two tool fixes it needed + +The live demo (`tests/live/test_live_sw_equations_wrench.py`, on the +demos page and in the README) builds a 13 mm combination wrench and drives +all twelve of its sizing dimensions from one global variable. Every size +grows from the centre line, so the wrench keeps its shape at any size. +Building it found two gaps, fixed here: + +- **`create_cut_extrude` with `both_directions` on a Blind cut** cut one + way only (the flag was read only with `ThroughAll`). It is now a + mid-plane cut, `depth` in total, as `create_extrusion` already did. +- **Polygons couldn't be sized by a dimension or turned.** + `add_sketch_dimension` with `diameter` on a polygon's `id` now + dimensions the circle `CreatePolygon` draws inside it (across flats + for a hexagon), and `add_polygon` takes an `angle` (the first corner's + turn from +x), so two hexagons 30° apart make a 12-point opening. + SolidWorks wouldn't linear-pattern a circular pattern of one hexagon, + which is why the second is drawn turned. +- **Ellipses couldn't be turned or sized by a dimension.** On the user's + reference wrench the jaw's bottom is a shallow curve that meets both + jaw walls. Here that is an ellipse cut at the head's centre: its major + axis is Size long across the jaw (turned 15° with it), its minor axis + 0.2 x Size. `add_ellipse` now takes an `angle` (the major axis's turn + from +x), and `add_sketch_dimension` takes `major_axis` and + `minor_axis` on an ellipse's `id`. Each is a dimension from the centre + to that axis's end point, so it holds half the axis (an ellipse has no + point at the other end to dimension the whole axis to); `value` is the + whole axis, as `add_ellipse` takes it. + +## Text on the wrench's handle: `add_sketch_text` + +The user asked for "solidworksmcp-python" and the wrench's size debossed +on both faces of the handle, so the size visibly changes with the +equations. Probed on SolidWorks 2026 (2026-11-18, scratch parts): + +- `IModelDoc2.InsertSketchText(x, y, z, text, alignment, flip, + horizontal_mirror, width_factor, space_between_chars)` adds text to the + open sketch. `space_between_chars` 0 stacked every letter on the first; + 100 (per cent, as `width_factor`) spaces them normally. +- A line selected first did NOT lay the text along it (the user's + suggestion, the usual way in the SolidWorks UI): the text stayed at the + point given, and moving the line by its dimension left the text where it + was. Centre alignment (2) didn't centre it either, and a mirrored text + (`horizontal_mirror` 1) cut nothing. The tool uses none of them. +- The height is `ISketchText.GetTextFormat()`, `CharHeight` (metres), + `SetTextFormat(False, format)`; the default was 3.5 mm. +- Centring works by measuring: `ISketchText.GetEdges2()` gives the + letters' edges (model space; `GetCurveParams3` start and end points + bound them), their middle is mapped into the sketch + (`ModelToSketchTransform`), and `SetCoordinates` moves the text by the + difference to the target point. On a 120 mm bar the text came out in + its middle, on the top face and on the underside. +- Text in a sketch opened on the underside face (`face_point`) reads + correctly from below; on a plane offset below the part it reads + mirrored. +- Text `solidworksmcp-python $PRP:"WrenchSize" mm`, with the file property + `WrenchSize` = `"D1@Boss-Extrude1"`, read `... 4.00 mm`, and `... 6.00 + mm` after the dimension changed: the text follows the dimension. + +The tool is `add_sketch_text(text, x, y, height, center_at)`. + +A linked text does NOT redraw when the model rebuilds. On the wrench at +Size 19 the lettering still read 13.00 after `ForceRebuild3`, +`EditRebuild3`, `Extension.Rebuild` (all, forced), with the link written +with the part's name, after saving, with a plain value in the property, +and after opening and closing the sketch. Writing `ISketchText.Text` +outside edit mode changed the string but not the geometry. What works: +open the sketch (`EditSketch`), write `Text` (the same `$PRP:` string +re-reads the link: 19.00), close it, rebuild. That is +`set_sketch_text(sketch_name, text)`; the demo calls it after each size +change, a visible re-letter step (the user's choice, 2026-11-18). The +lettering is one sketch text in every configuration, so it shows the +size it was last re-lettered at. + +A sketch text's position can't be driven by an equation, but the +wrench's handle middle moves with Size (x = 6.51 x Size). So the +lettering is cut, centred, into the faces of a spare block off the open +end (x = -190 mm, as thick as the handle), the two cuts are moved onto the +handle by a linear pattern whose spacing is `"Size" * 6.51 + 190mm`, and +the block is cut away, as the box end's pattern seed is. `WrenchSize` is +linked to a dimension the equations set to Size. + +## Migration Plan + +New tools; `add_polygon`'s and `add_ellipse`'s `angle` default to 0, so +existing calls are unchanged. A Blind cut with `both_directions` now cuts both ways, as its +name and the extrusion tool always said. diff --git a/openspec/changes/equations-and-global-variables/proposal.md b/openspec/changes/equations-and-global-variables/proposal.md new file mode 100644 index 00000000..4078f798 --- /dev/null +++ b/openspec/changes/equations-and-global-variables/proposal.md @@ -0,0 +1,67 @@ +## Why + +Equations and global variables are how a SolidWorks part becomes +parametric: one value (`"Width" = 60mm`) drives several dimensions +(`"D1@Sketch1" = "Width" / 2`), so changing it resizes the whole part +consistently. The server has nothing for them today. An agent can set +dimensions one at a time (`set_dimension`), but it can't link them, so a +change to one size leaves the others stale, and a part an agent hands back +isn't parametric the way a SolidWorks user expects. Configurations (queue +item 13) give variants; equations give the relations inside each variant. +This is the base the macro-driven parametric features build on (the +user's direction, 2026-11-17). + +## What Changes + +- **`list_equations`**: every equation and global variable of the active + part or assembly, in order, with its name, expression, kind (global + variable, dimension, other) and current value. +- **`set_equation`**: adds a global variable or a dimension equation, or + changes the expression of one that exists, in the configurations given + (`all` by default, as in SolidWorks' Equations dialog; `this`, or a + list). The model is solved and rebuilt, and the reply gives the new + value. An expression SolidWorks refuses fails as `equation_refused` and + nothing is changed. +- **`delete_equation`**: removes an equation or global variable by name. + A dimension it drove keeps its last value. +- **`add_sketch_text`** (added for the wrench demo, 2026-11-18): text in + the open sketch at a letter height, from a point or centred on a model + point; cut or extruded, it debosses or embosses. A `$PRP:` link to a custom + property that names a dimension makes the text follow that dimension, + so the wrench's handle reads its own size once re-lettered. +- **`set_sketch_text`**: rewrites a sketch's text with the sketch open, + then rebuilds; SolidWorks doesn't redraw sketch text on rebuild, so + this is the re-letter step after a size change. +- Tool count 140 to 145. + +## Capabilities + +### New Capabilities + +- `tools/equations`: reading, adding, changing and deleting equations and + global variables. +- `tools/sketch-text`: text in a sketch at a height, from a point or + centred on one, optionally showing a linked custom property. + +### Modified Capabilities + +None. (`tools/tool-naming` already allows `delete_`; its meaning in the +description standard gains "or equation".) + +## Impact + +- **COM, on the connect thread inside `_handle_com_operation`:** + `IModelDoc2.GetEquationMgr()`; `IEquationMgr.GetCount`, `Equation`, + `Value`, `GlobalVariable`, `Add3`, `SetEquationAndConfigurationOption`, + `Delete`, `EvaluateAll`; `IModelDoc2.Parameter` to check a dimension + name; `ForceRebuild3`. Argument lists checked against the installed + 2026 type library. +- **Code:** a new adapter mixin `adapters/solidworks/equations.py`; three + adapter methods through `base.py`, `circuit_breaker.py`, + `connection_pool.py`, `mock_adapter.py`; a new tool module + `tools/equations.py`; `tool_hints.py`, `support_levels.py`, + `toolsets.py`, an `equation_refused` rule in `error_classifier.py`. +- **Docs:** a catalog page, the agent skill's note on making a part + parametric, the description standard's `delete_` meaning, CHANGELOG, + progress bars. +- No issue is filed; this is queue item 29. diff --git a/openspec/changes/equations-and-global-variables/specs/tools/equations/spec.md b/openspec/changes/equations-and-global-variables/specs/tools/equations/spec.md new file mode 100644 index 00000000..a80d94fd --- /dev/null +++ b/openspec/changes/equations-and-global-variables/specs/tools/equations/spec.md @@ -0,0 +1,68 @@ +## Purpose + +An agent reads, adds, changes and deletes the equations and global +variables of the active part or assembly, so one value can drive several +dimensions and the model stays consistent when it changes. + +## ADDED Requirements + +### Requirement: List equations +`list_equations` SHALL return every equation of the active part or +assembly in SolidWorks' order, each with `index`, `name` (the left-hand +side without quotes), `expression` (the right-hand side), `kind` +(`global_variable`, `dimension` or `other`) and `value` (the solved value +SolidWorks reports, or null when it has none). A model with no equations +SHALL give an empty list, not an error. + +#### Scenario: A part with a global variable driving a dimension +- **WHEN** the part has `"Width" = 60mm` and `"D1@Sketch1" = "Width" / 2` +- **THEN** the reply lists `Width` as a `global_variable` with value 60 + and `D1@Sketch1` as a `dimension` with value 30 + +#### Scenario: No equations +- **WHEN** the part has none +- **THEN** the reply has an empty `equations` list and status `success` + +### Requirement: Add or change an equation +`set_equation` SHALL take `name` and `expression`, and `configurations` +(`all` by default, `this`, or a list of names). A `name` with an `@` is a +dimension and SHALL be one the model has; any other name is a global +variable. When an equation for `name` exists (names compared without +regard to case) its expression SHALL be replaced; otherwise one SHALL be +added. The model SHALL be solved and rebuilt, and the reply SHALL give +the equation as SolidWorks stored it, its value, and whether it was +`added` or `changed`. + +#### Scenario: A global variable drives a dimension +- **WHEN** `set_equation` is called with `Width` = `60mm`, then with + `D1@Sketch1` = `"Width" / 2` +- **THEN** the sketch dimension reads 30 mm, and setting `Width` to `80mm` + makes it read 40 mm + +#### Scenario: An expression SolidWorks refuses +- **WHEN** `expression` is `"NoSuchVariable" * 2` +- **THEN** the call fails with `equation_refused`, and `list_equations` + is unchanged + +#### Scenario: A dimension the model doesn't have +- **WHEN** `name` is `D9@NoSuchSketch` +- **THEN** the call fails with `invalid_input` pointing to + `list_model_dimensions`, and nothing is added + +#### Scenario: One configuration only +- **WHEN** `configurations` is `["Long"]` and the part has `Default` and + `Long` +- **THEN** the value applies in `Long`, and `Default` keeps its own + +### Requirement: Delete an equation +`delete_equation` SHALL take `name`, remove that equation, and reply with +the names left. A dimension it drove SHALL keep its last value. + +#### Scenario: Deleting a driving equation +- **WHEN** `D1@Sketch1` = `"Width" / 2` is deleted +- **THEN** `list_equations` no longer lists it and the dimension still + reads its last value + +#### Scenario: An unknown name +- **WHEN** no equation is named `name` +- **THEN** the call fails with `invalid_input` listing the equation names diff --git a/openspec/changes/equations-and-global-variables/specs/tools/sketch-text/spec.md b/openspec/changes/equations-and-global-variables/specs/tools/sketch-text/spec.md new file mode 100644 index 00000000..09e56541 --- /dev/null +++ b/openspec/changes/equations-and-global-variables/specs/tools/sketch-text/spec.md @@ -0,0 +1,71 @@ +## Purpose + +An agent writes text in a sketch, at a point or centred on one, at a +chosen letter height, so a cut or an extrusion can deboss or emboss it. +The text may show a custom property (`$PRP:"name"`); a property linked to +a dimension makes the text follow that dimension, and so an equation. + +## ADDED Requirements + +### Requirement: Text in the open sketch +`add_sketch_text` SHALL add `text` to the open sketch starting at `x`, +`y` (mm, sketch coordinates), its letters `height` millimetres tall +(default 3.5) and spaced normally, and reply with the text's `id`, the +text SolidWorks shows (a `$PRP:` link resolved) and the height. It SHALL +fail with `invalid_input` for empty text, a height that isn't positive or +a `center_at` that isn't three numbers, and with an error when no sketch +is open. + +#### Scenario: A word on a bar's top face +- **WHEN** a sketch is open on a 120 x 30 x 4 mm bar's top face and + `add_sketch_text` is called with `text` `solidworksmcp` and `height` 4 +- **THEN** the reply gives the text's `id`, `solidworksmcp` and height 4, + and a 0.3 mm cut from that sketch removes material from the bar + +### Requirement: Text centred on a model point +Given `center_at`, a model point `[x, y, z]` in mm, `add_sketch_text` +SHALL move the text so the middle of its extent lies on that point +projected onto the sketch. + +#### Scenario: The middle of a bar +- **WHEN** the bar runs from x = 0 to 120 and `center_at` is `[60, 2, 0]` + on its top face +- **THEN** the text's middle is at x = 60 mm, across the bar's middle + +#### Scenario: Read from the underside +- **WHEN** the sketch is opened on the bar's bottom face (`face_point`) + and the text centred at `[60, -2, 0]` +- **THEN** seen from below the text reads left to right, centred + +### Requirement: A linked property shows its dimension when written +Text containing `$PRP:"name"`, where the custom property `name` holds a +dimension's name in quotes (`"D1@Sketch3"`), SHALL show that dimension's +value at the moment the text is written. SolidWorks doesn't redraw sketch +text when the model rebuilds, so the text keeps that value until it is +written again (`set_sketch_text`). + +#### Scenario: Written at 13 mm +- **WHEN** the text is `size $PRP:"WrenchSize" mm` and `WrenchSize` is + `"D1@Sketch3"`, which is 13 mm +- **THEN** the text reads `size 13.00 mm`, and still does after an + equation changes `D1@Sketch3` to 19 mm and the model rebuilds + +### Requirement: Re-letter a sketch's text +`set_sketch_text` SHALL replace the text of every sketch text in the +named sketch with `text`, with the sketch open for editing (the only way +SolidWorks redraws it), close the sketch, rebuild, and reply with the +sketch and each text's string before and after (links read when +asked, so `before` can already hold a new value the lettering doesn't +show yet). A sketch that doesn't exist, or has no text, SHALL fail and +change nothing. + +#### Scenario: The size changed +- **WHEN** the lettering above is in `Sketch12`, `D1@Sketch3` is now 19 mm, + and `set_sketch_text` is called with `Sketch12` and the same + `size $PRP:"WrenchSize" mm` +- **THEN** the reply's `after` is `size 19.00 mm`, and the cut from that + sketch reads 19.00 + +#### Scenario: No such sketch +- **WHEN** `set_sketch_text` is called with `Sketch99` +- **THEN** it fails as not found and nothing changes diff --git a/openspec/changes/equations-and-global-variables/tasks.md b/openspec/changes/equations-and-global-variables/tasks.md new file mode 100644 index 00000000..99ae836b --- /dev/null +++ b/openspec/changes/equations-and-global-variables/tasks.md @@ -0,0 +1,26 @@ +## 1. Adapter + +- [x] 1.1 Adapter interface `list_equations`, `set_equation`, `delete_equation` through `base.py`, `circuit_breaker.py`, `connection_pool.py`; tests +- [x] 1.2 Real adapter mixin `adapters/solidworks/equations.py`: walk, name parse, dimension check, `Add2`, the `Equation` property put and `SetEquationAndConfigurationOption(..., 1, None)` per configuration (design decision 4) with read-back and restore, `Delete`, `EvaluateAll` + rebuild; tests with a fake that refuses configuration-name arrays as SolidWorks does +- [x] 1.3 Mock adapter: equation list, simple values, refusal of an unknown global variable; tests + +## 2. Tools + +- [x] 2.1 `tools/equations.py`: inputs (name and expression checks, `configurations`), the three tools, registration; tests +- [x] 2.2 `equation_refused` classifier rule; hints, support levels, toolsets; tool count 143; the `delete_` meaning in the description standard + +## 3. Docs + +- [x] 3.1 Catalog page; the agent skill's note on making a part parametric; CHANGELOG; queue row 29; progress bars regenerated +- [x] 3.2 Full mock suite at 100% coverage, ruff, mypy, `mkdocs build --strict` + +## 4. Live + +- [x] 4.1 Live probes of `IEquationMgr` (2026-11-17/18) and the fixes they led to (design decision 4); `Value` is in the document's units +- [x] 4.2 Wrench demo `tests/live/test_live_sw_equations_wrench.py`: 13 mm combination wrench, 19 equations, `Size` = 19mm regrows it, 8 mm in its own configuration, a bad expression refused; passed live and recorded 2026-11-18. Needed `create_cut_extrude` mid-plane for Blind `both_directions`, a polygon `diameter` dimension and `add_polygon` `angle`; tests for each +- [x] 4.3 Demos page section, README tile, catalog notes, CHANGELOG +- [x] 4.5 The wrench closer to the user's reference (review 2026-11-18): the jaw bottom curved by an ellipse cut (`add_ellipse` `angle`; `add_sketch_dimension` `major_axis` / `minor_axis` on an ellipse), neck fillets on both heads sized by Size, material 1.8159 (51CrV4) chrome-vanadium steel; tests for each tool change +- [x] 4.7 `add_sketch_text` (design: Text on the wrench's handle): adapter (`InsertSketchText` at a point, `CharHeight`, `center_at` by measuring its edges), `base`/`circuit_breaker`/`connection_pool`/mock, the tool, hints, support level, toolset, catalog; tests. The wrench debosses "solidworksmcp-python" and its size (`$PRP:` linked to a Size dimension) into both faces of the handle, centred at every size (cut on a spare block, patterned onto the handle by `"Size" * 6.48 + 190mm`), and each evidence line shows the equation set and the size before and after +- [x] 4.8 `set_sketch_text` (design: Text on the wrench's handle): re-letter a sketch's text in edit mode, rebuild; adapter, wrappers, mock, tool, hints, support level, catalog, tool count 145; tests. The wrench demo re-letters after each size change +- [x] 4.6 Once the user approves the wrench: re-record, then the demos page section, README tile, catalog notes and CHANGELOG (approved and recorded 2026-11-18: 27 equations, captions at the start of each step) +- [ ] 4.4 The user runs `tests/live/test_live_sw_equations.py` (block tests) and approves the demo; archive after diff --git a/openspec/queue.md b/openspec/queue.md index 26a2fa07..ad12a0c1 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -39,6 +39,8 @@ 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`) | +| 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`) | ## Removed tools (item 10, release 2.1.0) diff --git a/src/solidworks_mcp/adapters/base.py b/src/solidworks_mcp/adapters/base.py index 41d8f900..06ce2409 100644 --- a/src/solidworks_mcp/adapters/base.py +++ b/src/solidworks_mcp/adapters/base.py @@ -813,7 +813,12 @@ async def add_centerline( ) async def add_polygon( - self, center_x: float, center_y: float, radius: float, sides: int + self, + center_x: float, + center_y: float, + radius: float, + sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: """Add a regular polygon to the current sketch. @@ -822,6 +827,7 @@ async def add_polygon( center_y (float): The center y value. radius (float): The radius value. sides (int): The sides value. + angle (float): Degrees the first vertex is turned from +x. Returns: AdapterResult[str]: The result produced by the operation. @@ -837,6 +843,7 @@ async def add_ellipse( center_y: float, major_axis: float, minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: """Add an ellipse to the current sketch. @@ -845,6 +852,7 @@ async def add_ellipse( center_y (float): The center y value. major_axis (float): The major axis value. minor_axis (float): The minor axis value. + angle (float): The major axis's turn from +x, in degrees. Returns: AdapterResult[str]: The result produced by the operation. @@ -854,6 +862,49 @@ async def add_ellipse( error="add_ellipse is not implemented by this adapter", ) + async def add_sketch_text( + self, + text: str, + x: float = 0.0, + y: float = 0.0, + height: float = 3.5, + center_at: list[float] | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Add text to the current sketch. + + Args: + text (str): The text; ``$PRP:"name"`` shows a custom property. + x (float): Start x in mm (sketch coordinates). + y (float): Start y in mm (the baseline). + height (float): Letter height in mm. + center_at (list[float] | None): A model point [x, y, z] in mm for + the text's middle. + + Returns: + AdapterResult[dict[str, Any]]: ``id``, ``text`` and ``height``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="add_sketch_text is not implemented by this adapter", + ) + + async def set_sketch_text( + self, sketch_name: str, text: str + ) -> AdapterResult[dict[str, Any]]: + """Rewrite the text in a sketch, with the sketch open, then rebuild. + + Args: + sketch_name (str): The sketch, e.g. ``Sketch12``. + text (str): The new text. + + Returns: + AdapterResult[dict[str, Any]]: ``sketch``, ``before`` and ``after``. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="set_sketch_text is not implemented by this adapter", + ) + async def add_sketch_constraint( self, entity1: str, @@ -1507,6 +1558,49 @@ async def delete_configuration( error="delete_configuration is not implemented by this adapter", ) + async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]: + """List the active model's equations and global variables. + + Returns: + AdapterResult[list[dict[str, Any]]]: Not implemented by this adapter. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="list_equations is not implemented by this adapter", + ) + + async def set_equation( + self, + name: str, + expression: str, + configurations: str | list[str] = "all", + ) -> AdapterResult[dict[str, Any]]: + """Add an equation, or change the one ``name`` has. + + Args: + name (str): A global variable or a dimension (``D1@Sketch1``). + expression (str): The right-hand side. + configurations (str | list[str]): "all", "this" or names. + + Returns: + AdapterResult[dict[str, Any]]: Not implemented by this adapter. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="set_equation is not implemented by this adapter", + ) + + async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]: + """Delete the equation for ``name``. + + Returns: + AdapterResult[dict[str, Any]]: Not implemented by this adapter. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="delete_equation is not implemented by this adapter", + ) + async def active_configuration( self, ) -> AdapterResult[str]: diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index 2ceb895d..4e66f2ad 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -1187,6 +1187,37 @@ async def delete_configuration( }, ) + async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]: + """List the active model's equations through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "list_equations", lambda: self.adapter.list_equations() + ) + + async def set_equation( + self, + name: str, + expression: str, + configurations: str | list[str] = "all", + ) -> AdapterResult[dict[str, Any]]: + """Add or change an equation through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "set_equation", + lambda: self.adapter.set_equation(name, expression, configurations), + input_dict={ + "name": name, + "expression": expression, + "configurations": configurations, + }, + ) + + async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]: + """Delete an equation through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "delete_equation", + lambda: self.adapter.delete_equation(name), + input_dict={"name": name}, + ) + async def active_configuration( self, ) -> AdapterResult[str]: @@ -1401,12 +1432,17 @@ async def add_spline(self, points: list[dict[str, float]]) -> AdapterResult[str] ) async def add_polygon( - self, center_x: float, center_y: float, radius: float, sides: int + self, + center_x: float, + center_y: float, + radius: float, + sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: """Add polygon through circuit breaker.""" return await self._execute_with_circuit_breaker( "add_polygon", - lambda: self.adapter.add_polygon(center_x, center_y, radius, sides), + lambda: self.adapter.add_polygon(center_x, center_y, radius, sides, angle), input_dict={ "center_x": center_x, "center_y": center_y, @@ -1421,12 +1457,13 @@ async def add_ellipse( center_y: float, major_axis: float, minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: """Add ellipse through circuit breaker.""" return await self._execute_with_circuit_breaker( "add_ellipse", lambda: self.adapter.add_ellipse( - center_x, center_y, major_axis, minor_axis + center_x, center_y, major_axis, minor_axis, angle ), input_dict={ "center_x": center_x, @@ -1436,6 +1473,28 @@ async def add_ellipse( }, ) + async def add_sketch_text( + self, + text: str, + x: float = 0.0, + y: float = 0.0, + height: float = 3.5, + center_at: list[float] | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Add sketch text through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "add_sketch_text", + lambda: self.adapter.add_sketch_text(text, x, y, height, center_at), + ) + + async def set_sketch_text( + self, sketch_name: str, text: str + ) -> AdapterResult[dict[str, Any]]: + """Rewrite sketch text through circuit breaker.""" + return await self._execute_with_circuit_breaker( + "set_sketch_text", lambda: self.adapter.set_sketch_text(sketch_name, text) + ) + 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 68064ed5..7edbbc00 100644 --- a/src/solidworks_mcp/adapters/connection_pool.py +++ b/src/solidworks_mcp/adapters/connection_pool.py @@ -1033,6 +1033,30 @@ async def delete_configuration( lambda adapter: adapter.delete_configuration(name), ) + async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]: + """List the active model's equations using pool.""" + return await self._execute_with_pool( + "list_equations", lambda adapter: adapter.list_equations() + ) + + async def set_equation( + self, + name: str, + expression: str, + configurations: str | list[str] = "all", + ) -> AdapterResult[dict[str, Any]]: + """Add or change an equation using pool.""" + return await self._execute_with_pool( + "set_equation", + lambda adapter: adapter.set_equation(name, expression, configurations), + ) + + async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]: + """Delete an equation using pool.""" + return await self._execute_with_pool( + "delete_equation", lambda adapter: adapter.delete_equation(name) + ) + async def active_configuration( self, ) -> AdapterResult[str]: @@ -1228,7 +1252,12 @@ async def add_spline(self, points: list[dict[str, float]]) -> AdapterResult[str] ) async def add_polygon( - self, center_x: float, center_y: float, radius: float, sides: int + self, + center_x: float, + center_y: float, + radius: float, + sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: """Add polygon using pool. @@ -1237,13 +1266,16 @@ async def add_polygon( center_y (float): The center y value. radius (float): The radius value. sides (int): The sides value. + angle (float): Degrees the first vertex is turned from +x. Returns: AdapterResult[str]: The result produced by the operation. """ return await self._execute_with_pool( "add_polygon", - lambda adapter: adapter.add_polygon(center_x, center_y, radius, sides), + lambda adapter: adapter.add_polygon( + center_x, center_y, radius, sides, angle + ), ) async def add_ellipse( @@ -1252,6 +1284,7 @@ async def add_ellipse( center_y: float, major_axis: float, minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: """Add ellipse using pool. @@ -1260,6 +1293,7 @@ async def add_ellipse( center_y (float): The center y value. major_axis (float): The major axis value. minor_axis (float): The minor axis value. + angle (float): The major axis's turn from +x, in degrees. Returns: AdapterResult[str]: The result produced by the operation. @@ -1267,10 +1301,53 @@ async def add_ellipse( return await self._execute_with_pool( "add_ellipse", lambda adapter: adapter.add_ellipse( - center_x, center_y, major_axis, minor_axis + center_x, center_y, major_axis, minor_axis, angle ), ) + async def add_sketch_text( + self, + text: str, + x: float = 0.0, + y: float = 0.0, + height: float = 3.5, + center_at: list[float] | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Add sketch text using pool. + + Args: + text (str): The text; ``$PRP:"name"`` shows a custom property. + x (float): Start x in mm (sketch coordinates). + y (float): Start y in mm (the baseline). + height (float): Letter height in mm. + center_at (list[float] | None): A model point [x, y, z] in mm for + the text's middle. + + Returns: + AdapterResult[dict[str, Any]]: The result produced by the operation. + """ + return await self._execute_with_pool( + "add_sketch_text", + lambda adapter: adapter.add_sketch_text(text, x, y, height, center_at), + ) + + async def set_sketch_text( + self, sketch_name: str, text: str + ) -> AdapterResult[dict[str, Any]]: + """Rewrite sketch text using pool. + + Args: + sketch_name (str): The sketch. + text (str): The new text. + + Returns: + AdapterResult[dict[str, Any]]: The result produced by the operation. + """ + return await self._execute_with_pool( + "set_sketch_text", + lambda adapter: adapter.set_sketch_text(sketch_name, text), + ) + 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 a190423a..edab95c9 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -31,6 +31,7 @@ SweepParameters, ) from .mock_drawing_pack import MockDrawingPackMixin +from .mock_equations import MockEquationsMixin from .mock_sheet_metal import MockSheetMetalMixin from .mock_templates import MockTemplatesMixin from .solidworks.documentation import MATERIAL_PROPERTIES @@ -143,7 +144,11 @@ def __bool__(self) -> bool: class MockSolidWorksAdapter( - MockSheetMetalMixin, MockTemplatesMixin, MockDrawingPackMixin, SolidWorksAdapter + MockSheetMetalMixin, + MockTemplatesMixin, + MockDrawingPackMixin, + MockEquationsMixin, + SolidWorksAdapter, ): """Mock adapter that simulates SolidWorks operations. @@ -1941,14 +1946,16 @@ async def add_ellipse( center_y: float, major_axis: float, minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: - """Mock adding an axis-aligned ellipse to sketch. + """Mock adding an ellipse to sketch. Args: center_x (float): Ellipse centre X in millimetres. center_y (float): Ellipse centre Y in millimetres. major_axis (float): Full major-axis length in millimetres. minor_axis (float): Full minor-axis length in millimetres. + angle (float): The major axis's turn from +x, in degrees. Returns: AdapterResult[str]: The result produced by the operation. @@ -1970,8 +1977,69 @@ async def add_ellipse( execution_time=self._delays["sketch_operation"] / 2, ) + async def add_sketch_text( + self, + text: str, + x: float = 0.0, + y: float = 0.0, + height: float = 3.5, + center_at: list[float] | None = None, + ) -> AdapterResult[dict[str, Any]]: + """Mock adding sketch text: an id, the text as given, the height. + + Args: + text (str): The text; ``$PRP:"name"`` shows a custom property. + x (float): Start x in mm (sketch coordinates). + y (float): Start y in mm (the baseline). + height (float): Letter height in mm. + center_at (list[float] | None): A model point [x, y, z] in mm for + the text's middle. + + Returns: + AdapterResult[dict[str, Any]]: ``id``, ``text`` and ``height``. + """ + if not self._current_sketch: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active sketch" + ) + self._operation_count += 1 + text_id = f"Text_{random.randint(1000, 9999)}" + self._sketch_entity_ids.add(text_id) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"id": text_id, "text": text, "height": height}, + execution_time=self._delays["sketch_operation"] / 2, + ) + + async def set_sketch_text( + self, sketch_name: str, text: str + ) -> AdapterResult[dict[str, Any]]: + """Mock rewriting a sketch's text: the text given, before and after. + + Args: + sketch_name (str): The sketch. + text (str): The new text. + + Returns: + AdapterResult[dict[str, Any]]: ``sketch``, ``before`` and ``after``. + """ + if not self._current_model: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active model" + ) + self._operation_count += 1 + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"sketch": sketch_name, "before": [], "after": [text]}, + ) + async def add_polygon( - self, center_x: float, center_y: float, radius: float, sides: int + self, + center_x: float, + center_y: float, + radius: float, + sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: """Mock adding a regular polygon to sketch. @@ -1982,6 +2050,7 @@ async def add_polygon( to each vertex; matches the real adapter's ``CreatePolygon(..., Inscribed=True)`` semantics). sides (int): Number of polygon sides. + angle (float): Degrees the first vertex is turned from +x. Returns: AdapterResult[str]: The result produced by the operation. diff --git a/src/solidworks_mcp/adapters/mock_equations.py b/src/solidworks_mcp/adapters/mock_equations.py new file mode 100644 index 00000000..d18daa15 --- /dev/null +++ b/src/solidworks_mcp/adapters/mock_equations.py @@ -0,0 +1,203 @@ +"""The mock adapter's equations and global variables, kept in memory. + +Values are worked out for simple expressions: numbers (with an optional +``mm``, ``in`` or ``deg``, kept as written), quoted names of equations that +have a value, ``+ - * /`` and brackets. Anything else has no value, as an +equation SolidWorks can't solve. A quoted name with no equation is refused, +as SolidWorks refuses it, so the ``equation_refused`` path runs without +SolidWorks. +""" + +from __future__ import annotations + +import ast +import operator +import re +from typing import Any + +from .base import AdapterResult, AdapterResultStatus +from .solidworks.equations import equation_text + +_OPERATORS: dict[type, Any] = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Div: operator.truediv, +} +_QUOTED = re.compile(r'"([^"]*)"') +_UNITS = re.compile(r"(\d)\s*(mm|in|deg)\b") + + +def _arithmetic(node: ast.AST) -> float: + """The value of a tree of numbers, ``+ - * /`` and signs. + + Raises: + ValueError: For anything else. + """ + if isinstance(node, ast.Expression): + return _arithmetic(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): + return float(node.value) + if isinstance(node, ast.BinOp) and type(node.op) in _OPERATORS: + return float( + _OPERATORS[type(node.op)](_arithmetic(node.left), _arithmetic(node.right)) + ) + if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + value = _arithmetic(node.operand) + return -value if isinstance(node.op, ast.USub) else value + raise ValueError("not arithmetic") + + +def mock_value(expression: str, values: dict[str, float | None]) -> float | None: + """The value of ``expression``, with quoted names looked up in ``values``. + + Args: + expression: The right-hand side of an equation. + values: Each equation's value by lower-case name. + + Returns: + The value, or None when it can't be worked out. + + Raises: + LookupError: A quoted name has no equation. + """ + missing = [n for n in _QUOTED.findall(expression) if n.lower() not in values] + if missing: + raise LookupError(missing[0]) + names = {n.lower(): values[n.lower()] for n in _QUOTED.findall(expression)} + if any(v is None for v in names.values()): + return None + text = _QUOTED.sub(lambda m: repr(names[m.group(1).lower()]), expression) + try: + return _arithmetic(ast.parse(_UNITS.sub(r"\1", text), mode="eval")) + except (SyntaxError, ValueError, ZeroDivisionError): + return None + + +class MockEquationsMixin: + """``list_equations``, ``set_equation`` and ``delete_equation`` for the mock.""" + + _current_model: Any + _dimensions: dict[str, float] + + def _mock_equations(self) -> list[dict[str, Any]]: + """The active model's equations, in order.""" + if "_equations" not in self.__dict__: + self._equations: dict[str, list[dict[str, Any]]] = {} + return self._equations.setdefault(self._current_model.name, []) + + def _mock_solve(self) -> list[dict[str, Any]]: + """Every equation with its value; dimensions take theirs.""" + values: dict[str, float | None] = {} + rows = [] + for index, row in enumerate(self._mock_equations()): + value = mock_value(row["expression"], values) + values[row["name"].lower()] = value + if row["kind"] == "dimension" and value is not None: + self._dimensions[row["name"]] = value + rows.append({"index": index, **row, "value": value}) + return rows + + def _no_model(self) -> AdapterResult[Any] | None: + """An error when no model is open.""" + if self._current_model: + return None + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active model") + + async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]: + """The active model's equations, as the real adapter lists them. + + Returns: + AdapterResult[list[dict[str, Any]]]: Each with its value. + """ + refused = self._no_model() + if refused: + return refused + return AdapterResult( + status=AdapterResultStatus.SUCCESS, data=self._mock_solve() + ) + + async def set_equation( + self, + name: str, + expression: str, + configurations: str | list[str] = "all", + ) -> AdapterResult[dict[str, Any]]: + """Add or change an equation, as the real adapter does. + + Args: + name: A global variable, or a dimension such as ``D1@Sketch1``. + expression: The right-hand side. + configurations: ``"all"``, ``"this"`` or configuration names. + + Returns: + AdapterResult[dict[str, Any]]: The equation, its value and action. + """ + refused = self._no_model() + if refused: + return refused + scope = self._mock_scope(configurations) # type: ignore[attr-defined] + if isinstance(scope, AdapterResult): + return scope + if "@" in name and name not in self._dimensions: + return AdapterResult( + status=AdapterResultStatus.ERROR, + error=f"No dimension named '{name}' in the active document; read " + "the names with list_model_dimensions.", + ) + rows = self._mock_equations() + index = next( + (i for i, r in enumerate(rows) if r["name"].lower() == name.lower()), + None, + ) + values = {r["name"].lower(): r["value"] for r in self._mock_solve()} + try: + mock_value(expression, values) + except LookupError: + return AdapterResult( + status=AdapterResultStatus.ERROR, + error=f"SolidWorks refused the equation {equation_text(name, expression)}; " + "nothing was changed.", + ) + kind = "dimension" if "@" in name else "global_variable" + row = {"name": name, "expression": expression.strip(), "kind": kind} + if index is None: + rows.append(row) + index, action = len(rows) - 1, "added" + else: + rows[index] = row + action = "changed" + solved = self._mock_solve()[index] + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={**solved, "action": action, "configurations": scope}, + ) + + async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]: + """Delete an equation, as the real adapter does. + + Args: + name: The equation's name. + + Returns: + AdapterResult[dict[str, Any]]: The deleted name and those left. + """ + refused = self._no_model() + if refused: + return refused + rows = self._mock_equations() + index = next( + (i for i, r in enumerate(rows) if r["name"].lower() == name.lower()), + None, + ) + if index is None: + known = ", ".join(r["name"] for r in rows) or "none" + return AdapterResult( + status=AdapterResultStatus.ERROR, + error=f"No equation named '{name}'; the model has {known}.", + ) + deleted = rows.pop(index) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"deleted": deleted["name"], "equations": [r["name"] for r in rows]}, + ) diff --git a/src/solidworks_mcp/adapters/pywin32_adapter.py b/src/solidworks_mcp/adapters/pywin32_adapter.py index e0d67f9e..cb276fd2 100644 --- a/src/solidworks_mcp/adapters/pywin32_adapter.py +++ b/src/solidworks_mcp/adapters/pywin32_adapter.py @@ -29,6 +29,7 @@ SolidWorksDocumentationMixin, SolidWorksDrawingPackMixin, SolidWorksDrawingStandardMixin, + SolidWorksEquationsMixin, SolidWorksFeaturesMixin, SolidWorksIOMixin, SolidWorksPartFeaturesMixin, @@ -1719,6 +1720,7 @@ class PyWin32Adapter( SolidWorksTemplatesMixin, SolidWorksDrawingPackMixin, SolidWorksDrawingStandardMixin, + SolidWorksEquationsMixin, SolidWorksDocumentationMixin, SolidWorksSketchMixin, SolidWorksConfigurationsMixin, diff --git a/src/solidworks_mcp/adapters/solidworks/__init__.py b/src/solidworks_mcp/adapters/solidworks/__init__.py index ebf60b72..0bf08fa7 100644 --- a/src/solidworks_mcp/adapters/solidworks/__init__.py +++ b/src/solidworks_mcp/adapters/solidworks/__init__.py @@ -4,6 +4,7 @@ from .documentation import SolidWorksDocumentationMixin from .drawing_pack import SolidWorksDrawingPackMixin from .drawing_standard import SolidWorksDrawingStandardMixin +from .equations import SolidWorksEquationsMixin from .features import SolidWorksFeaturesMixin from .io import SolidWorksIOMixin from .part_features import SolidWorksPartFeaturesMixin @@ -17,6 +18,7 @@ "SolidWorksDocumentationMixin", "SolidWorksDrawingPackMixin", "SolidWorksDrawingStandardMixin", + "SolidWorksEquationsMixin", "SolidWorksFeaturesMixin", "SolidWorksIOMixin", "SolidWorksPartFeaturesMixin", diff --git a/src/solidworks_mcp/adapters/solidworks/equations.py b/src/solidworks_mcp/adapters/solidworks/equations.py new file mode 100644 index 00000000..882005ff --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/equations.py @@ -0,0 +1,349 @@ +"""Equations and global variables: list, add or change, and delete them. + +One value (``"Width" = 60mm``) can drive several dimensions +(``"D1@Sketch1" = "Width" / 2``), which is how a SolidWorks part becomes +parametric. + +COM calls (argument lists from the installed 2026 type library), all on +``IModelDoc2.GetEquationMgr()``. What each returns was measured on +SolidWorks 2026 (the equations live probe, 2026-11-18): + +- ``GetCount()``, and the indexed properties ``Equation(i)``, ``Value(i)`` + and ``GlobalVariable(i)``; ``Equation(i)`` reads the active + configuration's text; +- ``Add2(Index, Equation, Solve)`` returns the new index, or -1 when + SolidWorks refuses the text. It adds to every configuration; +- writing the ``Equation(i)`` property changes an equation in every + configuration (its scope goes back to all). A text SolidWorks can't use + is refused: ``Status`` becomes -1 and the stored text doesn't change; +- ``SetEquationAndConfigurationOption(Index, Equation, 1, None)`` (this + configuration) returns 0 when it worked. Named configurations are set one + at a time, each made active in turn, then the active one is shown again. + Given any array of configuration names it returns -1, and with option 2 + (all) it returns -1 on a part with many equations (19 in the wrench demo), + which is why "all" writes the property instead. ``Add3`` takes names too + and fails the same way, so it isn't used; +- ``Delete(Index)``; ``EvaluateAll()``, whose return value isn't used (it + returned -1 on a part that solved); +- ``Status``, the last operation's result: -1 when it failed, so an added + equation SolidWorks couldn't solve is deleted again. + +``IModelDoc2.Parameter(name)`` checks a dimension name before anything is +written. +""" + +from __future__ import annotations + +import re +from typing import Any, cast + +from .. import sw_type_info +from ..base import AdapterResult, AdapterResultStatus +from .configurations import ( + ALL_CONFIGURATIONS, + THIS_CONFIGURATION, + _active, + configuration_scope, +) + +#: The left-hand side of an equation: the text between its first quotes. +_NAME = re.compile(r'^\s*"([^"]*)"') + + +def equation_text(name: str, expression: str) -> str: + """The equation SolidWorks stores for ``name`` = ``expression``.""" + return f'"{name}" = {expression.strip()}' + + +def split_equation(text: str) -> tuple[str, str]: + """An equation's name and expression, from its text. + + Text with no quoted name (not one SolidWorks writes) gives an empty name + and the whole text as the expression. + """ + match = _NAME.match(text) + if not match: + return "", text.strip() + rest = text[match.end() :].lstrip() + return match.group(1), rest[1:].strip() if rest.startswith("=") else rest + + +def _same(a: str, b: str) -> bool: + """Whether two equation texts match, ignoring spaces and case.""" + return re.sub(r"\s+", "", a).lower() == re.sub(r"\s+", "", b).lower() + + +def _failed(manager: Any) -> bool: + """Whether the last operation failed: ``Status`` is negative then.""" + status = manager.Status + return isinstance(status, int) and status < 0 + + +def _add(manager: Any, index: int, text: str) -> int: + """Add ``text`` at ``index`` (-1: at the end); its index, or -1 if refused. + + An equation ``Add2`` accepts but can't solve leaves ``Status`` negative; + it is deleted again so nothing half-made stays in the model. + """ + added = int(manager.Add2(index, text, True)) + if added >= 0 and _failed(manager): + manager.Delete(added) + return -1 + return added + + +#: ``DISPATCH_PROPERTYPUT`` (pythoncom's value, written out so the module +#: imports on machines without pywin32, such as CI). +_DISPATCH_PROPERTYPUT = 4 + + +def _took(manager: Any, index: int, text: str) -> bool: + """Whether SolidWorks kept ``text`` for equation ``index``. + + ``Status`` isn't negative and the stored text reads back the same + (SolidWorks may respace it). + """ + return not _failed(manager) and _same(str(manager.Equation(index)), text) + + +def _put_everywhere(manager: Any, index: int, text: str) -> bool: + """Write the ``Equation(index)`` property: the text in every configuration. + + pywin32's late binding reads indexed properties but can't assign one, so + the property put goes through ``IDispatch.Invoke``. + """ + dispatch = manager._oleobj_ + dispid = dispatch.GetIDsOfNames("Equation") + dispatch.Invoke(dispid, 0, _DISPATCH_PROPERTYPUT, False, index, text) + return _took(manager, index, text) + + +def _set_here(manager: Any, index: int, text: str) -> bool: + """Set equation ``index`` to ``text`` in the active configuration only.""" + returned = manager.SetEquationAndConfigurationOption( + index, text, THIS_CONFIGURATION, None + ) + return returned == 0 and _took(manager, index, text) + + +def _kind(name: str, is_global: bool) -> str: + """``global_variable``, ``dimension`` (a name with ``@``) or ``other``.""" + if is_global: + return "global_variable" + return "dimension" if "@" in name else "other" + + +class SolidWorksEquationsMixin: + """List, add or change, and delete equations and global variables.""" + + def _equation_manager(self) -> Any: + """The active model's equation manager, its methods flagged.""" + adapter: Any = self + return sw_type_info.flagged( + adapter.currentModel.GetEquationMgr(), "IEquationMgr" + ) + + def _equations(self, manager: Any) -> list[dict[str, Any]]: + """Every equation, in order, with its solved value.""" + adapter: Any = self + rows = [] + for index in range(int(manager.GetCount() or 0)): + text = str(manager.Equation(index)) + name, expression = split_equation(text) + is_global = bool( + adapter._attempt(lambda i=index: manager.GlobalVariable(i), False) + ) + value = adapter._attempt(lambda i=index: manager.Value(i), None) + rows.append( + { + "index": index, + "name": name, + "expression": expression, + "kind": _kind(name, is_global), + "value": float(value) if value is not None else None, + } + ) + return rows + + def _set( + self, + index: int, + text: str, + option: int, + names: list[str], + values: dict[str, Any] | None = None, + ) -> bool: + """Set equation ``index`` to ``text`` where ``option`` says. + + All configurations and the active one are one call each. Named + configurations are set one at a time with "this configuration", each + made active in turn, and the configuration that was active is shown + again afterwards, whatever happens. + + Args: + index: The equation's index. + text: The whole equation, e.g. ``'"Size" = 8mm'``. + option: ``ALL_CONFIGURATIONS``, ``THIS_CONFIGURATION`` or + ``SPECIFY_CONFIGURATION``. + names: The configurations, for ``SPECIFY_CONFIGURATION``. + values: Filled with each named configuration's solved value, + read while it is active. + + Returns: + Whether SolidWorks took the text everywhere it was asked to. + """ + adapter: Any = self + if option == ALL_CONFIGURATIONS: + return _put_everywhere(self._equation_manager(), index, text) + if option == THIS_CONFIGURATION: + return _set_here(self._equation_manager(), index, text) + previous = _active(adapter) + took = True + try: + for name in names: + adapter.currentModel.ShowConfiguration2(name) + manager = self._equation_manager() + took = _set_here(manager, index, text) and took + if values is not None: + self._solve(manager) + value = adapter._attempt(lambda m=manager: m.Value(index), None) + values[name] = float(value) if value is not None else None + finally: + if previous: + adapter.currentModel.ShowConfiguration2(previous) + return took + + def _solve(self, manager: Any) -> None: + """Solve every equation, then rebuild.""" + adapter: Any = self + adapter._attempt(lambda: manager.EvaluateAll(), None) + adapter._attempt(lambda: adapter.currentModel.ForceRebuild3(False), None) + + def _on_model(self, operation: str, build: Any) -> AdapterResult[Any]: + """Run ``build`` on the COM thread when a model is open.""" + adapter: Any = self + if not adapter.currentModel: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active model" + ) + return cast(AdapterResult[Any], adapter._handle_com_operation(operation, build)) + + async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]: + """Every equation and global variable of the active model. + + Returns: + Each with ``index``, ``name``, ``expression``, ``kind`` and + ``value`` (in the document's units, or None). + """ + + def build() -> list[dict[str, Any]]: + return self._equations(self._equation_manager()) + + return self._on_model("list_equations", build) + + async def set_equation( + self, + name: str, + expression: str, + configurations: str | list[str] = "all", + ) -> AdapterResult[dict[str, Any]]: + """Add an equation for ``name``, or change the one there is. + + Args: + name: A global variable, or a dimension such as ``D1@Sketch1``. + expression: The right-hand side, e.g. ``60mm`` or ``"Width" / 2``. + configurations: ``"all"``, ``"this"`` or configuration names. + + Returns: + The stored equation, its value, ``action`` (``added`` or + ``changed``) and the configurations it applies in; for named + configurations, the expression set and ``values``, its solved + value in each of them. + """ + adapter: Any = self + + def build() -> dict[str, Any]: + option, names, _array = configuration_scope(adapter, configurations) + if "@" in name and not adapter.currentModel.Parameter(name): + raise LookupError( + f"No dimension named '{name}' in the active document; read " + "the names with list_model_dimensions." + ) + manager = self._equation_manager() + text = equation_text(name, expression) + values: dict[str, Any] = {} + existing = next( + ( + row + for row in self._equations(manager) + if row["name"].lower() == name.lower() + ), + None, + ) + if existing is None: + index = _add(manager, -1, text) + if index < 0: + raise ValueError( + f"SolidWorks refused the equation {text}; nothing was added." + ) + if option != ALL_CONFIGURATIONS and not self._set( + index, text, option, names, values + ): + self._equation_manager().Delete(index) + raise ValueError( + f"SolidWorks refused the equation {text} in " + f"{', '.join(names)}; nothing was added." + ) + action = "added" + else: + index = existing["index"] + previous = str(manager.Equation(index)) + if not self._set(index, text, option, names, values): + self._set(index, previous, option, names) + raise ValueError( + f"SolidWorks refused the equation {text}; the equation " + f"was left as {previous}." + ) + action = "changed" + manager = self._equation_manager() + self._solve(manager) + row = self._equations(manager)[index] + if values: + # The row is read in the active configuration; say what was + # set instead: the expression, its value in the first named + # configuration, and in each one it was set in. + row = { + **row, + "expression": expression.strip(), + "value": values[names[0]], + "values": values, + } + return {**row, "action": action, "configurations": names} + + return self._on_model("set_equation", build) + + async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]: + """Delete the equation for ``name``. + + Args: + name: The equation's name (its left-hand side). + + Returns: + The deleted name and the names left. + """ + + def build() -> dict[str, Any]: + manager = self._equation_manager() + rows = self._equations(manager) + match = next((r for r in rows if r["name"].lower() == name.lower()), None) + if match is None: + known = ", ".join(r["name"] for r in rows) or "none" + raise LookupError(f"No equation named '{name}'; the model has {known}.") + manager.Delete(match["index"]) + self._solve(manager) + return { + "deleted": match["name"], + "equations": [r["name"] for r in self._equations(manager)], + } + + return self._on_model("delete_equation", build) diff --git a/src/solidworks_mcp/adapters/solidworks/features.py b/src/solidworks_mcp/adapters/solidworks/features.py index 5209f8d9..e6c2254b 100644 --- a/src/solidworks_mcp/adapters/solidworks/features.py +++ b/src/solidworks_mcp/adapters/solidworks/features.py @@ -1485,7 +1485,9 @@ def _create_cut_extrude_impl( ``"through_all_both"`` (through all in both directions, cut as a double-ended Through All feature). - ``both_directions`` (bool): With ``"ThroughAll"``, cut through - all in both directions (same as ``"ThroughAllBoth"``). + all in both directions (same as ``"ThroughAllBoth"``); with + ``"Blind"``, a mid-plane cut ``depth`` deep in total, centred on + the sketch plane (as ``create_extrusion`` does). - ``feature_scope`` (bool): Limit cut to selected bodies. - ``auto_select`` (bool): Auto-select bodies in scope. - ``sketch_name`` (str | None): Sketch to cut from. See sketch @@ -1600,6 +1602,20 @@ def _cut_operation() -> SolidWorksFeature: reverse, ), ] + elif normalized.both_directions: + # Blind both ways is a mid-plane cut: ``depth`` in total, centred + # on the sketch plane, as create_extrusion does. It used to be cut + # one way only, so a slot meant to straddle its plane came out on + # one side of it (seen live on SW 2026, the wrench demo's jaw). + forms = [ + ( + " [mid-plane]", + True, + adapter.constants["swEndCondMidPlane"], + blind, + reverse, + ), + ] else: # One direction (Blind or Through All) is single-ended: Sd means # "single direction" (#193). Direction 1 follows the sketch diff --git a/src/solidworks_mcp/adapters/solidworks/sketch.py b/src/solidworks_mcp/adapters/solidworks/sketch.py index fac1744c..96aa934f 100644 --- a/src/solidworks_mcp/adapters/solidworks/sketch.py +++ b/src/solidworks_mcp/adapters/solidworks/sketch.py @@ -9,6 +9,7 @@ from .. import sw_type_info as _sw_type_info from ..base import AdapterResult, AdapterResultStatus +from .com_utils import as_list, double_array # swConstraintType_e values per the official SolidWorks API enum docs # (SolidWorks.Interop.swconst). The legacy IModelDoc2.SketchAddConstraints @@ -142,14 +143,41 @@ async def add_centerline( return _add_centerline_impl(self, x1, y1, x2, y2) async def add_polygon( - self, center_x: float, center_y: float, radius: float, sides: int + self, + center_x: float, + center_y: float, + radius: float, + sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: - return _add_polygon_impl(self, center_x, center_y, radius, sides) + return _add_polygon_impl(self, center_x, center_y, radius, sides, angle) async def add_ellipse( - self, center_x: float, center_y: float, major_axis: float, minor_axis: float + self, + center_x: float, + center_y: float, + major_axis: float, + minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: - return _add_ellipse_impl(self, center_x, center_y, major_axis, minor_axis) + return _add_ellipse_impl( + self, center_x, center_y, major_axis, minor_axis, angle + ) + + async def add_sketch_text( + self, + text: str, + x: float = 0.0, + y: float = 0.0, + height: float = 3.5, + center_at: list[float] | None = None, + ) -> AdapterResult[dict[str, Any]]: + return _add_sketch_text_impl(self, text, x, y, height, center_at) + + async def set_sketch_text( + self, sketch_name: str, text: str + ) -> AdapterResult[dict[str, Any]]: + return _set_sketch_text_impl(self, sketch_name, text) async def add_sketch_constraint( self, @@ -862,6 +890,7 @@ def _add_polygon_impl( center_y: float, radius: float, sides: int, + angle: float = 0.0, ) -> AdapterResult[str]: """Add a regular polygon inscribed in a circle to the active sketch. @@ -869,8 +898,8 @@ def _add_polygon_impl( Inscribed)``. All eight arguments are required by the COM API — passing fewer arguments surfaces a pywin32 ``"Parameter not optional."`` error at the SOLIDWORKS boundary. The vertex point ``(Xp, Yp, Zp)`` is placed on - the positive X axis at ``radius`` from centre, which fixes the polygon's - rotation reproducibly. + positive X axis at ``radius`` from centre, turned by ``angle`` degrees, + which fixes the polygon's rotation reproducibly. Args: adapter: A ``PyWin32Adapter`` with an open sketch. @@ -880,6 +909,7 @@ def _add_polygon_impl( vertex). Corresponds to ``CreatePolygon(..., Inscribed=True)``, i.e. the polygon is inscribed in a circle of this radius. sides: Number of polygon sides. SolidWorks accepts 3–40. + angle: Degrees the vertex point is turned from +X (0 by default). Returns: AdapterResult[str]: On success, ``data`` is the registered entity ID @@ -916,8 +946,8 @@ def _polygon_operation() -> str: center_x / 1000.0, center_y / 1000.0, 0, - (center_x + radius) / 1000.0, - center_y / 1000.0, + (center_x + radius * math.cos(math.radians(angle))) / 1000.0, + (center_y + radius * math.sin(math.radians(angle))) / 1000.0, 0, sides, True, @@ -948,13 +978,13 @@ def _add_ellipse_impl( center_y: float, major_axis: float, minor_axis: float, + angle: float = 0.0, ) -> AdapterResult[str]: - """Add an axis-aligned ellipse to the active sketch. + """Add an ellipse to the active sketch, its major axis turned by ``angle``. - Calls ``SketchManager.CreateEllipse`` with the major-axis endpoint on the - positive X direction from the centre and the minor-axis endpoint on the - positive Y direction. The ellipse is therefore axis-aligned and cannot - be rotated via this function. + Calls ``SketchManager.CreateEllipse`` with the major-axis endpoint + ``angle`` degrees anticlockwise from the sketch's +X and the minor-axis + endpoint a quarter turn further. The created ellipse is registered in the adapter's sketch-entity registry so subsequent constraint and dimension calls can reference it @@ -969,6 +999,7 @@ def _add_ellipse_impl( as the offset from centre). minor_axis: Full minor-axis length in **millimetres** (half is used as the offset from centre). + angle: The major axis's turn from +X, in degrees. Returns: AdapterResult[str]: On success, ``data`` is the registered entity ID @@ -997,15 +1028,18 @@ def _ellipse_operation() -> str: Raises: Exception: If ``CreateEllipse`` returns ``None``. """ + turn = math.radians(angle) + cos, sin = math.cos(turn), math.sin(turn) + major, minor = major_axis / 2, minor_axis / 2 ellipse = adapter.currentSketchManager.CreateEllipse( center_x / 1000.0, center_y / 1000.0, 0, - (center_x + major_axis / 2) / 1000.0, - center_y / 1000.0, + (center_x + major * cos) / 1000.0, + (center_y + major * sin) / 1000.0, 0, - center_x / 1000.0, - (center_y + minor_axis / 2) / 1000.0, + (center_x - minor * sin) / 1000.0, + (center_y + minor * cos) / 1000.0, 0, ) if not ellipse: @@ -1018,6 +1052,203 @@ def _ellipse_operation() -> str: ) +#: ``InsertSketchText``'s width factor and spacing between letters, in per +#: cent; a spacing of 0 stacked every letter on the first (SolidWorks 2026). +_TEXT_NORMAL = 100 + + +def _text_middle(sketch_text: Any) -> list[float]: + """The middle of a sketch text's extent, model metres, from its edges. + + ``ISketchText.GetEdges2`` gives the letters' outline edges; their start + and end points bound the text closely enough to centre it. + + Raises: + Exception: If the text has no edges to measure. + """ + xs: list[float] = [] + ys: list[float] = [] + zs: list[float] = [] + for edge in as_list(sketch_text.GetEdges2()): + params = _sw_type_info.flagged( + _sw_type_info.flagged(edge, "IEdge").GetCurveParams3(), "ICurveParamData" + ) + for point in (params.StartPoint, params.EndPoint): + xs.append(float(point[0])) + ys.append(float(point[1])) + zs.append(float(point[2])) + if not xs: + raise Exception("The sketch text has no edges to centre it by") + return [(min(v) + max(v)) / 2 for v in (xs, ys, zs)] + + +def _to_sketch_space(adapter: Any, point_m: list[float]) -> list[float]: + """A model point (metres) in the open sketch's coordinates (metres).""" + 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_m)), "IMathPoint" + ) + sketch = _sw_type_info.flagged(adapter.currentSketch, "ISketch") + moved = _sw_type_info.flagged( + point.MultiplyTransform(sketch.ModelToSketchTransform), "IMathPoint" + ) + return [float(v) for v in as_list(moved.ArrayData)[:3]] + + +def _centre_text(adapter: Any, sketch_text: Any, point_mm: list[float]) -> None: + """Move ``sketch_text`` so its middle is at model point ``point_mm``. + + ``InsertSketchText``'s centre alignment didn't centre the text (on SW + 2026 it dropped the selected line and started the text at the sketch's + origin), so the text is measured and moved: its middle, mapped into the + sketch, and ``SetCoordinates`` shifted by the difference to the point, + mapped into the sketch the same way (projected onto its plane). + """ + middle = _to_sketch_space(adapter, _text_middle(sketch_text)) + target = _to_sketch_space(adapter, [c / 1000.0 for c in point_mm]) + at = [float(v) for v in as_list(sketch_text.GetCoordinates())] + sketch_text.SetCoordinates( + at[0] + target[0] - middle[0], at[1] + target[1] - middle[1], at[2] + ) + + +def _add_sketch_text_impl( + adapter: Any, + text: str, + x: float, + y: float, + height: float, + center_at: list[float] | None, +) -> AdapterResult[dict[str, Any]]: + """Add text to the active sketch, from a point or centred on one. + + ``IModelDoc2.InsertSketchText`` puts the text at the point; the letter + height is the text format's ``CharHeight``. ``center_at`` measures the + text and moves it so its middle is at that model point. (A line + selected first didn't lay the text along it on SolidWorks 2026, nor did + centre alignment centre it, so neither is used.) + + Args: + adapter: A ``PyWin32Adapter`` with an open sketch. + text: The text; ``$PRP:"name"`` shows a custom property. + x: Start x in mm (sketch coordinates). + y: Start y in mm (the baseline). + height: Letter height in mm. + center_at: A model point ``[x, y, z]`` in mm to put the text's middle + at (projected onto the sketch). + + Returns: + AdapterResult with ``id``, ``text`` (as SolidWorks shows it, links + resolved) and ``height`` (mm, read back). + """ + if not adapter.currentSketchManager: + return AdapterResult(status=AdapterResultStatus.ERROR, error="No active sketch") + + def _text_operation() -> dict[str, Any]: + model = adapter.currentModel + model.ClearSelection2(True) + # Centred text starts at its target, so it never shows elsewhere + # (at the sketch's origin) before it is moved into place. + at_x, at_y = x / 1000.0, y / 1000.0 + if center_at is not None: + at_x, at_y, _z = _to_sketch_space(adapter, [c / 1000.0 for c in center_at]) + inserted = model.InsertSketchText( + at_x, at_y, 0.0, text, 0, 0, 0, _TEXT_NORMAL, _TEXT_NORMAL + ) + model.ClearSelection2(True) + if not inserted: + raise Exception("SolidWorks added no sketch text") + sketch_text = _sw_type_info.flagged(inserted, "ISketchText") + text_format = sketch_text.GetTextFormat() + text_format.CharHeight = height / 1000.0 + sketch_text.SetTextFormat(False, text_format) + if center_at is not None: + _centre_text(adapter, sketch_text, center_at) + shown = adapter._attempt(lambda: str(sketch_text.Text), default=text) + read_height = adapter._attempt( + lambda: float(sketch_text.GetTextFormat().CharHeight) * 1000.0, + default=height, + ) + return { + "id": adapter._register_sketch_entity("Text", inserted), + "text": shown, + "height": round(read_height, 4), + } + + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation("add_sketch_text", _text_operation), + ) + + +def _set_sketch_text_impl( + adapter: Any, sketch_name: str, text: str +) -> AdapterResult[dict[str, Any]]: + """Rewrite every sketch text in ``sketch_name``, with the sketch open. + + SolidWorks doesn't redraw sketch text when the model rebuilds, not even + a ``$PRP:`` link whose dimension changed, and writing + ``ISketchText.Text`` outside the sketch changes the string but not the + geometry (SolidWorks 2026, 2026-11-18). Written while the sketch is + open (``EditSketch``), a link is read again; the sketch is then closed + and the model rebuilt. + + Args: + adapter: A ``PyWin32Adapter`` with a part open. + sketch_name: The sketch, e.g. ``Sketch12``. + text: The new text; ``$PRP:"name"`` shows a custom property. + + Returns: + AdapterResult with ``sketch``, ``before`` and ``after``: each text's + string before and after (a ``$PRP:`` link is read when the string + is asked for, so ``before`` can already show a new value the + lettering doesn't). + """ + + def _operation() -> dict[str, Any]: + model = adapter.currentModel + if not model: + raise Exception("No active model") + feature = model.FeatureByName(sketch_name) + if not feature: + raise Exception( + f"Sketch '{sketch_name}' not found; read the names with list_features." + ) + feature = _sw_type_info.flagged(feature, "IFeature") + sketch = _sw_type_info.flagged(feature.GetSpecificFeature2(), "ISketch") + texts = [ + _sw_type_info.flagged(t, "ISketchText") + for t in as_list(adapter._attempt(lambda: sketch.GetSketchTextSegments())) + ] + if not texts: + raise Exception(f"Sketch '{sketch_name}' has no text to rewrite.") + before = [str(t.Text) for t in texts] + model.ClearSelection2(True) + feature.Select2(False, 0) + model.EditSketch() + try: + open_sketch = _sw_type_info.flagged(model.GetActiveSketch2(), "ISketch") + texts = [ + _sw_type_info.flagged(t, "ISketchText") + for t in as_list(open_sketch.GetSketchTextSegments()) + ] + for sketch_text in texts: + sketch_text.Text = text + after = [str(t.Text) for t in texts] + finally: + _sw_type_info.flagged(model.SketchManager, "ISketchManager").InsertSketch( + True + ) + model.ForceRebuild3(False) + return {"sketch": sketch_name, "before": before, "after": after} + + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation("set_sketch_text", _operation), + ) + + def _add_sketch_constraint_impl( adapter: Any, entity1: str, @@ -1310,6 +1541,11 @@ def _radial_dimension_placement() -> tuple[float, float, float, int]: f"Unknown sketch entity '{entity1}'. Use IDs returned by add_line/add_arc/add_circle/add_spline/add_centerline." ) + if isinstance(entity1_obj, (tuple, list)) and ( + (dimension_type or "").strip().lower() in {"radial", "diameter"} + ): + entity1_obj = _polygon_circle(entity1_obj, entity1) + entity2_obj = None if entity2: entity2_obj = adapter._sketch_entities.get(entity2) @@ -1319,6 +1555,12 @@ def _radial_dimension_placement() -> tuple[float, float, float, int]: ) dim_type = (dimension_type or "linear").strip().lower() + if dim_type in ELLIPSE_AXES: + display_ellipse = _ellipse_axis_dimension( + adapter, entity1_obj, entity1, dim_type + ) + _set_dimension_value(adapter, display_ellipse, value / 2 / 1000.0) + return adapter._register_sketch_entity("Dimension", display_ellipse) # type: ignore[no-any-return] placement = None if dim_type == "angular" and entity2_obj is not None: placement = adapter._angular_dimension_placement(entity1_obj, entity2_obj) @@ -1434,33 +1676,127 @@ def _try_create_angular_dimension() -> Any: value_si = value * _math_dim.pi / 180.0 else: value_si = value / 1000.0 + _set_dimension_value(adapter, display_dim, value_si) + return adapter._register_sketch_entity("Dimension", display_dim) # type: ignore[no-any-return] + + return cast( + AdapterResult[str], + adapter._handle_com_operation("add_sketch_dimension", _dimension_operation), + ) + - dim_obj = ( - adapter._attempt(lambda: display_dim.GetDimension2(0), default=None) - or adapter._attempt(lambda: display_dim.GetDimension(), default=None) - or display_dim +def _set_dimension_value(adapter: Any, display_dim: Any, value_si: float) -> None: + """Set a new dimension's value (metres or radians) in this configuration. + + ``SetSystemValue3``, then ``SetSystemValue2``, then the ``SystemValue`` + property, whichever this SolidWorks accepts. + """ + dim_obj = ( + adapter._attempt(lambda: display_dim.GetDimension2(0), default=None) + or adapter._attempt(lambda: display_dim.GetDimension(), default=None) + or display_dim + ) + if ( + adapter._attempt( + lambda: dim_obj.SetSystemValue3(value_si, 1, None), default=None ) + is None + ): if ( - adapter._attempt( - lambda: dim_obj.SetSystemValue3(value_si, 1, None), default=None - ) + adapter._attempt(lambda: dim_obj.SetSystemValue2(value_si, 1), default=None) is None ): - if ( - adapter._attempt( - lambda: dim_obj.SetSystemValue2(value_si, 1), default=None - ) - is None - ): - if hasattr(dim_obj, "SystemValue"): - dim_obj.SystemValue = value_si + if hasattr(dim_obj, "SystemValue"): + dim_obj.SystemValue = value_si - return adapter._register_sketch_entity("Dimension", display_dim) # type: ignore[no-any-return] - return cast( - AdapterResult[str], - adapter._handle_com_operation("add_sketch_dimension", _dimension_operation), +#: ``swSketchSegments_e.swSketchARC``: a circle or arc segment. +_SKETCH_ARC = 1 + +#: How far beside an ellipse's axis its dimension text goes, in metres. +_AXIS_TEXT_OFFSET = 0.005 + +#: An ellipse's axis dimensions, and the ``ISketchEllipse`` getter for the +#: point at that axis's end. +ELLIPSE_AXES = {"major_axis": "GetMajorPoint2", "minor_axis": "GetMinorPoint2"} + + +def _ellipse_axis_dimension( + adapter: Any, ellipse: Any, entity_id: str, axis: str +) -> Any: + """An aligned dimension from an ellipse's centre to the end of ``axis``. + + It holds half the axis: an ellipse has a point at one end of each axis + only. ``AddDimension2`` with the text beside the axis's middle makes it + aligned, so a turned ellipse gets its true half-axis (SolidWorks 2026, + 2026-11-18: 6.5 mm on an ellipse turned 30°, where a horizontal one + would read 5.63; ``AddSpecificDimension`` added nothing). A dimension + that doesn't read the axis's length (horizontal or vertical after all) + is refused rather than set, which would bend the ellipse. + + Args: + adapter: The adapter, with the ellipse's sketch open. + ellipse: The ellipse, as ``CreateEllipse`` returned it. + entity_id: Its registered id, for messages. + axis: ``major_axis`` or ``minor_axis``. + + Returns: + The display dimension. + + Raises: + Exception: If the entity isn't an ellipse, a point can't be selected, + or SolidWorks adds no dimension or one that isn't aligned. + """ + flagged = _sw_type_info.flagged(ellipse, "ISketchEllipse") + centre = adapter._attempt(lambda: flagged.GetCenterPoint2(), default=None) + end = adapter._attempt(lambda: getattr(flagged, ELLIPSE_AXES[axis])(), default=None) + if centre is None or end is None: + raise Exception( + f"'{entity_id}' is not an ellipse; {axis} dimensions an ellipse from add_ellipse." + ) + model = adapter.currentModel + model.ClearSelection2(True) + for point, append in ((centre, False), (end, True)): + if not adapter._attempt(lambda p=point, a=append: bool(p.Select2(a, 0)), False): + raise Exception(f"Failed to select the {axis} points of '{entity_id}'") + dx, dy = end.X - centre.X, end.Y - centre.Y + length = math.hypot(dx, dy) + side = (-dy / length, dx / length) if length else (0.0, 1.0) + display = adapter._attempt( + lambda: model.AddDimension2( + centre.X + dx / 2 + side[0] * _AXIS_TEXT_OFFSET, + centre.Y + dy / 2 + side[1] * _AXIS_TEXT_OFFSET, + 0.0, + ), + default=None, + ) + if not display: + raise Exception(f"SolidWorks added no {axis} dimension to '{entity_id}'") + measured = adapter._attempt( + lambda: display.GetDimension2(0).SystemValue, default=None ) + if measured is None or abs(float(measured) - length) > 1e-6: + raise Exception( + f"The {axis} dimension of '{entity_id}' reads {measured}, not the " + f"axis's {length:.6f} m: it isn't aligned with the axis." + ) + return display + + +def _polygon_circle(segments: Any, entity_id: str) -> Any: + """A polygon's construction circle, which sizes it across its flats. + + ``CreatePolygon`` returns the polygon's sides and the circle drawn + inside them; a diameter dimension on that circle drives the polygon. + + Raises: + Exception: If no segment is a circle. + """ + for segment in segments: + flagged = _sw_type_info.flagged(segment, "ISketchSegment") + if flagged.GetType() == _SKETCH_ARC: + return segment + raise Exception(f"Polygon '{entity_id}' has no construction circle to dimension.") def _sketch_point_xyz( diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md index cf56aec6..4be2832f 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md @@ -129,6 +129,20 @@ To turn a feature off without deleting it, `suppress_feature`. After 3. `activate_configuration` to look at a variant; `get_dimension` reads the active one. +## One value driving several dimensions (equations) + +1. `set_equation` with a global variable: `name` `Width`, `expression` + `60mm` (give units; a bare number is in the document's units). +2. `list_model_dimensions` for the full name of each dimension to drive, + then `set_equation` with `name` `D1@Sketch1` and `expression` + `"Width" / 2` (names inside an expression go in double quotes). +3. Change `Width` with `set_equation` again: the model is solved and + rebuilt, and every dimension that uses it follows. `verify_model` then. + +Equations apply in every configuration unless `configurations` says +otherwise (unlike `set_dimension`, which changes the active one). On +`equation_refused`, check the quoted names with `list_equations`. + ## Starting every part the same way (a template) 1. `create_part`, then set it up: `set_units`, `set_material`, diff --git a/src/solidworks_mcp/tools/__init__.py b/src/solidworks_mcp/tools/__init__.py index da467c3d..5d24a62f 100644 --- a/src/solidworks_mcp/tools/__init__.py +++ b/src/solidworks_mcp/tools/__init__.py @@ -15,6 +15,7 @@ from .drawing_analysis import register_drawing_analysis_tools from .drawing_automation import register_drawing_automation_tools from .engineering_data import register_engineering_data_tools +from .equations import register_equation_tools from .export import register_export_tools from .file_management import register_file_management_tools from .macro_recording import register_macro_recording_tools @@ -40,6 +41,7 @@ async def register_tools(mcp: FastMCP, adapter: Any, config: Any) -> int: # Register tool categories await register_modeling_tools(mcp, adapter, config) + await register_equation_tools(mcp, adapter, config) await register_sketching_tools(mcp, adapter, config) await register_drawing_tools(mcp, adapter, config) await register_drawing_analysis_tools(mcp, adapter, config) diff --git a/src/solidworks_mcp/tools/equations.py b/src/solidworks_mcp/tools/equations.py new file mode 100644 index 00000000..8a078697 --- /dev/null +++ b/src/solidworks_mcp/tools/equations.py @@ -0,0 +1,219 @@ +"""Equations and global variables: what makes a part parametric. + +``list_equations``, ``set_equation`` and ``delete_equation`` read and change +the active part's or assembly's equations, so one value +(``"Width" = 60mm``) can drive several dimensions +(``"D1@Sketch1" = "Width" / 2``) and the model stays consistent when it +changes. +""" + +from __future__ import annotations + +from typing import Any, Literal + +from fastmcp import FastMCP +from pydantic import Field + +from ..adapters.base import SolidWorksAdapter +from .input_compat import CompatInput +from .modeling import _check_configurations +from .tool_boundary import ( + normalize_input, + require_capability, + require_success, + with_tool_boundary, +) + +#: Characters a name can't hold: SolidWorks writes it between quotes. +_NAME_FORBIDDEN = ('"', "=", "\n", "\r") + + +class SetEquationInput(CompatInput): + """Input schema for adding or changing an equation. + + Attributes: + name (str): A global variable, or a dimension such as ``D1@Sketch1``. + expression (str): The right-hand side. + configurations (str | list[str]): Where it applies. + """ + + name: str = Field( + description=( + "A global variable (e.g. 'Width'), or a dimension of the active " + "document as list_model_dimensions names it (e.g. 'D1@Sketch1'); " + "no quotes" + ) + ) + expression: str = Field( + description=( + "The right-hand side, e.g. '60mm' or '\"Width\" / 2'; names in " + "double quotes. A number with no unit is in the document's units" + ) + ) + configurations: Literal["all", "this"] | list[str] = Field( + default="all", + description="Where it applies: 'all' (the default, as in SolidWorks' " + "Equations dialog), 'this' (the active configuration), or a list of " + "configuration names from `list_configurations`", + ) + + def model_post_init(self, __context: Any) -> None: + """Check the name and expression before anything is written. + + Args: + __context (Any): The context value. + + Raises: + ValueError: A blank name or expression, a name with a quote, ``=`` + or line break, an expression with a line break, or an empty + list of configurations. + """ + if not self.name.strip(): + raise ValueError("name is required") + if any(c in self.name for c in _NAME_FORBIDDEN): + raise ValueError( + f"name {self.name!r} can't hold a double quote, '=' or a line " + "break; give it without quotes, e.g. Width or D1@Sketch1" + ) + if not self.expression.strip(): + raise ValueError("expression is required, e.g. 60mm") + if "\n" in self.expression or "\r" in self.expression: + raise ValueError("expression must be one line") + self.name = self.name.strip() + _check_configurations(self.configurations) + + +class EquationNameInput(CompatInput): + """Input schema naming one equation. + + Attributes: + name (str): The equation's name (its left-hand side). + """ + + name: str = Field( + description="The equation's name as list_equations gives it, e.g. 'Width'" + ) + + def model_post_init(self, __context: Any) -> None: + """Refuse a blank name. + + Args: + __context (Any): The context value. + + Raises: + ValueError: The name is blank. + """ + if not self.name.strip(): + raise ValueError("name is required") + self.name = self.name.strip() + + +async def register_equation_tools( + mcp: FastMCP, adapter: SolidWorksAdapter, config: Any +) -> int: + """Register the equation tools with FastMCP. + + Args: + mcp (FastMCP): The mcp value. + adapter (SolidWorksAdapter): Adapter instance used for the operation. + config (Any): Configuration values for the operation. + + Returns: + int: How many tools were registered. + """ + mcp = with_tool_boundary(mcp) + + @mcp.tool() + async def list_equations() -> dict[str, Any]: + """List the active part's or assembly's equations and global variables, with their values. + + Use it before `set_equation` or `delete_equation`, to see which values + drive which dimensions. Needs: an open part or assembly. Read-only. + Returns: `equations`, each with `index`, `name`, `expression`, `kind` + (`global_variable`, `dimension` or `other`) and `value` (solved, in the + document's units; null when SolidWorks has none), and `count`. + """ + require_capability( + adapter, "list_equations", "Active adapter can't read equations" + ) + result = await adapter.list_equations() + require_success(result, "Failed to list equations") + rows = result.data or [] + return { + "status": "success", + "equations": rows, + "count": len(rows), + "execution_time": result.execution_time, + } + + @mcp.tool() + async def set_equation(input_data: SetEquationInput) -> dict[str, Any]: + """Add or change an equation or global variable, so one value drives others (a parametric part). + + E.g. `Width` = `60mm`, then `D1@Sketch1` = `"Width" / 2`: changing `Width` + later resizes the sketch. A `name` with `@` is a dimension of the active + document (`list_model_dimensions`); any other is a global variable. An + existing equation for `name` is changed, else one is added; the model + is solved and rebuilt. Applies in all configurations unless + `configurations` says otherwise. An expression SolidWorks can't use + fails as `equation_refused`, changing nothing. Needs: an open part or + assembly. Changes: the equation and what it drives. Returns: + `equation` with `name`, `expression`, `kind`, `value` (document units), + `action` (`added` or `changed`) and `configurations`. + + Args: + input_data: `name` and `expression` are required; `configurations` + defaults to `all`. + + Returns: + dict[str, Any]: The equation as SolidWorks stored it. + """ + input_data = normalize_input(input_data, SetEquationInput) + require_capability( + adapter, "set_equation", "Active adapter can't change equations" + ) + result = await adapter.set_equation( + input_data.name, input_data.expression, input_data.configurations + ) + require_success(result, "Failed to set equation") + data = result.data or {} + return { + "status": "success", + "message": f"{str(data.get('action', 'set')).capitalize()} " + f"{input_data.name} = {input_data.expression.strip()}", + "equation": data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def delete_equation(input_data: EquationNameInput) -> dict[str, Any]: + """Delete an equation or global variable of the active part or assembly, by name. + + A dimension the equation drove keeps its last value; an equation that + used a deleted global variable stops solving, so check + `list_equations` afterwards. Needs: an open part or assembly with that + equation. Changes: removes the equation. Returns: `deleted` and the + `equations` left (names). + + Args: + input_data: `name`, as `list_equations` gives it. + + Returns: + dict[str, Any]: The deleted name and those left. + """ + input_data = normalize_input(input_data, EquationNameInput) + require_capability( + adapter, "delete_equation", "Active adapter can't delete equations" + ) + result = await adapter.delete_equation(input_data.name) + require_success(result, "Failed to delete equation") + data = result.data or {} + return { + "status": "success", + "message": f"Deleted equation {data.get('deleted', input_data.name)}", + "deleted": data.get("deleted"), + "equations": data.get("equations", []), + "execution_time": result.execution_time, + } + + return 3 diff --git a/src/solidworks_mcp/tools/error_classifier.py b/src/solidworks_mcp/tools/error_classifier.py index 78219fc2..bfac4f4d 100644 --- a/src/solidworks_mcp/tools/error_classifier.py +++ b/src/solidworks_mcp/tools/error_classifier.py @@ -206,6 +206,24 @@ def matches(self, message: str, hresult: int | None) -> bool: ), patterns=(r"No configuration named",), ), + ErrorRule( + error_type="equation_refused", + hint=( + "SolidWorks couldn't use that expression. Names in it go in double " + "quotes and must exist: read them with list_equations (global " + "variables) and list_model_dimensions (dimensions); give units, " + "e.g. 60mm." + ), + patterns=(r"SolidWorks refused the equation",), + ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "Use a name from list_equations, or for a dimension the full_name " + "list_model_dimensions gives (e.g. D1@Sketch1)." + ), + patterns=(r"No equation named", r"No dimension named '[^']*' in the active"), + ), ErrorRule( error_type=INVALID_INPUT, hint=( diff --git a/src/solidworks_mcp/tools/modeling.py b/src/solidworks_mcp/tools/modeling.py index 43f44487..cb172a3e 100644 --- a/src/solidworks_mcp/tools/modeling.py +++ b/src/solidworks_mcp/tools/modeling.py @@ -487,7 +487,7 @@ class CreateCutExtrudeInput(CompatInput): draft_angle (float): Draft angle in degrees. end_condition (str): End condition type. reverse_direction (bool): Reverse cut direction. - both_directions (bool): With ``"ThroughAll"``, cut both ways. + both_directions (bool): Cut both ways: mid-plane when Blind. sketch_name (str | None): Sketch to cut from. """ @@ -512,8 +512,10 @@ class CreateCutExtrudeInput(CompatInput): both_directions: bool = Field( default=False, description=( - "With end_condition 'ThroughAll', cut through the body both ways " - "(same as 'ThroughAllBoth')" + "Cut both ways from the sketch plane: with 'Blind', a mid-plane " + "cut 'depth' mm in total, centred on the plane (a slot either side " + "of it); with 'ThroughAll', through the body both ways (same as " + "'ThroughAllBoth')" ), ) sketch_name: str | None = Field( diff --git a/src/solidworks_mcp/tools/sketching.py b/src/solidworks_mcp/tools/sketching.py index 39437ba0..ee2eae17 100644 --- a/src/solidworks_mcp/tools/sketching.py +++ b/src/solidworks_mcp/tools/sketching.py @@ -281,6 +281,51 @@ class AddRelationInput(BaseModel): ) +class AddSketchTextInput(CompatInput): + """Input schema for adding text to the open sketch. + + Attributes: + text (str): The text; ``$PRP:"name"`` shows a custom property. + x (float): Start x in mm (sketch coordinates). + y (float): Start y (baseline) in mm. + height (float): Letter height in mm. + center_at (list[float] | None): A model point [x, y, z] in mm for the + text's middle. + """ + + text: str = Field( + min_length=1, + description='The text. $PRP:"name" shows a custom property, e.g. one ' + 'linked to a dimension ("D1@Sketch3"), so the text follows it', + ) + x: float = Field(default=0.0, description="Start x in mm, sketch coordinates") + y: float = Field(default=0.0, description="Start y (baseline) in mm") + height: float = Field(default=3.5, gt=0, description="Letter height in mm") + center_at: list[float] | None = Field( + default=None, + min_length=3, + max_length=3, + description="Model point [x, y, z] in mm to put the text's middle at " + "(projected onto the sketch), e.g. the middle of a handle's face", + ) + + +class SetSketchTextInput(CompatInput): + """Input schema for rewriting the text in a sketch. + + Attributes: + sketch_name (str): The sketch whose text to rewrite. + text (str): The new text. + """ + + sketch_name: str = Field(min_length=1, description="The sketch, e.g. Sketch12") + text: str = Field( + min_length=1, + description='The new text; give the same $PRP:"name" text to re-read a ' + "linked property after the model changed", + ) + + class CheckSketchDefinitionInput(CompatInput): """Input schema for checking sketch definition status. @@ -770,11 +815,13 @@ async def add_polygon(input_data: dict[str, Any]) -> dict[str, Any]: Use it for nuts, hex bosses and pockets. Needs: an open sketch (`create_sketch`). Changes: adds the polygon's sides. Returns: `polygon` with - `id`, `center`, `radius` and `sides`. + `id`, `center`, `radius`, `sides` and `angle`. A `diameter` dimension + (`add_sketch_dimension`) on its `id` sizes it by the circle drawn inside it. Args: input_data: A mapping: `center_x`, `center_y` (mm, default 0), `radius` - (mm, circumscribed, default 10) and `sides` (default 6). + (mm, circumscribed, default 10), `sides` (default 6) and `angle` + (degrees the first corner is turned from +x, default 0). Returns: dict[str, Any]: The polygon added. @@ -783,8 +830,9 @@ async def add_polygon(input_data: dict[str, Any]) -> dict[str, Any]: center_y = input_data.get("center_y", 0.0) radius = input_data.get("radius", 10.0) sides = input_data.get("sides", 6) + angle = float(input_data.get("angle", 0.0)) - result = await adapter.add_polygon(center_x, center_y, radius, sides) + result = await adapter.add_polygon(center_x, center_y, radius, sides, angle) require_success(result, context="Failed to add polygon") polygon_id = result.data @@ -796,6 +844,7 @@ async def add_polygon(input_data: dict[str, Any]) -> dict[str, Any]: "center": {"x": center_x, "y": center_y}, "radius": radius, "sides": sides, + "angle": angle, }, "execution_time": result.execution_time, } @@ -805,12 +854,13 @@ async def add_ellipse(input_data: dict[str, Any]) -> dict[str, Any]: """Draw an ellipse in the open sketch from its centre and axis lengths, in mm. Use it for oval holes and bosses. Needs: an open sketch (`create_sketch`). - Changes: adds an ellipse. Returns: `ellipse` with `id`, `center`, `major_axis` - and `minor_axis`. + Changes: adds an ellipse. Returns: `ellipse` with `id`, `center`, `major_axis`, + `minor_axis` and `angle`. Args: input_data: A mapping: `center_x`, `center_y` (mm, default 0), - `major_axis` (default 20) and `minor_axis` (default 10), in mm. + `major_axis` (default 20) and `minor_axis` (default 10), in mm, and + `angle`, the major axis's turn from +x in degrees (default 0). Returns: dict[str, Any]: The ellipse added. @@ -819,8 +869,11 @@ async def add_ellipse(input_data: dict[str, Any]) -> dict[str, Any]: center_y = input_data.get("center_y", 0.0) major_axis = input_data.get("major_axis", 20.0) minor_axis = input_data.get("minor_axis", 10.0) + angle = input_data.get("angle", 0.0) - result = await adapter.add_ellipse(center_x, center_y, major_axis, minor_axis) + result = await adapter.add_ellipse( + center_x, center_y, major_axis, minor_axis, angle + ) require_success(result, context="Failed to add ellipse") ellipse_id = result.data @@ -832,10 +885,81 @@ async def add_ellipse(input_data: dict[str, Any]) -> dict[str, Any]: "center": {"x": center_x, "y": center_y}, "major_axis": major_axis, "minor_axis": minor_axis, + "angle": angle, + }, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def add_sketch_text(input_data: AddSketchTextInput) -> dict[str, Any]: + """Write text in the open sketch, at a point or centred on one, to deboss or emboss it. + + Use it for lettering, then cut (`create_cut_extrude`) or extrude the sketch. + `center_at` (a model point in mm) puts the text's middle there; otherwise it + starts at `x`, `y`. `$PRP:"name"` in the text shows a custom property; + one holding a dimension's name (`"D1@Sketch3"`, set with `set_custom_property`) + makes the text follow that dimension. To read from a face's own side, such as + an underside, open the sketch on that face (`create_sketch` `face_point`). + Needs: an open sketch (`create_sketch`). Changes: adds text. Returns: the + text's `id`, the `text` as SolidWorks shows it (links resolved) and its + `height`. + + Args: + input_data: The text. `text` is required; `x`, `y` (mm), `height` (3.5 + mm) and `center_at` have defaults. + + Returns: + dict[str, Any]: The text added. + """ + input_data = normalize_input(input_data, AddSketchTextInput) + result = await adapter.add_sketch_text( + input_data.text, + input_data.x, + input_data.y, + input_data.height, + input_data.center_at, + ) + require_success(result, context="Failed to add sketch text") + added: dict[str, Any] = result.data or {} + return { + "status": "success", + "message": f"Added text {added['text']!r}, {added['height']} mm high", + "sketch_text": { + **added, + "center_at": input_data.center_at, }, "execution_time": result.execution_time, } + @mcp.tool() + async def set_sketch_text(input_data: SetSketchTextInput) -> dict[str, Any]: + """Rewrite the text in a sketch and rebuild, so debossed lettering shows it. + + Use it after a change the text should follow: SolidWorks doesn't redraw sketch + text on rebuild, not even a `$PRP:` link to a dimension an equation changed. + Give the same `$PRP:"name"` text to re-read the link, or new text. The sketch + is opened, its text rewritten, closed, and the model rebuilt, so a cut made + from it changes too. Needs: a part with that sketch, holding text from + `add_sketch_text`. Changes: the sketch's text. Returns: the `sketch`, each + text `before` and `after` (links resolved). + + Args: + input_data: `sketch_name` and `text`, both required. + + Returns: + dict[str, Any]: The text before and after. + """ + input_data = normalize_input(input_data, SetSketchTextInput) + result = await adapter.set_sketch_text(input_data.sketch_name, input_data.text) + require_success(result, context="Failed to rewrite the sketch text") + changed: dict[str, Any] = result.data or {} + return { + "status": "success", + "message": f"{input_data.sketch_name} now reads {changed.get('after')}", + "sketch_text": changed, + "execution_time": result.execution_time, + } + @mcp.tool() async def add_sketch_constraint(input_data: AddRelationInput) -> dict[str, Any]: """Add a geometric relation between sketch entities: horizontal, vertical, parallel, perpendicular, tangent, coincident, concentric, equal, symmetric, collinear or fix. @@ -878,12 +1002,13 @@ async def add_sketch_constraint(input_data: AddRelationInput) -> dict[str, Any]: @mcp.tool() async def add_sketch_dimension(input_data: AddDimensionInput) -> dict[str, Any]: - """Add a driving dimension to sketch entities: linear, angular, radial or diameter. + """Add a driving dimension to sketch entities: linear, angular, radial, diameter or an ellipse axis. Use it to fix a size so the sketch is fully defined and can be changed later with `set_dimension`. Entities are the `id`s the add_* tools returned; two - connected lines for angular, a circle or arc for radial or diameter. No dialog - opens. Needs: an open sketch (`create_sketch`). Changes: adds the dimension and + connected lines for angular, a circle or arc for radial or diameter, an + ellipse for `major_axis` or `minor_axis` (`value` is the whole axis; the + dimension runs from the centre, so it shows half). No dialog opens. Needs: an open sketch (`create_sketch`). Changes: adds the dimension and resizes the geometry to `value`. Returns: `dimension` with `id`, `type`, `value` and the entities. diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index b88f53f9..b132ff4f 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -247,6 +247,10 @@ def _deprecated(replacement: str | None) -> Support: "create_configuration": _STABLE, "activate_configuration": _STABLE, "delete_configuration": _STABLE, + # equations + "list_equations": _STABLE, + "set_equation": _STABLE, + "delete_equation": _STABLE, "list_features": _STABLE, "list_open_documents": _STABLE, "load_assembly": _deprecated("open_model"), @@ -310,6 +314,8 @@ def _deprecated(replacement: str | None) -> Support: "add_centerline": _STABLE, "add_circle": _STABLE, "add_ellipse": _STABLE, + "add_sketch_text": _STABLE, + "set_sketch_text": _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 d4467302..dbdaffb6 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -165,6 +165,9 @@ def _discards(title: str) -> ToolHints: "create_configuration": _adds("Add Configuration"), "activate_configuration": _sets("Activate Configuration"), "delete_configuration": _discards("Delete Configuration"), + "list_equations": _reads("List Equations"), + "set_equation": _sets("Set Equation"), + "delete_equation": _discards("Delete Equation"), "load_part": _sets("Load Part"), "load_assembly": _sets("Load Assembly"), "save_part": _overwrites("Save Part"), @@ -230,6 +233,8 @@ def _discards(title: str) -> ToolHints: "add_centerline": _adds("Add Sketch Centerline"), "add_polygon": _adds("Add Sketch Polygon"), "add_ellipse": _adds("Add Sketch Ellipse"), + "add_sketch_text": _adds("Add Sketch Text"), + "set_sketch_text": _sets("Set Sketch Text"), "add_sketch_constraint": _adds("Add Sketch Relation"), "add_sketch_dimension": _adds("Add Sketch Dimension"), "sketch_linear_pattern": _adds("Sketch Linear Pattern"), diff --git a/src/solidworks_mcp/tools/toolsets.py b/src/solidworks_mcp/tools/toolsets.py index ff871ff4..65c70e9a 100644 --- a/src/solidworks_mcp/tools/toolsets.py +++ b/src/solidworks_mcp/tools/toolsets.py @@ -18,6 +18,7 @@ "core": frozenset( { "modeling", + "equations", "sketching", "file_management", "analysis", diff --git a/tests/integration/test_tool_descriptions.py b/tests/integration/test_tool_descriptions.py index 80b4f0bb..90cfe85a 100644 --- a/tests/integration/test_tool_descriptions.py +++ b/tests/integration/test_tool_descriptions.py @@ -25,6 +25,7 @@ "drawing_analysis", "drawing_automation", "engineering_data", + "equations", "export", "file_management", "macro_recording", diff --git a/tests/live/test_live_sw_equations.py b/tests/live/test_live_sw_equations.py new file mode 100644 index 00000000..7694e1fa --- /dev/null +++ b/tests/live/test_live_sw_equations.py @@ -0,0 +1,158 @@ +"""Equations and global variables (queue item 29), checked on real SolidWorks. + +1. ``set_equation`` adds the global variable ``Depth`` = 30mm and makes the + block's extrusion depth ``"Depth"``; the depth reads 30 mm, and 45 mm + (volume 72,000 mm³) after ``Depth`` = 45mm. ``list_equations`` shows both + with their values (confirming the units ``Value`` reports). An expression + naming a variable that doesn't exist is refused as ``equation_refused`` + and the list is unchanged. Deleting the depth equation keeps 45 mm; +2. ``Depth`` = 50mm in ``Long`` only: ``Long`` is 50 mm deep, ``Default`` + stays 30 mm. + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_equations.py::test_a_global_variable_drives_the_depth + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from tests.live.evidence import evidence +from tests.live.test_live_sw_beta_tools import _sketch + +pytestmark = pytest.mark.asyncio + +DEPTH = "D1@Boss-Extrude1" + + +async def _tools(adapter: Any) -> dict[str, Any]: + """The modeling, equation and file-management tools on ``adapter``.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.analysis import register_analysis_tools + from solidworks_mcp.tools.engineering_data import register_engineering_data_tools + from solidworks_mcp.tools.equations import register_equation_tools + from solidworks_mcp.tools.file_management import register_file_management_tools + from solidworks_mcp.tools.modeling import register_modeling_tools + from solidworks_mcp.tools.sketching import register_sketching_tools + + mcp = FastMCP("equations-live") + for register in ( + register_modeling_tools, + register_sketching_tools, + register_file_management_tools, + register_analysis_tools, + register_engineering_data_tools, + register_equation_tools, + ): + await register(mcp, adapter, {}) + return {t.name: t.fn for t in await mcp.list_tools()} + + +async def _block(tools: dict[str, Any], name: str) -> None: + """A 40 x 40 mm block, 20 mm deep, on the Top plane.""" + assert (await tools["create_part"]({"name": name}))["status"] == "success" + await _sketch(tools, "Top", {"x1": -20, "y1": -20, "x2": 20, "y2": 20}) + assert (await tools["create_extrusion"]({"depth": 20}))["status"] == "success" + + +async def _depth(tools: dict[str, Any]) -> Any: + """The extrusion depth in mm, as get_dimension reads it.""" + read = await tools["get_dimension"]({"name": DEPTH}) + return read.get("dimension", {}).get("value") + + +async def test_a_global_variable_drives_the_depth(scratch: Any) -> None: + """Depth drives the extrusion; a bad expression is refused; delete keeps it.""" + tools = await _tools(scratch.adapter) + await _block(tools, "equations") + + variable = await tools["set_equation"]({"name": "Depth", "expression": "30mm"}) + driven = await tools["set_equation"]({"name": DEPTH, "expression": '"Depth"'}) + at_30 = await _depth(tools) + changed = await tools["set_equation"]({"name": "Depth", "expression": "45mm"}) + at_45 = await _depth(tools) + mass = await tools["get_mass_properties"]() + volume = round(float(mass["mass_properties"]["volume"]["value"]), 1) + listed = await tools["list_equations"]() + refused = await tools["set_equation"]( + {"name": "Width", "expression": '"NoSuchVariable" * 2'} + ) + after_refusal = await tools["list_equations"]() + deleted = await tools["delete_equation"]({"name": DEPTH}) + kept = await _depth(tools) + + evidence( + "Depth drives the extrusion depth", + { + "added": [variable.get("message"), driven.get("message")], + "depth_at_30_then_45": [at_30, at_45], + "changed": changed.get("equation"), + "volume_mm3": volume, + "listed": listed.get("equations"), + }, + ) + evidence( + "A bad expression is refused; deleting keeps the last depth", + { + "refused": [ + refused["status"], + refused.get("error_type"), + refused["message"], + ], + "unchanged": after_refusal.get("equations") == listed.get("equations"), + "deleted": [deleted.get("deleted"), deleted.get("equations")], + "depth_after_delete": kept, + }, + ) + assert variable["status"] == "success", variable + assert driven["status"] == "success", driven + assert at_30 == pytest.approx(30.0, abs=1e-6) + assert changed["equation"]["action"] == "changed" + assert at_45 == pytest.approx(45.0, abs=1e-6) + assert volume == pytest.approx(72000.0, rel=1e-3) + kinds = {row["name"]: row["kind"] for row in listed["equations"]} + assert kinds == {"Depth": "global_variable", DEPTH: "dimension"} + assert refused["error_type"] == "equation_refused", refused + assert after_refusal["equations"] == listed["equations"] + assert deleted["equations"] == ["Depth"] + assert kept == pytest.approx(45.0, abs=1e-6) + + +async def test_an_equation_in_one_configuration(scratch: Any) -> None: + """Depth = 50mm in Long only; Default keeps 30 mm.""" + tools = await _tools(scratch.adapter) + await _block(tools, "equation_configs") + made = await tools["create_configuration"]({"name": "Long"}) + assert made["status"] == "success", made + assert (await tools["set_equation"]({"name": "Depth", "expression": "30mm"}))[ + "status" + ] == "success" + assert (await tools["set_equation"]({"name": DEPTH, "expression": '"Depth"'}))[ + "status" + ] == "success" + + long_only = await tools["set_equation"]( + {"name": "Depth", "expression": "50mm", "configurations": ["Long"]} + ) + default_depth = await _depth(tools) + await tools["activate_configuration"]({"name": "Long"}) + long_depth = await _depth(tools) + await tools["activate_configuration"]({"name": "Default"}) + + evidence( + "Depth = 50mm in Long only", + { + "set": long_only.get("equation", long_only.get("message")), + "depth_default_long": [default_depth, long_depth], + }, + ) + assert long_only["status"] == "success", long_only + assert default_depth == pytest.approx(30.0, abs=1e-6) + assert long_depth == pytest.approx(50.0, abs=1e-6) diff --git a/tests/live/test_live_sw_equations_wrench.py b/tests/live/test_live_sw_equations_wrench.py new file mode 100644 index 00000000..c446cca6 --- /dev/null +++ b/tests/live/test_live_sw_equations_wrench.py @@ -0,0 +1,1081 @@ +"""A combination wrench sized by one global variable (the equations demo). + +Modelled from pictures of the user's reference wrench (a 16 mm combination +wrench; standard views exported read-only, its feature tree not read): an +open end whose jaw is a parallel-sided slot at 15°, its bottom a shallow +curve just past the head's centre (a nut Size across flats bears on both +walls, its corners clear in the curve), a 12-point box end tilted 15° and +raised, a flat handle with rounded edges, thinner than the heads, filleted +into both heads, and chrome-vanadium steel (51CrV4), the usual wrench +steel. It is built at Size = 13 mm with fixed numbers, then +``set_equation`` ties every size to ``Size``, so one edit makes a 19 mm +wrench and a configuration holds an 8 mm one. + +Each size is a dimension that grows from the centre, so the wrench keeps its +shape at any size: + +- the handle is a round bar along x (its diameter is the handle's width, its + length the distance between the heads), flattened by two cuts from planes + offset either side of the Top Plane (the offsets are its thickness); +- the box end is a disc with two hexagon cuts 30° apart (a 12-point opening, + each hexagon sized across flats), all on a plane tilted 15° about the z + axis and moved 0.13 x Size along the ring's axis, built near the origin + and moved to the far end by a linear pattern whose spacing is the + length; a clearance cut then removes the pattern's seed; +- the open end is a disc at the origin and a jaw Size wide, cut both ways + from a plane at 15° from the head's centre outward; an ellipse at the + centre, Size across the jaw and 0.2 x Size along it, curves the bottom + (measured on the reference: 0.1 x Size past the centre); +- fillets where the handle meets each head, 0.2 x Size at its sides and + 0.16 x Size along its flat faces, where they meet the head and the side + fillets (the user's pick, 2 mm on the 13 mm wrench). + +The reference's handle bends up into the box end. Here the ring is lifted +just enough to cover the handle's end on both faces, so the handle meets +only its round wall and the neck fillets curve it in; a true bend would +need a swept or lofted handle. + +Run it with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_equations_wrench.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 solidworks_mcp.adapters import sw_type_info +from tests.live.evidence import evidence, starting +from tests.live.test_live_sw_beta_tools import _sketch +from tests.live.test_live_sw_equations import _tools +from tests.live.test_live_sw_ujoint_tool_gaps import _plane + +pytestmark = pytest.mark.asyncio + +SIZE_MM = 13.0 + +#: Each global variable as a multiple of Size, measured from the reference +#: (16 mm: heads 205 mm apart, open end Ø31.6, box end Ø24.4, heads 8.2 mm +#: thick, handle 14.6 x 4.7 mm). +RATIOS = { + "Length": 12.8, + "OpenHead": 2.0, + "BoxHead": 1.55, + "HeadT": 0.5, + "HandleW": 0.9, + "HandleT": 0.3, +} +#: The clearance cut that removes the box end's pattern seed: a little wider +#: than the raised, tilted ring reaches (0.89 x Size from the origin). +CLEARANCE = 1.2 +JAW_ANGLE_DEG = 15.0 +BOX_TILT_DEG = 15.0 +#: How far the ring is moved along its own axis, as a multiple of Size. The +#: handle runs to the ring's centre, so the ring must cover it up to the +#: 12-point hole: lifted less than 0.12 x Size the handle shows above the +#: ring's top face, more than 0.14 x Size it shows below its underside as a +#: ledge (checked numerically 2026-11-18). In between, the handle meets only +#: the ring's round wall, and the neck fillets curve it in. +RING_RISE = 0.13 +#: The jaw's curved bottom: an ellipse's axes as multiples of Size. +RELIEF = {"across": 1.0, "along": 0.2} +#: Neck fillet radii as multiples of Size: at the handle's sides and faces. +FILLET = {"sides": 0.2, "faces": 0.16} +#: Chrome-vanadium spring steel, the usual wrench steel (SAE 6150 / 51CrV4). +MATERIAL = "1.8159 (51CrV4)" +MATERIAL_LIBRARY = "SolidWorks DIN Materials" +#: Lettering debossed into both faces of the handle. ``$PRP:"WrenchSize"`` +#: shows a custom property linked to a dimension the equations set to Size, +#: so the handle reads its own size after each change. +LETTERING = 'solidworksmcp-python $PRP:"WrenchSize" mm' +LETTER_HEIGHT_MM = 3.5 +DEBOSS_MM = 0.3 +#: ``swUserPreferenceIntegerValue_e.swUnitsLinearDecimalPlaces``: the part +#: shows whole millimetres, so the lettering's linked size reads "13 mm", +#: not "13.00 mm" (display only; every value stays exact). +_LINEAR_DECIMAL_PLACES = 49 +#: ``swUserPreferenceToggle_e.swAutoNormalToSketchMode``: SolidWorks turns the +#: view square-on to every sketch it opens. Off for the demo (and set back +#: after), so the camera stays put while the lettering is cut and re-lettered. +_AUTO_NORMAL_TO_SKETCH = 477 + +#: The handle's visible middle as a multiple of Size: between the open +#: end's rim (x = Size) and the ring's near edge (x = 11.95 x Size). +HANDLE_MIDDLE = 6.48 +#: The spare block the lettering is first cut into, off the open end +#: (x from -260 to -120 mm, centred at -190), clear of the wrench at any +#: size; a linear pattern moves the lettering onto the handle's middle. +SPARE_X_MM = (-260.0, -120.0) +SPARE_CENTRE_MM = -190.0 +_ISO_VIEW = 7 # swStandardViews_e.swIsometricView +#: ``swUserPreferenceToggle_e``: swDisplayAxes, swDisplayPlanes, +#: swDisplayOrigins, swDisplayTemporaryAxes, swDisplaySketches. Sketches +#: too: the lettering's, off the open end, would make zoom-to-fit frame +#: them and leave the wrench tiny. +_HIDDEN_REFERENCES = (4, 5, 6, 7, 196) + + +def _hide_references(adapter: Any) -> None: + """Hide the reference planes, axes, origin and sketches: the wrench alone. + + Sketches are hidden one by one too (``BlankSketch``): the display toggle + alone left the spare block's sketch showing off the open end, and + zoom-to-fit framed it with the wrench, which then looked tiny. + """ + model = adapter.currentModel + for toggle in _HIDDEN_REFERENCES: + adapter._attempt( + lambda t=toggle: model.Extension.SetUserPreferenceToggle(t, 0, False), + default=None, + ) + feature = adapter._attempt(lambda: model.FirstFeature(), default=None) + while feature: + flagged = sw_type_info.flagged(feature, "IFeature") + if adapter._attempt(lambda f=flagged: f.GetTypeName2(), "") == "ProfileFeature": + model.ClearSelection2(True) + if adapter._attempt(lambda f=flagged: f.Select2(False, 0), False): + adapter._attempt(lambda: model.BlankSketch(), None) + feature = adapter._attempt(lambda f=flagged: f.GetNextFeature(), None) + model.ClearSelection2(True) + + +def _frame(adapter: Any, room_for: float = 1.0) -> None: + """Point the camera: isometric, zoomed to fit, then out to leave room. + + Staging for the recording, not a tool call. ``room_for`` is how many + times larger the part will grow: the camera is set once and left alone + after that, so a wrench that grows or shrinks visibly does (zooming to + fit each time made every size look the same). + """ + model = adapter.currentModel + _hide_references(adapter) + adapter._attempt(lambda: model.ShowNamedView2("", _ISO_VIEW), default=None) + adapter._zoom_to_fit(model) + view = sw_type_info.flagged(model.ActiveView, "IModelView") + adapter._attempt(lambda: view.ZoomByFactor(0.92 / room_for), default=None) + + +def _mm(variable: str, size: float = SIZE_MM) -> float: + """A variable's value in mm for a given Size.""" + return round(RATIOS[variable] * size, 4) + + +#: The box end as built at Size = 13 mm: its centre's offset from where the +#: pattern puts it (x = Length on the handle's line), and its axis. +Ring = tuple[tuple[float, ...], tuple[float, ...]] + + +def _ring_centre(size: float, ring: Ring) -> tuple[float, float, float]: + """The box end's centre in mm for a given Size (everything scales).""" + offset, _axis = ring + k = size / SIZE_MM + return (_mm("Length", size) + k * offset[0], k * offset[1], k * offset[2]) + + +def _disc_reach(radius: float, half: float, axis_part: float) -> float: + """How far a disc reaches along a model axis from its centre. + + ``axis_part`` is that model axis's component of the disc's own axis: + the rim reaches radius x sin, the faces half the thickness x cos. + """ + return radius * math.sqrt(1 - axis_part**2) + half * abs(axis_part) + + +def wrench_box(size: float, ring: Ring) -> list[float]: + """The wrench's overall size [x, y, z] in mm for a given Size. + + x: the jaw takes the open end's tip off; what stays furthest out is the + jaw corner nearer the axis, √(R² − (S/2)²) along the jaw and S/2 across + it, turned 15°. Then the ring's centre and its reach along x. + y: from the open end's underside (half its thickness below) to the + ring's top, its centre plus its reach along y. z: the open end's + diameter. + """ + r = _mm("OpenHead", size) / 2 + rb = _mm("BoxHead", size) / 2 + t = _mm("HeadT", size) / 2 + jaw = math.radians(JAW_ANGLE_DEG) + open_reach = math.sqrt(r**2 - (size / 2) ** 2) * math.cos(jaw) + open_reach += size / 2 * math.sin(jaw) + centre = _ring_centre(size, ring) + axis = ring[1] + x = open_reach + centre[0] + _disc_reach(rb, t, axis[0]) + top = centre[1] + _disc_reach(rb, t, axis[1]) + bottom = min(-t, centre[1] - _disc_reach(rb, t, axis[1])) + return [round(x, 2), round(top - bottom, 2), round(2 * r, 2)] + + +async def _one_body(tools: dict[str, Any]) -> bool: + """Whether the part is still one solid body.""" + checked = await tools["verify_model"]({"solid_body_count": 1}) + return bool(checked["verdict"] == "pass") + + +async def _length(tools: dict[str, Any]) -> float: + """The part's overall size along x, in mm (its body count isn't judged).""" + checked = await tools["verify_model"]({"solid_body_count": 1}) + box = checked["measured"]["bounding_box_mm"] + size = box.get("size") if isinstance(box, dict) else box + return float(size[0]) + + +async def _sized_sketch( + tools: dict[str, Any], plane: str, shape: str, args: dict[str, Any], value: float +) -> str: + """A sketch of one circle or polygon at the origin, sized by a diameter.""" + made = await tools["create_sketch"]({"plane": plane}) + assert made["status"] == "success", made + drawn = await tools[shape](args) + assert drawn["status"] == "success", drawn + key = "circle" if shape == "add_circle" else "polygon" + sized = await tools["add_sketch_dimension"]( + {"entity1": drawn[key]["id"], "dimension_type": "diameter", "value": value} + ) + assert sized["status"] == "success", sized + closed = await tools["exit_sketch"]() + assert closed["status"] == "success", closed + return str(closed.get("sketch", made["sketch"])["name"]) + + +async def _flatten(tools: dict[str, Any], adapter: Any, flip: bool) -> str: + """Cut the bar away beyond a plane HandleT/2 above (or below) the Top Plane. + + Which way a cut goes from a reference plane isn't certain, so the volume + decides: the right cut takes off one rounded cap and leaves more than half + the bar (58-70 %); the wrong one leaves less (30-42 %), or SolidWorks + refuses it because nothing would be left. Then the cut is undone and made + the other way, from the same sketch. + + Returns: + The plane, at the handle's flat face (the lettering goes on it). + """ + half = _mm("HandleT") / 2 + plane = await tools["create_reference_plane"]( + {"reference": "Top Plane", "offset": half, "flip": flip} + ) + assert plane["status"] == "success", plane + name = str(plane["plane"]["name"]) + origin, _normal = _plane(adapter, name) + assert origin[1] == pytest.approx(-half if flip else half, abs=1e-3), ( + f"{name} is at y = {origin[1]:.3f} mm, not {'-' if flip else ''}{half} mm" + ) + sketch = await _sketch(tools, name, {"x1": -400, "y1": -400, "x2": 400, "y2": 400}) + for reverse in (False, True): + cut = await tools["create_cut_extrude"]( + { + "sketch_name": sketch, + "depth": 1, + "end_condition": "ThroughAll", + "reverse_direction": reverse, + } + ) + if cut["status"] != "success": + continue + change = cut.get("measured_change", {}) + if change.get("volume_after_mm3", 0) > 0.5 * change.get("volume_before_mm3", 0): + return name + await tools["undo"]({"count": 1}) + raise AssertionError(f"neither cut from {name} left the flattened handle") + + +async def _box_end(tools: dict[str, Any], adapter: Any) -> tuple[list[str], Ring]: + """The box end near the origin, tilted 15°: a disc and a 12-point opening. + + All three are sketched on a plane 0.13 x Size up along the ring's axis + from a plane through the z axis, 15° off the Top Plane: the ring tilts + and covers the handle's end on both faces. The 12 points are two hexagons 30° apart, each its own cut and + each sized across flats by a dimension. (SolidWorks wouldn't copy a + circular pattern of one hexagon with the linear pattern that moves the + box end, so the second hexagon is drawn turned instead.) + + Returns: + The features for the linear pattern to copy, and the ring: its + centre (the raised plane's origin) and axis, pointing up. + """ + s = SIZE_MM + z_axis = await tools["create_axis"]({"reference": "z"}) + tilted = await _angled_plane( + tools, adapter, "Top Plane", str(z_axis["axis"]["name"]), facing=1 + ) + tilted, centre, axis = await _raised(tools, adapter, tilted) + disc = await _sized_sketch( + tools, + tilted, + "add_circle", + {"center_x": 0, "center_y": 0, "radius": _mm("BoxHead") / 2}, + _mm("BoxHead"), + ) + boss = await tools["create_extrusion"]( + {"sketch_name": disc, "depth": _mm("HeadT"), "both_directions": True} + ) + assert boss["status"] == "success", boss + features = [boss["extrusion"]["name"]] + for angle in (0.0, 30.0): + hexagon = await _sized_sketch( + tools, + tilted, + "add_polygon", + {"center_x": 0, "center_y": 0, "radius": s / 2, "sides": 6, "angle": angle}, + s, + ) + hole = await tools["create_cut_extrude"]( + {"sketch_name": hexagon, "depth": 1, "end_condition": "ThroughAllBoth"} + ) + assert hole["status"] == "success", hole + features.append(hole["cut_extrude"]["name"]) + return features, (centre, axis) + + +async def _raised( + tools: dict[str, Any], adapter: Any, tilted: str +) -> tuple[str, tuple[float, ...], tuple[float, ...]]: + """A plane RING_RISE x Size from ``tilted``, on the upper side. + + Which side an offset plane lands on isn't certain, so its origin is + measured; one below the Top Plane is undone and made flipped. + + Returns: + The plane, its origin in mm (the ring's centre) and its normal, + turned to point up. + """ + rise = round(SIZE_MM * RING_RISE, 4) + tried = [] + for flip in (False, True): + plane = await tools["create_reference_plane"]( + {"reference": tilted, "offset": rise, "flip": flip} + ) + assert plane["status"] == "success", plane + name = str(plane["plane"]["name"]) + origin, normal = _plane(adapter, name) + tried.append([round(c, 3) for c in origin]) + if origin[1] > 0: + assert math.dist(origin, (0, 0, 0)) == pytest.approx(rise, abs=1e-3), origin + up = tuple(c if normal[1] > 0 else -c for c in normal) + return name, tuple(origin), up + await tools["undo"]({"count": 1}) + raise AssertionError(f"no plane {rise} mm above {tilted}: origins {tried}") + + +async def _through_circle(tools: dict[str, Any], diameter: float) -> None: + """A round hole ``diameter`` across at the origin, through everything.""" + sketch = await _sized_sketch( + tools, + "Top", + "add_circle", + {"center_x": 0, "center_y": 0, "radius": diameter / 2}, + diameter, + ) + cut = await tools["create_cut_extrude"]( + {"sketch_name": sketch, "depth": 1, "end_condition": "ThroughAllBoth"} + ) + assert cut["status"] == "success", cut + + +async def _angled_plane( + tools: dict[str, Any], + adapter: Any, + reference: str, + axis: str, + facing: int, + flip: bool = False, +) -> str: + """A plane through ``axis`` whose normal is 15° off model axis ``facing``. + + ``flip`` turns it the other way about ``axis``. + + ``create_reference_plane`` at 15° from the Front Plane about y once gave + a plane whose normal ran along x (SolidWorks 2026, 2026-11-18), so the + normal is measured: 15° and then 75° are tried, and a plane that faces + the wrong way is undone. + """ + made = [] + want = math.cos(math.radians(15.0)) + for angle in (15.0, 75.0): + plane = await tools["create_reference_plane"]( + {"reference": reference, "angle": angle, "axis": axis, "flip": flip} + ) + assert plane["status"] == "success", plane + name = str(plane["plane"]["name"]) + _origin, normal = _plane(adapter, name) + made.append({"angle": angle, "normal": [round(c, 3) for c in normal]}) + if abs(normal[facing]) == pytest.approx(want, abs=0.01): + return name + await tools["undo"]({"count": 1}) + raise AssertionError(f"no plane through {axis} came out at 15°: {made}") + + +async def _jaw( + tools: dict[str, Any], adapter: Any, axis: str, ring: Ring +) -> tuple[float, ...]: + """The jaw: Size wide, cut both ways from the jaw's centre plane. + + On this plane SolidWorks 2026 puts sketch x along the model's y (up) and + sketch y along the wrench (measured 2026-11-18: a rectangle spanning + sketch x 0..120 cut a half-depth groove), so the rectangle spans sketch x + across the whole thickness and sketch y along one side. Which side is + away from the handle isn't known, and a jaw on the handle's side still + leaves one body, so the overall size decides: a wrong jaw leaves the open + end's full radius, 0.2 mm too long. Then the cut and its sketch are undone + and drawn on the other side. + + Returns: + The jaw plane's normal: the direction across the jaw. + """ + # Flipped so the jaw's walls rise towards the handle, as on the reference. + name = await _angled_plane(tools, adapter, "Front Plane", axis, facing=2, flip=True) + tried = [] + for y1, y2 in ((-120.0, 0.0), (0.0, 120.0)): + sketch = await _sketch(tools, name, {"x1": -60, "y1": y1, "x2": 60, "y2": y2}) + cut = await tools["create_cut_extrude"]( + {"sketch_name": sketch, "depth": SIZE_MM, "both_directions": True} + ) + assert cut["status"] == "success", cut + size = await _size(tools, SIZE_MM, ring) + tried.append( + {"sketch_y": [y1, y2], "cut": cut.get("measured_change"), "size": size} + ) + if size["verdict"] == "pass": + _origin, normal = _plane(adapter, name) + return tuple(normal) + undone = await tools["undo"]({"count": 2}) + tried[-1]["undone"] = undone.get("data") + raise AssertionError(f"neither side of the plane gave the jaw its size: {tried}") + + +async def _relief(tools: dict[str, Any], across: tuple[float, ...]) -> str: + """Curve the jaw's bottom: an ellipse at the head's centre, cut through. + + Its major axis lies across the jaw (``across``, the jaw plane's normal), + Size long, so it meets both walls where the flat bottom ended; its minor + axis, 0.2 x Size, takes the bottom 0.1 x Size past the centre. The half + towards the opening is inside the jaw already. On the Top Plane sketch x + is model x and sketch y is model -z. + + Returns: + The ellipse's sketch. + """ + angle = math.degrees(math.atan2(-across[2], across[0])) + made = await tools["create_sketch"]({"plane": "Top"}) + assert made["status"] == "success", made + ellipse = await tools["add_ellipse"]( + { + "major_axis": SIZE_MM * RELIEF["across"], + "minor_axis": SIZE_MM * RELIEF["along"], + "angle": angle, + } + ) + assert ellipse["status"] == "success", ellipse + for axis, ratio in (("major_axis", "across"), ("minor_axis", "along")): + sized = await tools["add_sketch_dimension"]( + { + "entity1": ellipse["ellipse"]["id"], + "dimension_type": axis, + "value": SIZE_MM * RELIEF[ratio], + } + ) + assert sized["status"] == "success", sized + closed = await tools["exit_sketch"]() + assert closed["status"] == "success", closed + sketch = str(closed.get("sketch", made["sketch"])["name"]) + cut = await tools["create_cut_extrude"]( + {"sketch_name": sketch, "depth": 1, "end_condition": "ThroughAllBoth"} + ) + assert cut["status"] == "success", cut + return sketch + + +def _entry( + inside: Any, start: tuple[float, float, float], step: float, stop: float +) -> list[float] | None: + """Where a line along x from ``start`` first enters a head, in metres. + + Marched ``step`` mm at a time up to x = ``stop``: the neck edges for the + fillets are where the handle's faces and sides meet each head, found + this way rather than by solving each surface. None if the line never + enters before ``stop`` (no edge there to fillet). + """ + point = list(start) + while (point[0] - stop) * step < 0: + if inside(point): + return [round(c / 1000, 6) for c in point] + point[0] += step + return None + + +def _neck_edges(ring: Ring) -> dict[str, list[str]]: + """Points on the edges where the handle meets each head, 'x,y,z' in metres. + + ``sides``: the handle's rounded sides (y = 0, z = ±half its width); + ``faces``: its flat faces (z = 0, y = ±half its thickness). The open end + is a disc about y at the origin; the box end the raised, tilted disc + ``ring``. + """ + r_open = _mm("OpenHead") / 2 + r_box = _mm("BoxHead") / 2 + half = _mm("HeadT") / 2 + length = _mm("Length") + centre = _ring_centre(SIZE_MM, ring) + ring_axis = ring[1] + w = _mm("HandleW") / 2 + t = _mm("HandleT") / 2 + + def in_open(p: list[float]) -> bool: + return abs(p[1]) <= half and p[0] ** 2 + p[2] ** 2 <= r_open**2 + + def in_box(p: list[float]) -> bool: + d = (p[0] - centre[0], p[1] - centre[1], p[2] - centre[2]) + along = sum(a * b for a, b in zip(d, ring_axis, strict=False)) + radial = sum(c * c for c in d) - along**2 + return abs(along) <= half and radial <= r_box**2 + + # Faces first: a side fillet at the box end ran on round the neck and + # took the face edge with it (2026-11-18). + starts = {"faces": [(t, 0.0), (-t, 0.0)], "sides": [(0.0, w), (0.0, -w)]} + edges: dict[str, list[str]] = {} + for kind, offsets in starts.items(): + points = [] + for y, z in offsets: + mid = length / 2 + points.append(_entry(in_open, (mid, y, z), -0.01, 0.0)) + points.append(_entry(in_box, (mid, y, z), 0.01, length)) + edges[kind] = [",".join(str(c) for c in p) for p in points if p] + return edges + + +async def _necks(tools: dict[str, Any], ring: Ring) -> list[str]: + """Fillet the handle into both heads: its faces, then its sides. + + Returns: + The two fillets. + """ + names = [] + for kind, points in _neck_edges(ring).items(): + fillet = await tools["add_fillet"]( + {"radius": round(SIZE_MM * FILLET[kind], 4), "edge_names": points} + ) + assert fillet["status"] == "success", (kind, points, fillet) + names.append(str(fillet["fillet"]["name"])) + return names + + +def _spacing_to_middle(size: float = SIZE_MM) -> float: + """The lettering pattern's spacing: from the spare block to the handle's middle.""" + return round(HANDLE_MIDDLE * size - SPARE_CENTRE_MM, 4) + + +async def _lettering( + tools: dict[str, Any], adapter: Any, x_axis: str, size_dimension: str +) -> list[Any]: + """Deboss the lettering into the middle of both faces of the handle. + + A sketch text's position can't follow an equation, but a pattern's + spacing can. So the lettering is cut, centred, into the top and bottom + faces of a spare block off the open end, as thick as the handle (each + sketch opened on its face, so the underside's text reads from below); + a linear pattern moves both cuts to the handle's middle, x = + HANDLE_MIDDLE x Size, by a spacing an equation drives; then the block is + cut away, as the box end's pattern seed is. ``WrenchSize``, which the + text shows, is linked to ``size_dimension`` (one the equations set to + Size). + + Returns: + The two lettering sketches, and what each read when written. + """ + model = adapter.currentModel + adapter._attempt( + lambda: model.Extension.SetUserPreferenceInteger(_LINEAR_DECIMAL_PLACES, 0, 0), + None, + ) + linked = await tools["set_custom_property"]( + {"name": "WrenchSize", "value": f'"{size_dimension}"'} + ) + assert linked["status"] == "success", linked + x0, x1 = SPARE_X_MM + spare = await _sketch(tools, "Top", {"x1": x0, "y1": -15, "x2": x1, "y2": 15}) + block = await tools["create_extrusion"]( + {"sketch_name": spare, "depth": _mm("HandleT"), "both_directions": True} + ) + assert block["status"] == "success", block + sketches, reads, cuts = [], [], [] + for y in (_mm("HandleT") / 2, -_mm("HandleT") / 2): + face = [SPARE_CENTRE_MM, y, 0.0] + made = await tools["create_sketch"]({"face_point": face}) + assert made["status"] == "success", made + text = await tools["add_sketch_text"]( + {"text": LETTERING, "height": LETTER_HEIGHT_MM, "center_at": face} + ) + assert text["status"] == "success", text + sketches.append(str(made["sketch"]["name"])) + reads.append(str(text["sketch_text"]["text"])) + closed = await tools["exit_sketch"]() + assert closed["status"] == "success", closed + cut = await tools["create_cut_extrude"]( + {"sketch_name": made["sketch"]["name"], "depth": DEBOSS_MM} + ) + assert cut["status"] == "success", cut + cuts.append(cut["cut_extrude"]["name"]) + tried = [] + # Reversed first: from the spare block the handle lies that way on the + # x axis (every run so far); the other way is the fallback. + for reverse in (True, False): + moved = await tools["pattern_linear"]( + { + "features": cuts, + "direction": x_axis, + "count": 2, + "spacing": _spacing_to_middle(), + "reverse": reverse, + } + ) + tried.append(moved) + # The right way cuts the lettering into the handle: volume drops. + if moved["status"] == "success" and moved["pattern"]["volume_change"] < 0: + break + if moved["status"] == "success": + await tools["undo"]({"count": 1}) + else: + raise AssertionError(f"the lettering didn't reach the handle: {tried}") + clear = await _sketch( + tools, "Top", {"x1": x0 - 20, "y1": -40, "x2": x1 + 20, "y2": 40} + ) + gone = await tools["create_cut_extrude"]( + {"sketch_name": clear, "depth": 1, "end_condition": "ThroughAllBoth"} + ) + assert gone["status"] == "success", gone + assert await _one_body(tools), "the spare block is still there" + return sketches, reads + + +async def _reletter( + tools: dict[str, Any], sketches: list[str], drawn: list[str] +) -> dict[str, Any]: + """Re-letter the handle: each lettering sketch's text written again. + + SolidWorks doesn't redraw sketch text when an equation changes the + model, so the lettering keeps the size it was written at until + ``set_sketch_text`` writes the same ``$PRP:`` text again, which reads + the linked Size dimension now (the user's choice: a visible re-letter + step after each size change). + + Returns: + The lettering ``before`` (``drawn``: what the cuts showed; the + text's own string already reads the new size, as links are read + when asked) and ``after``, both faces. + """ + after: list[str] = [] + for sketch in sketches: + rewritten = await tools["set_sketch_text"]( + {"sketch_name": sketch, "text": LETTERING} + ) + assert rewritten["status"] == "success", rewritten + after += rewritten["sketch_text"]["after"] + return {"before": drawn, "after": after} + + +async def build_wrench( + tools: dict[str, Any], adapter: Any +) -> tuple[str, Ring, str, str]: + """The 13 mm combination wrench, at fixed sizes, not yet lettered. + + Returns: + The sketch of the jaw's curved bottom (its two dimensions are + picked by that sketch, not by value), the box end's ring, the x + axis (the lettering's pattern direction) and a dimension that is + Size (the lettering's link). + """ + starting( + "Building a 13 mm wrench: the handle", call="create_part, create_extrusion" + ) + assert (await tools["create_part"]({"name": "wrench"}))["status"] == "success" + bar = await _sized_sketch( + tools, + "Right", + "add_circle", + {"center_x": 0, "center_y": 0, "radius": _mm("HandleW") / 2}, + _mm("HandleW"), + ) + handle = await tools["create_extrusion"]( + {"sketch_name": bar, "depth": _mm("Length")} + ) + assert handle["status"] == "success", handle + _frame(adapter, room_for=1.3) # room for the heads still to come + await _flatten(tools, adapter, flip=False) + await _flatten(tools, adapter, flip=True) + + starting( + "Building: the box end (ring and 12-point socket)", + call="create_extrusion, create_cut_extrude, pattern_linear", + ) + box_features, ring = await _box_end(tools, adapter) + x_axis = await tools["create_axis"]({"reference": "x"}) + tried = [] + for reverse in (False, True): + moved = await tools["pattern_linear"]( + { + "features": box_features, + "direction": x_axis["axis"]["name"], + "count": 2, + "spacing": _mm("Length"), + "reverse": reverse, + } + ) + tried.append(moved) + if moved["status"] != "success": + continue # the tool already removed a pattern that built nothing + # A lifted seed can float clear of the handle, so the part may be two + # bodies until the clearance cut; the overall length tells the way + # instead: about Length plus the ring's reach along the handle, + # nearly twice Length the wrong way. + if await _length(tools) < 1.5 * _mm("Length"): + break + await tools["undo"]({"count": 1}) + else: + raise AssertionError(f"the box end didn't reach the handle's end: {tried}") + + # The pattern's seed near the origin pokes out of the open end (it's + # tilted and raised), so it is cut away; the open end then fills the gap. + starting( + "Building: the open end and its curved jaw", + call="create_extrusion, add_ellipse, create_cut_extrude", + ) + await _through_circle(tools, round(_mm("BoxHead") * CLEARANCE, 4)) + assert await _one_body(tools), "the box end isn't joined to the handle" + head = await _sized_sketch( + tools, + "Top", + "add_circle", + {"center_x": 0, "center_y": 0, "radius": _mm("OpenHead") / 2}, + _mm("OpenHead"), + ) + boss = await tools["create_extrusion"]( + {"sketch_name": head, "depth": _mm("HeadT"), "both_directions": True} + ) + assert boss["status"] == "success", boss + y_axis = await tools["create_axis"]({"reference": "y"}) + across = await _jaw(tools, adapter, str(y_axis["axis"]["name"]), ring) + relief = await _relief(tools, across) + starting( + "Building: fillets where the heads meet the handle, then steel", + call="add_fillet x 2, set_material", + ) + await _necks(tools, ring) + steel = await tools["set_material"]( + {"material_name": MATERIAL, "database": MATERIAL_LIBRARY} + ) + assert steel["status"] == "success", steel + listed = await tools["list_model_dimensions"]({}) + size_dimension = next( + str(row["full_name"]) + for row in listed["data"] + if abs(float(row["value"]) - SIZE_MM) < 1e-3 + and not str(row["full_name"]).endswith(f"@{relief}") + ) + return relief, ring, str(x_axis["axis"]["name"]), size_dimension + + +def drivers(dimensions: list[dict[str, Any]], relief: str) -> dict[str, str]: + """Each dimension's full name -> the expression that will drive it. + + Picked by the value it was built with, so the test doesn't depend on + SolidWorks' feature numbering. The jaw's ellipse (sketch ``relief``) is + picked by its sketch: half its long axis is Size / 2, the same number as + HeadT. Each of its dimensions holds half an axis. + """ + by_value = { + _mm("Length"): '"Length"', + _mm("OpenHead"): '"OpenHead"', + _mm("BoxHead"): '"BoxHead"', + _mm("HeadT"): '"HeadT"', + _mm("HandleW"): '"HandleW"', + _mm("HandleT") / 2: '"HandleT" / 2', + round(_mm("BoxHead") * CLEARANCE, 4): f'"BoxHead" * {CLEARANCE}', + round(SIZE_MM * RING_RISE, 4): f'"Size" * {RING_RISE}', + SIZE_MM: '"Size"', + round(SIZE_MM * FILLET["sides"], 4): f'"Size" * {FILLET["sides"]}', + round(SIZE_MM * FILLET["faces"], 4): f'"Size" * {FILLET["faces"]}', + } + halves = {SIZE_MM * RELIEF[k] / 2: f'"Size" * {RELIEF[k] / 2}' for k in RELIEF} + found: dict[str, str] = {} + for row in dimensions: + if str(row["full_name"]).endswith(f"@{relief}"): + for value, expression in halves.items(): + if abs(float(row["value"]) - value) < 1e-3: + found[row["full_name"]] = expression + continue + for value, expression in by_value.items(): + if abs(float(row["value"]) - value) < 1e-3: + found[row["full_name"]] = expression + return found + + +async def _size(tools: dict[str, Any], size: float, ring: Ring) -> dict[str, Any]: + """verify_model against the wrench's expected size: verdict and box.""" + want = wrench_box(size, ring) + checked = await tools["verify_model"]( + {"bounding_box_mm": want, "solid_body_count": 1} + ) + box = checked["measured"]["bounding_box_mm"] + return { + "verdict": checked["verdict"], + "expected_mm": want, + "measured_mm": box.get("size") if isinstance(box, dict) else box, + } + + +@pytest.mark.timeout(1200) # 27 equations, each a rebuild +async def test_a_combination_wrench_sized_by_one_variable(scratch: Any) -> None: + """One variable, Size, drives a whole combination wrench. + + 1. Build a 13 mm wrench at fixed sizes. + 2. Add Size = 13mm and six variables computed from it, and an equation + on each dimension. + 3. Size = 19mm: one edit regrows the whole wrench. + 4. Size = 8mm in a configuration "8 mm" only; Default stays 19 mm. + 5. An expression naming a variable that doesn't exist is refused and the + wrench is unchanged. + + The handle is lettered after the equations (step 2b): every equation + rebuilds the part, and rebuilding the lettering's text cuts each time + made the run 3 minutes longer, with nothing moving on screen. + """ + app = scratch.adapter.swApp + was = scratch.adapter._attempt( + lambda: app.GetUserPreferenceToggle(_AUTO_NORMAL_TO_SKETCH), None + ) + scratch.adapter._attempt( + lambda: app.SetUserPreferenceToggle(_AUTO_NORMAL_TO_SKETCH, False), None + ) + try: + await _demo(scratch) + finally: + if was is not None: + scratch.adapter._attempt( + lambda: app.SetUserPreferenceToggle(_AUTO_NORMAL_TO_SKETCH, was), + None, + ) + + +async def _demo(scratch: Any) -> None: + """The demo's steps (the test around it keeps the camera still).""" + tools = await _tools(scratch.adapter) + relief, ring, x_axis, size_dimension = await build_wrench(tools, scratch.adapter) + listed = await tools["list_model_dimensions"]({}) + found = drivers(listed["data"], relief) + built = await _size(tools, SIZE_MM, ring) + _frame( + scratch.adapter, + room_for=wrench_box(19, ring)[0] / wrench_box(SIZE_MM, ring)[0], + ) + evidence( + "A 13 mm combination wrench, built at fixed sizes", + { + "dimensions_to_drive": found, + "size": built, + }, + call="create_part, 10 sketches, 3 extrusions, 7 cuts, a linear pattern, " + "2 fillets, set_material", + ) + assert built["verdict"] == "pass", built + assert sorted(set(found.values())) == sorted( + [ + '"Length"', + '"OpenHead"', + '"BoxHead"', + '"HeadT"', + '"HandleW"', + '"HandleT" / 2', + f'"BoxHead" * {CLEARANCE}', + f'"Size" * {RING_RISE}', + '"Size"', + f'"Size" * {FILLET["sides"]}', + f'"Size" * {FILLET["faces"]}', + f'"Size" * {RELIEF["across"] / 2}', + f'"Size" * {RELIEF["along"] / 2}', + ] + ), listed + + starting( + "Adding Size = 13mm, six variables and an equation per dimension", + call="set_equation x 25", + ) + added = [await tools["set_equation"]({"name": "Size", "expression": "13mm"})] + for name, ratio in RATIOS.items(): + added.append( + await tools["set_equation"]( + {"name": name, "expression": f'"Size" * {ratio}'} + ) + ) + for name, expression in found.items(): + added.append( + await tools["set_equation"]({"name": name, "expression": expression}) + ) + equations = await tools["list_equations"]() + _hide_references(scratch.adapter) + evidence( + "Size, six variables from it, and an equation on every dimension", + { + "added": f"{sum(a['status'] == 'success' for a in added)} of {len(added)}", + "equations": [ + f"{row['name']} = {row['expression']}" + for row in equations.get("equations", []) + ], + }, + call=f"set_equation x {len(added)}, then list_equations", + ) + assert all(a["status"] == "success" for a in added), added + + # The camera is set on the wrench alone before the spare block exists, + # so the lettering is never seen on it, only on the handle. + _frame( + scratch.adapter, + room_for=wrench_box(19, ring)[0] / wrench_box(SIZE_MM, ring)[0], + ) + starting( + "Lettering the handle's middle", + call="add_sketch_text x 2, create_cut_extrude, pattern_linear", + ) + lettering, letters = await _lettering( + tools, scratch.adapter, x_axis, size_dimension + ) + driven = {row["name"] for row in equations.get("equations", [])} + new_dimensions = (await tools["list_model_dimensions"]({}))["data"] + lettering_drivers = { + str(row["full_name"]): expression + for row in new_dimensions + if str(row["full_name"]) not in driven + for value, expression in ( + (_mm("HandleT"), '"HandleT"'), + ( + _spacing_to_middle(), + f'"Size" * {HANDLE_MIDDLE} + {-SPARE_CENTRE_MM:g}mm', + ), + ) + if abs(float(row["value"]) - value) < 1e-3 + } + tied = [ + await tools["set_equation"]({"name": name, "expression": expression}) + for name, expression in lettering_drivers.items() + ] + _frame( + scratch.adapter, + room_for=wrench_box(19, ring)[0] / wrench_box(SIZE_MM, ring)[0], + ) + evidence( + "The handle lettered in its middle, the size read from Size", + { + "handle_reads": letters, + "equations": [f"{n} = {e}" for n, e in lettering_drivers.items()], + }, + call="set_custom_property (WrenchSize = Size's dimension), add_sketch_text x 2 " + "on a spare block, pattern_linear onto the handle's middle, set_equation x 2", + ) + assert len(lettering_drivers) == 2, new_dimensions + assert all(t["status"] == "success" for t in tied), tied + assert all("13 mm" in t for t in letters), letters + + starting( + "Size = 19mm, then re-letter", + call='set_equation({"name": "Size", "expression": "19mm"}), set_sketch_text x 2', + ) + grown = await tools["set_equation"]({"name": "Size", "expression": "19mm"}) + at_19 = await _size(tools, 19, ring) + relettered_19 = await _reletter(tools, lettering, letters) + _hide_references(scratch.adapter) + evidence( + "Size = 19mm: one edit, the whole wrench regrows", + { + "equation": '"Size" = 19mm', + "change": { + "Size_mm": [13, grown.get("equation", {}).get("value")], + "box_mm": [built["measured_mm"], at_19["measured_mm"]], + "handle_reads": relettered_19, + }, + "size": at_19, + }, + call='set_equation({"name": "Size", "expression": "19mm"}), then ' + "set_sketch_text on both lettering sketches (re-letter)", + ) + assert grown["status"] == "success", grown + assert at_19["verdict"] == "pass", at_19 + assert all("19 mm" in t for t in relettered_19["after"]), relettered_19 + + starting( + 'Size = 8mm in configuration "8 mm" only, then re-letter', + call="create_configuration, set_equation, activate_configuration, set_sketch_text x 2", + ) + made = await tools["create_configuration"]({"name": "8 mm"}) + assert made["status"] == "success", made + small = await tools["set_equation"]( + {"name": "Size", "expression": "8mm", "configurations": ["8 mm"]} + ) + default_size = await _size(tools, 19, ring) + await tools["activate_configuration"]({"name": "8 mm"}) + small_size = await _size(tools, 8, ring) + relettered_8 = await _reletter(tools, lettering, relettered_19["after"]) + _hide_references(scratch.adapter) + evidence( + 'Size = 8mm in configuration "8 mm" only', + { + "equation": '"Size" = 8mm, in "8 mm"', + "change": { + "Size_mm": { + "Default": 19, + "8 mm": small.get("equation", {}).get("values"), + }, + "box_mm": { + "Default": default_size["measured_mm"], + "8 mm": small_size["measured_mm"], + }, + "handle_reads": relettered_8, + }, + "8 mm": small_size, + "Default": default_size, + }, + call='set_equation({"name": "Size", "expression": "8mm", ' + '"configurations": ["8 mm"]}), activate_configuration, re-letter', + ) + assert small["status"] == "success", small + assert small["equation"]["values"] == {"8 mm": pytest.approx(8.0)}, small + assert small_size["verdict"] == "pass", small_size + assert default_size["verdict"] == "pass", default_size + assert all("8 mm" in t for t in relettered_8["after"]), relettered_8 + + starting( + 'Back to Default (19 mm), re-letter, then "Size" = "Nut" * 2', + call="activate_configuration, set_sketch_text x 2, set_equation", + ) + await tools["activate_configuration"]({"name": "Default"}) + back = await _reletter(tools, lettering, relettered_8["after"]) + refused = await tools["set_equation"]({"name": "Size", "expression": '"Nut" * 2'}) + unchanged = await _size(tools, 19, ring) + _hide_references(scratch.adapter) + evidence( + "A variable that doesn't exist is refused; the wrench is unchanged", + { + "equation": '"Size" = "Nut" * 2', + "refused": [refused["status"], refused.get("error_type")], + "change": { + "box_mm": [at_19["measured_mm"], unchanged["measured_mm"]], + "handle_reads": back, + }, + "size": unchanged, + }, + call='set_equation({"name": "Size", "expression": "\\"Nut\\" * 2"})', + ) + assert refused["error_type"] == "equation_refused", refused + assert unchanged["verdict"] == "pass", unchanged + evidence( + "Equations demo done", + { + "Size_mm": [13, 19, 8, 19], + "one variable drives": f"{len(added) + len(tied)} equations", + "handle_reads": back["after"], + }, + call="Size 13 mm -> 19 mm -> 8 mm (its own configuration) -> 19 mm", + ) diff --git a/tests/solidworks_mcp/adapters/solidworks/test_equations.py b/tests/solidworks_mcp/adapters/solidworks/test_equations.py new file mode 100644 index 00000000..c336cd02 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_equations.py @@ -0,0 +1,391 @@ +"""The real adapter's equation methods, against a fake equation manager. + +Spec: tools/equations. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, cast + +import pytest + +from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus +from solidworks_mcp.adapters.solidworks import configurations as cfg +from solidworks_mcp.adapters.solidworks import equations as eq +from solidworks_mcp.adapters.solidworks.equations import ( + SolidWorksEquationsMixin, + equation_text, + split_equation, +) + +pytestmark = pytest.mark.asyncio + + +class FakeManager: + """IEquationMgr as SolidWorks 2026 behaves from Python (the live probe). + + ``Add2`` adds; writing ``Equation(i)`` (through ``_oleobj_.Invoke``) + changes it everywhere, or leaves it and sets ``Status`` -1 when told to + refuse; the set call returns 0, or -1 when given any array of + configuration names (as the real one does) or told to refuse. + """ + + def __init__(self, model: FakeModel) -> None: + self.model = model + self.texts: list[str] = [] + self.values: list[Any] = [] + self.globals: list[Any] = [] + self.Status = 0 + self.refuse_add = False + self.refuse_set = False + self.raise_on_set = False + self.fail_status = False + self.store_as: str | None = None + self.calls: list[tuple[Any, ...]] = [] + self.evaluated = 0 + self._oleobj_ = self # IDispatch: GetIDsOfNames and Invoke below + + def GetIDsOfNames(self, name: str) -> int: + assert name == "Equation" + return 7 + + def Invoke( + self, dispid: int, lcid: int, flags: int, wanted: bool, index: int, text: str + ) -> None: + assert (dispid, lcid, flags, wanted) == (7, 0, 4, False) # a property put + self.calls.append(("Put", index, text, self.model.active)) + self._store(index, text) + + def _store(self, index: int, text: str) -> bool: + """Keep ``text`` unless told to refuse; whether it was kept.""" + if self.refuse_set: + self.refuse_set = False + self.Status = -1 + return False + self.texts[index] = self.store_as if self.store_as is not None else text + self.store_as = None + self.Status = -1 if self.fail_status else 1 + self.fail_status = False + return True + + def GetCount(self) -> int: + return len(self.texts) + + def Equation(self, index: int) -> str: + return self.texts[index] + + def Value(self, index: int) -> Any: + return self.values[index] + + def GlobalVariable(self, index: int) -> bool: + if self.globals[index] is None: + raise RuntimeError("no such property") + return bool(self.globals[index]) + + def Add2(self, index: int, text: str, solve: bool) -> int: + self.calls.append(("Add2", index, text, solve)) + if self.refuse_add: + return -1 + self.texts.append(text) + self.values.append(1.0) + self.globals.append("@" not in text.split("=")[0]) + self.Status = -1 if self.fail_status else 1 + return len(self.texts) - 1 + + def SetEquationAndConfigurationOption( + self, index: int, text: str, option: int, names: Any + ) -> int: + self.calls.append(("Set", index, text, option, names, self.model.active)) + if self.raise_on_set: + raise RuntimeError("COM error") + if names is not None: + self.Status = -1 + return -1 + return 0 if self._store(index, text) else -1 + + def Delete(self, index: int) -> int: + self.calls.append(("Delete", index)) + del self.texts[index], self.values[index], self.globals[index] + return 0 + + def EvaluateAll(self) -> int: + self.evaluated += 1 + return 0 + + +class FakeModel: + """A model with an equation manager, dimensions and configurations.""" + + def __init__(self, dimensions: set[str]) -> None: + self.manager = FakeManager(self) + self.dimensions = dimensions + self.rebuilt = 0 + self.active: str | None = "Default" + self.shown: list[str] = [] + + def GetEquationMgr(self) -> FakeManager: + return self.manager + + def Parameter(self, name: str) -> Any: + return SimpleNamespace(name=name) if name in self.dimensions else None + + def ForceRebuild3(self, top_only: bool) -> None: + self.rebuilt += 1 + + def GetConfigurationNames(self) -> tuple[str, ...]: + return ("Default", "Long", "Short") + + def GetActiveConfiguration(self) -> Any: + return SimpleNamespace(Name=self.active) if self.active else None + + def ShowConfiguration2(self, name: str) -> bool: + self.shown.append(name) + self.active = name + return True + + +class FakeAdapter(SolidWorksEquationsMixin): + def __init__(self, model: Any) -> None: + self.currentModel = model + + def _attempt(self, fn: Any, default: Any = None) -> Any: + try: + return fn() + except Exception: + return default + + def _handle_com_operation(self, name: str, fn: Any) -> AdapterResult[Any]: + try: + return AdapterResult(status=AdapterResultStatus.SUCCESS, data=fn()) + except Exception as error: + return AdapterResult(status=AdapterResultStatus.ERROR, error=str(error)) + + +@pytest.fixture(autouse=True) +def _no_flagging(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(eq.sw_type_info, "flagged", lambda obj, *_: obj) + monkeypatch.setattr(cfg, "string_array", lambda names: tuple(names)) + + +def _adapter(*texts: str, dimensions: set[str] | None = None) -> FakeAdapter: + model = FakeModel(dimensions or {"D1@Sketch1"}) + for text in texts: + model.manager.texts.append(text) + model.manager.values.append(2.0) + model.manager.globals.append("@" not in text.split("=")[0]) + return FakeAdapter(model) + + +def _manager(adapter: FakeAdapter) -> FakeManager: + return cast(FakeManager, adapter.currentModel.manager) + + +def test_equation_text_quotes_the_name() -> None: + assert equation_text("Width", " 60mm ") == '"Width" = 60mm' + + +@pytest.mark.parametrize( + ("text", "parts"), + [ + ('"Width" = 60mm', ("Width", "60mm")), + ('"D1@Sketch1"= "Width" / 2', ("D1@Sketch1", '"Width" / 2')), + ('"Odd" 5', ("Odd", "5")), + ("no quotes", ("", "no quotes")), + ], +) +def test_split_equation(text: str, parts: tuple[str, str]) -> None: + assert split_equation(text) == parts + + +async def test_list_gives_each_equation_with_its_kind_and_value() -> None: + adapter = _adapter( + '"Width" = 60mm', '"D1@Sketch1" = "Width" / 2', '"Fillet1" = "suppressed"' + ) + manager = _manager(adapter) + manager.globals[2] = None # GlobalVariable unreadable: not a global + manager.values[2] = None + rows = (await adapter.list_equations()).data + assert [(r["name"], r["kind"], r["value"]) for r in rows] == [ + ("Width", "global_variable", 2.0), + ("D1@Sketch1", "dimension", 2.0), + ("Fillet1", "other", None), + ] + assert rows[1]["expression"] == '"Width" / 2' + + +async def test_no_model_is_an_error() -> None: + result = await FakeAdapter(None).list_equations() + assert result.error == "No active model" + + +async def test_a_new_global_variable_is_added_in_all_configurations() -> None: + adapter = _adapter() + result = await adapter.set_equation("Width", "60mm") + manager = _manager(adapter) + assert manager.calls == [("Add2", -1, '"Width" = 60mm', True)] + assert result.data["action"] == "added" + assert result.data["kind"] == "global_variable" + assert result.data["configurations"] == ["Default", "Long", "Short"] + assert manager.evaluated == 1 and adapter.currentModel.rebuilt == 1 + + +async def test_a_new_equation_for_this_configuration_is_scoped_after_adding() -> None: + adapter = _adapter() + result = await adapter.set_equation("Width", "60mm", "this") + assert _manager(adapter).calls[1] == ( + "Set", + 0, + '"Width" = 60mm', + 1, + None, + "Default", + ) + assert result.data["configurations"] == ["Default"] + + +async def test_named_configurations_are_set_one_at_a_time_then_shown_back() -> None: + adapter = _adapter('"Width" = 60mm') + result = await adapter.set_equation("width", "80mm", ["Long", "Short"]) + model = adapter.currentModel + assert _manager(adapter).calls == [ + ("Set", 0, '"width" = 80mm', 1, None, "Long"), + ("Set", 0, '"width" = 80mm', 1, None, "Short"), + ] + assert model.shown == ["Long", "Short", "Default"] + assert result.data["action"] == "changed" + # Read back in Default, so the reply says what was set and each value. + assert result.data["expression"] == "80mm" + assert result.data["values"] == {"Long": 2.0, "Short": 2.0} + assert result.data["value"] == 2.0 + + +async def test_an_unreadable_value_in_a_configuration_is_none() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).values[0] = None + result = await adapter.set_equation("Width", "80mm", ["Long"]) + assert result.data["values"] == {"Long": None} + + +async def test_a_change_in_all_configurations_writes_the_property() -> None: + adapter = _adapter('"Width" = 60mm') + await adapter.set_equation("Width", "80mm") + assert _manager(adapter).calls == [("Put", 0, '"Width" = 80mm', "Default")] + + +async def test_solidworks_reformatting_the_text_is_not_a_refusal() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).store_as = '"Width"= 80MM' + result = await adapter.set_equation("Width", "80mm") + assert result.is_success, result.error + + +async def test_an_add_solidworks_refuses_changes_nothing() -> None: + adapter = _adapter() + _manager(adapter).refuse_add = True + result = await adapter.set_equation("Width", '"Nope" * 2') + assert result.error.startswith('SolidWorks refused the equation "Width"') + assert _manager(adapter).texts == [] + + +async def test_an_add_that_fails_to_solve_is_deleted_again() -> None: + adapter = _adapter() + _manager(adapter).fail_status = True + result = await adapter.set_equation("Width", '"Nope" * 2') + assert "refused" in result.error + assert _manager(adapter).texts == [] + assert ("Delete", 0) in _manager(adapter).calls + + +async def test_an_add_its_configuration_refuses_is_deleted_again() -> None: + adapter = _adapter() + _manager(adapter).refuse_set = True + result = await adapter.set_equation("Width", "5mm", ["Long"]) + assert result.error == ( + 'SolidWorks refused the equation "Width" = 5mm in Long; nothing was added.' + ) + assert _manager(adapter).texts == [] + assert adapter.currentModel.active == "Default" + + +async def test_a_change_solidworks_refuses_restores_the_old_text() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).refuse_set = True + result = await adapter.set_equation("Width", '"Nope" * 2') + assert 'was left as "Width" = 60mm' in result.error + assert _manager(adapter).texts == ['"Width" = 60mm'] + + +async def test_a_change_in_one_configuration_it_refuses_is_restored() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).refuse_set = True + result = await adapter.set_equation("Width", '"Nope" * 2', "this") + assert 'was left as "Width" = 60mm' in result.error + assert [c[0] for c in _manager(adapter).calls] == ["Set", "Set"] + + +async def test_a_change_that_fails_to_solve_restores_the_old_text() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).fail_status = True + result = await adapter.set_equation("Width", '"Nope" * 2') + assert "refused" in result.error + assert _manager(adapter).texts == ['"Width" = 60mm'] + + +async def test_a_change_stored_differently_is_restored() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).store_as = '"Width" = 1' + result = await adapter.set_equation("Width", "80mm") + assert "refused" in result.error + assert _manager(adapter).texts == ['"Width" = 60mm'] + + +async def test_the_active_configuration_is_shown_again_after_an_error() -> None: + adapter = _adapter('"Width" = 60mm') + _manager(adapter).raise_on_set = True + result = await adapter.set_equation("Width", "80mm", ["Long"]) + assert result.error == "COM error" + assert adapter.currentModel.active == "Default" + + +async def test_with_no_active_configuration_nothing_is_shown_back() -> None: + adapter = _adapter('"Width" = 60mm') + adapter.currentModel.active = None + result = await adapter.set_equation("Width", "80mm", ["Long"]) + assert result.is_success, result.error + assert adapter.currentModel.shown == ["Long"] + + +async def test_a_dimension_the_model_lacks_is_refused_first() -> None: + adapter = _adapter() + result = await adapter.set_equation("D9@Nowhere", "5mm") + assert result.error.startswith("No dimension named 'D9@Nowhere'") + assert _manager(adapter).calls == [] + + +async def test_a_known_dimension_is_driven() -> None: + adapter = _adapter('"Width" = 60mm') + result = await adapter.set_equation("D1@Sketch1", '"Width" / 2') + assert result.data["kind"] == "dimension" + + +async def test_an_unknown_configuration_is_refused() -> None: + result = await _adapter().set_equation("Width", "1mm", ["Tall"]) + assert result.error.startswith("No configuration named 'Tall'") + + +async def test_delete_removes_the_equation_and_solves() -> None: + adapter = _adapter('"Width" = 60mm', '"D1@Sketch1" = "Width"') + result = await adapter.delete_equation("d1@sketch1") + assert result.data == {"deleted": "D1@Sketch1", "equations": ["Width"]} + assert _manager(adapter).evaluated == 1 + + +@pytest.mark.parametrize( + ("texts", "known"), [(('"Width" = 1',), "Width"), ((), "none")] +) +async def test_delete_an_unknown_name_lists_the_names( + texts: tuple[str, ...], known: str +) -> None: + result = await _adapter(*texts).delete_equation("Ghost") + assert result.error == f"No equation named 'Ghost'; the model has {known}." diff --git a/tests/solidworks_mcp/adapters/solidworks/test_features.py b/tests/solidworks_mcp/adapters/solidworks/test_features.py index d745b5a0..5bf3af02 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_features.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_features.py @@ -1038,6 +1038,26 @@ def test_through_all_both_falls_back_to_the_single_ended_enum() -> None: ] +def test_a_blind_cut_both_ways_is_one_mid_plane_cut() -> None: + """Blind with both_directions straddles the sketch plane: T1 = mid-plane, + ``depth`` in total, and no flipped retry (both sides are already cut).""" + feature = SimpleNamespace(Name="Cut-Extrude6") + adapter, log = _cut_adapter_recording( + cut4=lambda _args: feature, cut3=lambda _args: None + ) + adapter.constants = {**adapter.constants, "swEndCondMidPlane": 6} + + result = features._create_cut_extrude_impl( + adapter, ExtrusionParameters(depth=13.0, both_directions=True) + ) + + assert result.is_success, result.error + assert result.data.parameters["direction_flipped"] is False + cut_args = [entry[1] for entry in log if entry[0] != "select"] + # (Sd, Dir, T1, D1) of the one FeatureCut4 call. + assert [(a[0], a[2], a[3], a[5]) for a in cut_args] == [(True, False, 6, 0.013)] + + def test_blind_cut_from_a_face_sketch_flips_direction() -> None: """The requested direction points out of the part and builds nothing, so the single-ended cut is retried the other way (#193).""" diff --git a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py index 91d186d1..b2bf876f 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py @@ -876,6 +876,214 @@ def test_add_sketch_dimension_radial_diameter_and_selection_errors() -> None: assert "Failed to select secondary entity" in (bad_secondary.error or "") +def _polygon_adapter( + segments: tuple[object, ...], +) -> tuple[_FakeSketchAdapter, list[object]]: + """A fake adapter whose ``Polygon_1`` is ``segments``; the selections made.""" + adapter = _FakeSketchAdapter() + adapter.currentSketchManager = object() + adapter._sketch_entities = {"Polygon_1": segments} + selected: list[object] = [] + adapter._select_sketch_entity = lambda entity, append: ( + selected.append(entity) or True + ) + adapter.currentModel = SimpleNamespace( + ClearSelection2=lambda *_args: True, + AddDiameterDimension2=lambda *_args: SimpleNamespace( + GetDimension2=lambda *_a: SimpleNamespace(SetSystemValue3=lambda *_b: True) + ), + ) + return adapter, selected + + +def test_a_polygon_angle_turns_its_first_corner() -> None: + """The vertex point CreatePolygon takes is turned ``angle`` degrees from +x.""" + adapter = _FakeSketchAdapter() + create = Mock(return_value=(object(),)) + adapter.currentSketchManager = SimpleNamespace(CreatePolygon=create) + + result = sketch._add_polygon_impl(adapter, 10.0, 0.0, 6.5, 6, 30.0) + + assert result.is_success, result.error + args = create.call_args.args + assert args[3] == pytest.approx((10.0 + 6.5 * math.cos(math.radians(30))) / 1000) + assert args[4] == pytest.approx(6.5 * math.sin(math.radians(30)) / 1000) + assert args[6:] == (6, True) + + +def test_an_ellipse_angle_turns_its_axes() -> None: + """The major point is ``angle`` from +x, the minor point a quarter turn on.""" + adapter = _FakeSketchAdapter() + create = Mock(return_value=object()) + adapter.currentSketchManager = SimpleNamespace(CreateEllipse=create) + + result = sketch._add_ellipse_impl(adapter, 10.0, 0.0, 13.0, 2.6, 15.0) + + assert result.is_success, result.error + args = create.call_args.args + turn = math.radians(15) + assert args[3] == pytest.approx((10.0 + 6.5 * math.cos(turn)) / 1000) + assert args[4] == pytest.approx(6.5 * math.sin(turn) / 1000) + assert args[6] == pytest.approx((10.0 - 1.3 * math.sin(turn)) / 1000) + assert args[7] == pytest.approx(1.3 * math.cos(turn) / 1000) + + +class _Point: + """A sketch point that records whether it was selected.""" + + def __init__(self, x: float, selects: bool = True) -> None: + self.X, self.Y, self.Z = x, 0.0, 0.0 + self._selects = selects + self.selected: list[bool] = [] + + def Select2(self, append: bool, _mark: int) -> bool: + self.selected.append(append) + return self._selects + + +def _ellipse_adapter( + ellipse: object, added: object +) -> tuple[_FakeSketchAdapter, list[tuple[object, ...]]]: + """A fake adapter with ``Ellipse_1``; the AddDimension2 calls made.""" + adapter = _FakeSketchAdapter() + adapter.currentSketchManager = object() + adapter._sketch_entities = {"Ellipse_1": ellipse} + calls: list[tuple[object, ...]] = [] + + def _add(*args: object) -> object: + calls.append(args) + return added + + adapter.currentModel = SimpleNamespace( + ClearSelection2=lambda *_a: True, AddDimension2=_add + ) + return adapter, calls + + +def _display(reads: float, values: list[float]) -> SimpleNamespace: + """A display dimension that reads ``reads`` m and records values set.""" + dimension = SimpleNamespace( + SystemValue=reads, SetSystemValue3=lambda v, *_a: values.append(v) or True + ) + return SimpleNamespace(GetDimension2=lambda *_a: dimension) + + +@pytest.mark.parametrize( + ("axis", "getter"), + [("major_axis", "GetMajorPoint2"), ("minor_axis", "GetMinorPoint2")], +) +def test_an_ellipse_axis_is_dimensioned_from_its_centre(axis: str, getter: str) -> None: + """Centre then axis point, text beside the axis; it holds half the axis.""" + centre, end = _Point(0.0), _Point(0.0065) + ellipse = SimpleNamespace(GetCenterPoint2=lambda: centre, **{getter: lambda: end}) + values: list[float] = [] + adapter, calls = _ellipse_adapter(ellipse, _display(0.0065, values)) + + result = sketch._add_sketch_dimension_impl(adapter, "Ellipse_1", None, axis, 13.0) + + assert result.is_success, result.error + assert (centre.selected, end.selected) == ([False], [True]) + # Beside the axis's middle: half way along x, 5 mm off it in y. + assert calls[0] == (pytest.approx(0.00325), pytest.approx(0.005), 0.0) + assert values == [pytest.approx(0.0065)] + + +def test_an_axis_dimension_that_is_not_aligned_is_refused() -> None: + """A dimension reading less than the axis (horizontal on a turned one).""" + ellipse = SimpleNamespace( + GetCenterPoint2=lambda: _Point(0.0), GetMajorPoint2=lambda: _Point(0.0065) + ) + values: list[float] = [] + adapter, _calls = _ellipse_adapter(ellipse, _display(0.0056, values)) + + result = sketch._add_sketch_dimension_impl( + adapter, "Ellipse_1", None, "major_axis", 13.0 + ) + + assert result.status == AdapterResultStatus.ERROR + assert "isn't aligned with the axis" in (result.error or "") + assert values == [] + + +def test_a_zero_length_axis_puts_its_text_above_the_centre() -> None: + ellipse = SimpleNamespace( + GetCenterPoint2=lambda: _Point(0.0), GetMinorPoint2=lambda: _Point(0.0) + ) + adapter, calls = _ellipse_adapter(ellipse, _display(0.0, [])) + + result = sketch._add_sketch_dimension_impl( + adapter, "Ellipse_1", None, "minor_axis", 0.0 + ) + + assert result.is_success, result.error + assert calls[0] == (0.0, pytest.approx(0.005), 0.0) + + +def test_an_axis_dimension_needs_an_ellipse() -> None: + adapter, _calls = _ellipse_adapter(SimpleNamespace(), None) + + result = sketch._add_sketch_dimension_impl( + adapter, "Ellipse_1", None, "major_axis", 13.0 + ) + + assert result.status == AdapterResultStatus.ERROR + assert "is not an ellipse" in (result.error or "") + + +def test_an_axis_point_that_cannot_be_selected_is_an_error() -> None: + ellipse = SimpleNamespace( + GetCenterPoint2=lambda: _Point(0.0), GetMajorPoint2=lambda: _Point(1.0, False) + ) + adapter, _calls = _ellipse_adapter(ellipse, None) + + result = sketch._add_sketch_dimension_impl( + adapter, "Ellipse_1", None, "major_axis", 13.0 + ) + + assert result.status == AdapterResultStatus.ERROR + assert "Failed to select the major_axis points" in (result.error or "") + + +def test_no_axis_dimension_from_solidworks_is_an_error() -> None: + ellipse = SimpleNamespace( + GetCenterPoint2=lambda: _Point(0.0), GetMinorPoint2=lambda: _Point(1.0) + ) + adapter, _calls = _ellipse_adapter(ellipse, None) + + result = sketch._add_sketch_dimension_impl( + adapter, "Ellipse_1", None, "minor_axis", 2.6 + ) + + assert result.status == AdapterResultStatus.ERROR + assert "added no minor_axis dimension" in (result.error or "") + + +def test_a_diameter_on_a_polygon_dimensions_its_construction_circle() -> None: + """The circle inside the polygon sizes it across flats; its sides are skipped.""" + side = SimpleNamespace(GetType=lambda: 0) + circle = SimpleNamespace(GetType=lambda: 1) + adapter, selected = _polygon_adapter((side, side, circle)) + + result = sketch._add_sketch_dimension_impl( + adapter, "Polygon_1", None, "diameter", 13.0 + ) + + assert result.is_success, result.error + assert selected == [circle] + + +def test_a_polygon_with_no_circle_cannot_be_dimensioned() -> None: + side = SimpleNamespace(GetType=lambda: 0) + adapter, _selected = _polygon_adapter((side, side)) + + result = sketch._add_sketch_dimension_impl( + adapter, "Polygon_1", None, "diameter", 13.0 + ) + + assert result.status == AdapterResultStatus.ERROR + assert "no construction circle" in (result.error or "") + + def test_add_sketch_dimension_missing_entities_and_placement_errors() -> None: adapter = _FakeSketchAdapter() adapter.currentSketchManager = object() @@ -2513,3 +2721,284 @@ class _Mixin(SolidWorksSketchMixin): assert await _Mixin().create_sketch(None, (1.0, 2.0, 3.0)) == "ok" assert calls == [(None, (1.0, 2.0, 3.0))] + + +class _TextFormat: + def __init__(self) -> None: + self.CharHeight = 0.0035 + + +class _CurveParams: + def __init__(self, start: tuple[float, ...], end: tuple[float, ...]) -> None: + self.StartPoint = start + self.EndPoint = end + + +class _Edge: + """An IEdge whose curve runs from ``start`` to ``end`` (model metres).""" + + def __init__(self, start: tuple[float, ...], end: tuple[float, ...]) -> None: + self._params = _CurveParams(start, end) + + def GetCurveParams3(self) -> _CurveParams: + return self._params + + +class _SketchText: + """ISketchText: a format, the text shown, edges, and its position.""" + + def __init__(self, shown: str, edges: tuple[_Edge, ...] = ()) -> None: + self.Text = shown + self._format = _TextFormat() + self._edges = edges + self.coordinates = (0.0, 0.0, 0.0) + + def GetTextFormat(self) -> _TextFormat: + return self._format + + def SetTextFormat(self, _use_doc: bool, text_format: _TextFormat) -> bool: + self._format = text_format + return True + + def GetEdges2(self) -> tuple[_Edge, ...]: + return self._edges + + def GetCoordinates(self) -> tuple[float, float, float]: + return self.coordinates + + def SetCoordinates(self, x: float, y: float, z: float) -> bool: + self.coordinates = (x, y, z) + return True + + +def _text_adapter( + inserted: object, +) -> tuple[_FakeSketchAdapter, list[tuple[object, ...]]]: + """A fake adapter with an open sketch; the InsertSketchText calls made. + + Its sketch maps model x to sketch x and model z to sketch y (a sketch + on a face 2 mm up, seen from above), through the math utility. + """ + adapter = _FakeSketchAdapter() + adapter.currentSketchManager = object() + calls: list[tuple[object, ...]] = [] + + def _insert(*args: object) -> object: + calls.append(args) + return inserted + + adapter.currentModel = SimpleNamespace( + ClearSelection2=lambda *_a: True, InsertSketchText=_insert + ) + + 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, z, 0.0)) + ) + + adapter.swApp = SimpleNamespace( + GetMathUtility=lambda: SimpleNamespace(CreatePoint=_point) + ) + adapter.currentSketch = SimpleNamespace(ModelToSketchTransform=object()) + return adapter, calls + + +def test_sketch_text_at_a_point_at_a_height() -> None: + """Normal spacing, no flags; the height is set and read back.""" + adapter, calls = _text_adapter(_SketchText("solidworksmcp-python 13.00 mm")) + + result = sketch._add_sketch_text_impl( + adapter, 'solidworksmcp-python $PRP:"Size" mm', 10.0, -2.0, 4.0, None + ) + + assert result.is_success, result.error + assert calls[0][:3] == (pytest.approx(0.01), pytest.approx(-0.002), 0.0) + assert calls[0][3:] == ('solidworksmcp-python $PRP:"Size" mm', 0, 0, 0, 100, 100) + assert result.data["text"] == "solidworksmcp-python 13.00 mm" + assert result.data["height"] == pytest.approx(4.0) + assert result.data["id"].startswith("Text_") + + +def test_sketch_text_centred_on_a_model_point() -> None: + """Its middle (from its edges) is moved onto the point, mapped into the sketch.""" + edges = ( + _Edge((0.000, 0.002, 0.000), (0.020, 0.002, 0.000)), + _Edge((0.040, 0.002, 0.004), (0.040, 0.002, 0.000)), + ) + text = _SketchText("abc", edges) + adapter, calls = _text_adapter(text) + + result = sketch._add_sketch_text_impl(adapter, "abc", 0, 0, 4.0, [60.0, 2.0, 1.0]) + + assert result.is_success, result.error + # Inserted at the point already (mapped into the sketch: 0.060, 0.001), + # so it never shows at the sketch's origin first. + assert calls[0][:2] == (pytest.approx(0.060), pytest.approx(0.001)) + # Middle (0.020, 0.002) in the sketch; the point maps to (0.060, 0.001). + assert text.coordinates == ( + pytest.approx(0.040), + pytest.approx(-0.001), + 0.0, + ) + + +def test_sketch_text_with_no_edges_cannot_be_centred() -> None: + adapter, _calls = _text_adapter(_SketchText("abc")) + + result = sketch._add_sketch_text_impl(adapter, "abc", 0, 0, 4.0, [60.0, 2.0, 0.0]) + + assert result.status == AdapterResultStatus.ERROR + assert "no edges to centre it by" in (result.error or "") + + +def test_sketch_text_needs_an_open_sketch() -> None: + adapter = _FakeSketchAdapter() + + result = sketch._add_sketch_text_impl(adapter, "abc", 0, 0, 3.5, None) + + assert result.status == AdapterResultStatus.ERROR + assert "No active sketch" in (result.error or "") + + +def test_no_sketch_text_from_solidworks_is_an_error() -> None: + adapter, _calls = _text_adapter(None) + + result = sketch._add_sketch_text_impl(adapter, "abc", 0, 0, 3.5, None) + + assert result.status == AdapterResultStatus.ERROR + assert "added no sketch text" in (result.error or "") + + +@pytest.mark.asyncio +async def test_the_mixin_passes_sketch_text_on() -> None: + adapter, calls = _text_adapter(_SketchText("abc")) + adapter.add_sketch_text = sketch.SolidWorksSketchMixin.add_sketch_text.__get__( + adapter + ) + + result = await adapter.add_sketch_text("abc", 1.0, 2.0, 5.0) + + assert result.is_success, result.error + assert calls[0][:2] == (pytest.approx(0.001), pytest.approx(0.002)) + + +class _Lettering: + """ISketchText whose text resolves a $PRP link to ``value``.""" + + def __init__(self, shown: str, value: str) -> None: + self._text = shown + self._value = value + + @property + def Text(self) -> str: + return self._text.replace('$PRP:"WrenchSize"', self._value) + + @Text.setter + def Text(self, text: str) -> None: + self._text = text + + +def _lettered_model( + texts: list[_Lettering], feature: object | None = True +) -> tuple[_FakeSketchAdapter, list[str]]: + """A fake part with ``Sketch12`` holding ``texts``; the calls made, in order.""" + calls: list[str] = [] + sketch = SimpleNamespace(GetSketchTextSegments=lambda: tuple(texts)) + found = ( + SimpleNamespace( + GetSpecificFeature2=lambda: sketch, + Select2=lambda *_a: calls.append("select") or True, + ) + if feature + else None + ) + adapter = _FakeSketchAdapter() + adapter.currentModel = SimpleNamespace( + FeatureByName=lambda name: found if name == "Sketch12" else None, + ClearSelection2=lambda *_a: True, + EditSketch=lambda: calls.append("edit"), + GetActiveSketch2=lambda: sketch, + SketchManager=SimpleNamespace( + InsertSketch=lambda _rebuild: calls.append("close") + ), + ForceRebuild3=lambda _top: calls.append("rebuild"), + ) + return adapter, calls + + +def test_sketch_text_is_rewritten_with_the_sketch_open() -> None: + """Open, write, close, rebuild; the link reads the new size.""" + text = _Lettering("size 13.00 mm", "19.00") + adapter, calls = _lettered_model([text]) + + result = sketch._set_sketch_text_impl( + adapter, "Sketch12", 'size $PRP:"WrenchSize" mm' + ) + + assert result.is_success, result.error + assert result.data == { + "sketch": "Sketch12", + "before": ["size 13.00 mm"], + "after": ["size 19.00 mm"], + } + assert calls == ["select", "edit", "close", "rebuild"] + + +def test_rewriting_text_in_a_missing_sketch_changes_nothing() -> None: + adapter, calls = _lettered_model([], feature=None) + + result = sketch._set_sketch_text_impl(adapter, "Sketch12", "abc") + + assert result.status == AdapterResultStatus.ERROR + assert "Sketch 'Sketch12' not found" in (result.error or "") + assert calls == [] + + +def test_a_sketch_with_no_text_is_an_error() -> None: + adapter, calls = _lettered_model([]) + + result = sketch._set_sketch_text_impl(adapter, "Sketch12", "abc") + + assert result.status == AdapterResultStatus.ERROR + assert "has no text to rewrite" in (result.error or "") + assert calls == [] + + +def test_the_sketch_is_closed_even_when_writing_fails() -> None: + class _Stuck(_Lettering): + @property + def Text(self) -> str: + return "abc" + + @Text.setter + def Text(self, _text: str) -> None: + raise RuntimeError("read only") + + adapter, calls = _lettered_model([_Stuck("abc", "")]) + + result = sketch._set_sketch_text_impl(adapter, "Sketch12", "xyz") + + assert result.status == AdapterResultStatus.ERROR + assert calls == ["select", "edit", "close"] + + +def test_rewriting_sketch_text_needs_a_model() -> None: + adapter = _FakeSketchAdapter() + + result = sketch._set_sketch_text_impl(adapter, "Sketch12", "abc") + + assert result.status == AdapterResultStatus.ERROR + assert "No active model" in (result.error or "") + + +@pytest.mark.asyncio +async def test_the_mixin_passes_set_sketch_text_on() -> None: + adapter, _calls = _lettered_model([_Lettering("a", "")]) + adapter.set_sketch_text = sketch.SolidWorksSketchMixin.set_sketch_text.__get__( + adapter + ) + + result = await adapter.set_sketch_text("Sketch12", "b") + + assert result.data["after"] == ["b"] diff --git a/tests/solidworks_mcp/adapters/test_base.py b/tests/solidworks_mcp/adapters/test_base.py index 13ab8f90..4daf6ddb 100644 --- a/tests/solidworks_mcp/adapters/test_base.py +++ b/tests/solidworks_mcp/adapters/test_base.py @@ -132,6 +132,12 @@ async def test_base_default_sketch_helpers_return_error() -> None: result = await adapter.add_ellipse(0.0, 0.0, 2.0, 1.0) assert result.status == AdapterResultStatus.ERROR + result = await adapter.add_sketch_text("abc") + assert result.status == AdapterResultStatus.ERROR + + result = await adapter.set_sketch_text("Sketch1", "abc") + assert result.status == AdapterResultStatus.ERROR + result = await adapter.add_sketch_constraint("e1", None, "coincident") assert result.status == AdapterResultStatus.ERROR diff --git a/tests/solidworks_mcp/adapters/test_base_equations.py b/tests/solidworks_mcp/adapters/test_base_equations.py new file mode 100644 index 00000000..4fb75ec0 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_base_equations.py @@ -0,0 +1,26 @@ +"""The equation methods on the base adapter: none is implemented there.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from .test_base_configurations import _bare + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("name", "args"), + [ + ("list_equations", ()), + ("set_equation", ("Width", "60mm")), + ("delete_equation", ("Width",)), + ], +) +async def test_each_equation_method_names_itself_as_missing( + name: str, args: tuple[Any, ...] +) -> None: + result = await getattr(_bare(), name)(*args) + + assert result.error == f"{name} is not implemented by this adapter" diff --git a/tests/solidworks_mcp/adapters/test_circuit_breaker.py b/tests/solidworks_mcp/adapters/test_circuit_breaker.py index f737c986..110ae244 100644 --- a/tests/solidworks_mcp/adapters/test_circuit_breaker.py +++ b/tests/solidworks_mcp/adapters/test_circuit_breaker.py @@ -64,6 +64,12 @@ def cb_with_mock(): inner.add_ellipse = AsyncMock( return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data="ellipse") ) + inner.add_sketch_text = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) + inner.set_sketch_text = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data={}) + ) inner.sketch_linear_pattern = AsyncMock( return_value=AdapterResult(status=AdapterResultStatus.SUCCESS) ) @@ -174,18 +180,18 @@ async def test_circuit_breaker_add_spline(cb_with_mock): async def test_circuit_breaker_add_polygon(cb_with_mock): """add_polygon should route through _execute_with_circuit_breaker. Covers line 738.""" cb, inner = cb_with_mock - result = await cb.add_polygon(0.0, 0.0, 5.0, 6) + result = await cb.add_polygon(0.0, 0.0, 5.0, 6, 30.0) assert result.is_success - inner.add_polygon.assert_awaited_once() + inner.add_polygon.assert_awaited_once_with(0.0, 0.0, 5.0, 6, 30.0) @pytest.mark.asyncio async def test_circuit_breaker_add_ellipse(cb_with_mock): """add_ellipse should route through _execute_with_circuit_breaker. Covers line 757.""" cb, inner = cb_with_mock - result = await cb.add_ellipse(0.0, 0.0, 3.0, 1.5) + result = await cb.add_ellipse(0.0, 0.0, 3.0, 1.5, 15.0) assert result.is_success - inner.add_ellipse.assert_awaited_once() + inner.add_ellipse.assert_awaited_once_with(0.0, 0.0, 3.0, 1.5, 15.0) @pytest.mark.asyncio @@ -1137,3 +1143,23 @@ async def _run(name, operation, **kwargs): assert result.is_success assert inner.last_sketch_args == (None, (1.0, 2.0, 3.0)) assert recorded == {"plane": None, "face_point": (1.0, 2.0, 3.0)} + + +@pytest.mark.asyncio +async def test_circuit_breaker_add_sketch_text(cb_with_mock): + """add_sketch_text routes through the breaker with every argument.""" + cb, inner = cb_with_mock + result = await cb.add_sketch_text("abc", 1.0, 2.0, 4.0, [60.0, 2.0, 0.0]) + assert result.status == AdapterResultStatus.SUCCESS + inner.add_sketch_text.assert_awaited_once_with( + "abc", 1.0, 2.0, 4.0, [60.0, 2.0, 0.0] + ) + + +@pytest.mark.asyncio +async def test_circuit_breaker_set_sketch_text(cb_with_mock): + """set_sketch_text routes through the breaker.""" + cb, inner = 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") diff --git a/tests/solidworks_mcp/adapters/test_circuit_breaker_equations.py b/tests/solidworks_mcp/adapters/test_circuit_breaker_equations.py new file mode 100644 index 00000000..66ae54c6 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_circuit_breaker_equations.py @@ -0,0 +1,24 @@ +"""The equation methods pass through the circuit breaker.""" + +from __future__ import annotations + +import pytest + +from solidworks_mcp.adapters.circuit_breaker import CircuitBreakerAdapter +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter + + +@pytest.mark.asyncio +async def test_set_list_and_delete_pass_through() -> None: + inner = MockSolidWorksAdapter({}) + await inner.connect() + await inner.create_part() + breaker = CircuitBreakerAdapter(adapter=inner) + + added = await breaker.set_equation("Width", "60mm", "this") + listed = await breaker.list_equations() + deleted = await breaker.delete_equation("Width") + + assert added.data["value"] == 60.0 + assert [row["name"] for row in listed.data] == ["Width"] + assert deleted.data == {"deleted": "Width", "equations": []} diff --git a/tests/solidworks_mcp/adapters/test_connection_pool.py b/tests/solidworks_mcp/adapters/test_connection_pool.py index bd9ba217..c1d6be35 100644 --- a/tests/solidworks_mcp/adapters/test_connection_pool.py +++ b/tests/solidworks_mcp/adapters/test_connection_pool.py @@ -1773,8 +1773,10 @@ async def test_connection_pool_forwards_explicit_templates() -> None: _SKETCH_PASSTHROUGHS = [ ("add_spline", ([{"x": 0.0, "y": 0.0}, {"x": 1.0, "y": 2.0}],)), - ("add_polygon", (0.0, 0.0, 5.0, 6)), - ("add_ellipse", (0.0, 0.0, 10.0, 5.0)), + ("add_polygon", (0.0, 0.0, 5.0, 6, 30.0)), + ("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")), ("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_connection_pool_equations.py b/tests/solidworks_mcp/adapters/test_connection_pool_equations.py new file mode 100644 index 00000000..bf2ba9b6 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_connection_pool_equations.py @@ -0,0 +1,27 @@ +"""The equation methods pass through the connection pool.""" + +from __future__ import annotations + +import pytest + +from solidworks_mcp.adapters.connection_pool import ConnectionPoolAdapter +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter + + +@pytest.mark.asyncio +async def test_set_list_and_delete_pass_through() -> None: + pool = ConnectionPoolAdapter( + adapter_factory=lambda: MockSolidWorksAdapter({}), max_size=1 + ) + await pool.connect() + try: + assert (await pool.create_part()).is_success + added = await pool.set_equation("Width", "60mm") + listed = await pool.list_equations() + deleted = await pool.delete_equation("Width") + finally: + await pool.disconnect() + + assert added.data["action"] == "added" + assert [row["name"] for row in listed.data] == ["Width"] + assert deleted.data["equations"] == [] diff --git a/tests/solidworks_mcp/adapters/test_mock_adapter.py b/tests/solidworks_mcp/adapters/test_mock_adapter.py index 46d301a9..bd9d2a00 100644 --- a/tests/solidworks_mcp/adapters/test_mock_adapter.py +++ b/tests/solidworks_mcp/adapters/test_mock_adapter.py @@ -529,6 +529,44 @@ async def test_add_spline_error_when_too_few_points(self): assert result.status == AdapterResultStatus.ERROR assert "at least 2 points" in (result.error or "") + @pytest.mark.asyncio + async def test_add_sketch_text_gives_an_id_the_text_and_height(self): + """Mock add_sketch_text gives an id, the text and the height.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + + result = await adapter.add_sketch_text( + "abc", height=4.0, center_at=[60.0, 2.0, 0.0] + ) + + assert result.status == AdapterResultStatus.SUCCESS + 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_set_sketch_text_gives_the_text(self): + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + no_model = await adapter.set_sketch_text("Sketch12", "abc") + await adapter.create_part() + + result = await adapter.set_sketch_text("Sketch12", "abc") + + assert no_model.status == AdapterResultStatus.ERROR + assert result.data == {"sketch": "Sketch12", "before": [], "after": ["abc"]} + + @pytest.mark.asyncio + async def test_add_sketch_text_needs_a_sketch(self): + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + + result = await adapter.add_sketch_text("abc") + + assert result.status == AdapterResultStatus.ERROR + @pytest.mark.asyncio async def test_add_ellipse_success(self): """Mock add_ellipse returns an Ellipse_* id with an active sketch.""" diff --git a/tests/solidworks_mcp/adapters/test_mock_equations.py b/tests/solidworks_mcp/adapters/test_mock_equations.py new file mode 100644 index 00000000..16e1343e --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_mock_equations.py @@ -0,0 +1,99 @@ +"""The mock adapter's equations: values worked out, refusals as SolidWorks gives them. + +Spec: tools/equations. +""" + +from __future__ import annotations + +import pytest + +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.adapters.mock_equations import mock_value + +pytestmark = pytest.mark.asyncio + + +async def _mock() -> MockSolidWorksAdapter: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + return adapter + + +@pytest.mark.parametrize( + ("expression", "value"), + [ + ("60mm", 60.0), + ("2.5 in", 2.5), + ("-(3 + 1) * 2 / 4", -2.0), + ("+7", 7.0), + ('"Width" / 2', 30.0), + ('"Blank" + 1', None), + ("sin(30)", None), + ("1 / 0", None), + ("2 ** 3", None), + ("'text'", None), + ("not (", None), + ], +) +async def test_mock_value(expression: str, value: float | None) -> None: + assert mock_value(expression, {"width": 60.0, "blank": None}) == value + + +async def test_a_quoted_name_with_no_equation_is_a_lookup_error() -> None: + with pytest.raises(LookupError, match="Nope"): + mock_value('"Nope" * 2', {}) + + +async def test_a_global_variable_drives_a_dimension() -> None: + adapter = await _mock() + await adapter.set_equation("Width", "60mm") + driven = await adapter.set_equation("D1@Sketch1", '"Width" / 2') + changed = await adapter.set_equation("width", "80mm", ["Default"]) + + assert driven.data["kind"] == "dimension" + assert driven.data["value"] == 30.0 + assert changed.data["action"] == "changed" + assert changed.data["configurations"] == ["Default"] + assert adapter._dimensions["D1@Sketch1"] == 40.0 + listed = (await adapter.list_equations()).data + assert [(r["index"], r["name"], r["value"]) for r in listed] == [ + (0, "width", 80.0), + (1, "D1@Sketch1", 40.0), + ] + + +async def test_refusals() -> None: + adapter = await _mock() + refused = await adapter.set_equation("X", '"Nope" * 2') + no_dimension = await adapter.set_equation("D9@Nowhere", "1") + no_config = await adapter.set_equation("X", "1", ["Short"]) + no_equation = await adapter.delete_equation("Ghost") + + assert refused.error == ( + 'SolidWorks refused the equation "X" = "Nope" * 2; nothing was changed.' + ) + assert no_dimension.error.startswith("No dimension named 'D9@Nowhere'") + assert no_config.error.startswith("No configuration named 'Short'") + assert no_equation.error == "No equation named 'Ghost'; the model has none." + assert (await adapter.list_equations()).data == [] + + +async def test_delete_keeps_the_dimension_value() -> None: + adapter = await _mock() + await adapter.set_equation("D1@Sketch1", "12") + deleted = await adapter.delete_equation("D1@Sketch1") + + assert deleted.data == {"deleted": "D1@Sketch1", "equations": []} + assert adapter._dimensions["D1@Sketch1"] == 12.0 + + +async def test_no_model_is_an_error() -> None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + for call in ( + adapter.list_equations(), + adapter.set_equation("X", "1"), + adapter.delete_equation("X"), + ): + assert (await call).error == "No active model" diff --git a/tests/solidworks_mcp/tools/test_equations.py b/tests/solidworks_mcp/tools/test_equations.py new file mode 100644 index 00000000..242fe335 --- /dev/null +++ b/tests/solidworks_mcp/tools/test_equations.py @@ -0,0 +1,100 @@ +"""The equation tools, through the error boundary, on the mock adapter. + +Spec: tools/equations. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastmcp import FastMCP + +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.tools.equations import register_equation_tools + +pytestmark = pytest.mark.asyncio + + +async def _tools(adapter: Any = None) -> dict[str, Any]: + if adapter is None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + mcp = FastMCP("equations") + assert await register_equation_tools(mcp, adapter, {}) == 3 + return {t.name: t.fn for t in await mcp.list_tools()} + + +async def test_set_list_and_delete() -> None: + tools = await _tools() + added = await tools["set_equation"]({"name": " Width ", "expression": "60mm"}) + driven = await tools["set_equation"]( + {"name": "D1@Sketch1", "expression": '"Width" / 2', "configurations": "this"} + ) + listed = await tools["list_equations"]() + deleted = await tools["delete_equation"]({"name": "D1@Sketch1"}) + + assert added["message"] == "Added Width = 60mm" + assert driven["equation"]["value"] == 30.0 + assert listed["count"] == 2 + assert [row["kind"] for row in listed["equations"]] == [ + "global_variable", + "dimension", + ] + assert deleted["message"] == "Deleted equation D1@Sketch1" + assert deleted["equations"] == ["Width"] + + +async def test_a_refused_expression_is_equation_refused() -> None: + tools = await _tools() + result = await tools["set_equation"]({"name": "X", "expression": '"Nope" * 2'}) + assert result["status"] == "error" + assert result["error_type"] == "equation_refused" + assert "list_equations" in result["hint"] + + +@pytest.mark.parametrize( + ("call", "payload"), + [ + ("set_equation", {"name": "D9@Nowhere", "expression": "1"}), + ("delete_equation", {"name": "Ghost"}), + ], +) +async def test_unknown_names_are_invalid_input( + call: str, payload: dict[str, Any] +) -> None: + result = await (await _tools())[call](payload) + assert result["error_type"] == "invalid_input", result + assert "list_" in result["hint"] + + +@pytest.mark.parametrize( + "payload", + [ + {"name": " ", "expression": "1"}, + {"name": '"Width"', "expression": "1"}, + {"name": "A=B", "expression": "1"}, + {"name": "Width", "expression": " "}, + {"name": "Width", "expression": "1\n2"}, + {"name": "Width", "expression": "1", "configurations": []}, + ], +) +async def test_bad_inputs_are_refused_before_anything_runs( + payload: dict[str, Any], +) -> None: + result = await (await _tools())["set_equation"](payload) + assert result["status"] == "error" + assert result["error_type"] == "invalid_input" + + +async def test_a_blank_name_to_delete_is_refused() -> None: + result = await (await _tools())["delete_equation"]({"name": " "}) + assert result["error_type"] == "invalid_input" + + +async def test_no_open_document_is_no_active_document() -> None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + result = await (await _tools(adapter))["list_equations"]() + assert result["error_type"] == "no_active_document" diff --git a/tests/solidworks_mcp/tools/test_sketching.py b/tests/solidworks_mcp/tools/test_sketching.py index 949efe18..9b9ce854 100644 --- a/tests/solidworks_mcp/tools/test_sketching.py +++ b/tests/solidworks_mcp/tools/test_sketching.py @@ -871,6 +871,130 @@ async def test_sketching_error_branches_with_exceptions(mcp_server, mock_config) assert result["status"] == "error" +@pytest.mark.asyncio +async def test_add_polygon_passes_its_angle_on(mcp_server, mock_config): + """The angle reaches the adapter and comes back in the reply (0 by default).""" + adapter = _SketchAdapterStub() + adapter.add_polygon = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data="P_1") + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "add_polygon") + + turned = await tool(input_data={"radius": 6.5, "sides": 6, "angle": 30}) + plain = await tool(input_data={"radius": 6.5, "sides": 6}) + + assert adapter.add_polygon.await_args_list[0].args == (0.0, 0.0, 6.5, 6, 30.0) + assert turned["polygon"]["angle"] == 30.0 + assert plain["polygon"]["angle"] == 0.0 + + +@pytest.mark.asyncio +async def test_add_sketch_text_passes_everything_on(mcp_server, mock_config): + """Every input reaches the adapter; the reply carries what SolidWorks shows.""" + adapter = _SketchAdapterStub() + adapter.add_sketch_text = AsyncMock( + return_value=AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"id": "Text_1", "text": "size 13.00 mm", "height": 4.0}, + ) + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "add_sketch_text") + + reply = await tool( + input_data={ + "text": 'size $PRP:"Size" mm', + "height": 4, + "center_at": [60, 2, 0], + } + ) + + assert adapter.add_sketch_text.await_args.args == ( + 'size $PRP:"Size" mm', + 0.0, + 0.0, + 4.0, + [60.0, 2.0, 0.0], + ) + assert reply["status"] == "success" + assert reply["sketch_text"] == { + "id": "Text_1", + "text": "size 13.00 mm", + "height": 4.0, + "center_at": [60.0, 2.0, 0.0], + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "bad", + [{"text": ""}, {"text": "a", "height": 0}, {"text": "a", "center_at": [1, 2]}], +) +async def test_add_sketch_text_rejects_bad_input(mcp_server, mock_config, bad): + adapter = _SketchAdapterStub() + adapter.add_sketch_text = AsyncMock() + await register_sketching_tools(mcp_server, adapter, mock_config) + + reply = await (await _tool(mcp_server, "add_sketch_text"))(input_data=bad) + + assert reply["error_type"] == "invalid_input" + adapter.add_sketch_text.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_add_sketch_text_failure_is_an_error(mcp_server, mock_config): + adapter = _SketchAdapterStub() + adapter.add_sketch_text = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.ERROR, error="no sketch") + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + + reply = await (await _tool(mcp_server, "add_sketch_text"))(input_data={"text": "a"}) + + assert reply["status"] == "error" + assert "no sketch" in reply["message"] + + +@pytest.mark.asyncio +async def test_set_sketch_text_gives_before_and_after(mcp_server, mock_config): + adapter = _SketchAdapterStub() + adapter.set_sketch_text = AsyncMock( + return_value=AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"sketch": "Sketch12", "before": ["13.00"], "after": ["19.00"]}, + ) + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "set_sketch_text") + + reply = await tool(input_data={"sketch_name": "Sketch12", "text": "x"}) + bad = await tool(input_data={"sketch_name": "", "text": "x"}) + + adapter.set_sketch_text.assert_awaited_once_with("Sketch12", "x") + assert reply["sketch_text"]["after"] == ["19.00"] + assert "Sketch12 now reads ['19.00']" in reply["message"] + assert bad["error_type"] == "invalid_input" + + +@pytest.mark.asyncio +async def test_add_ellipse_passes_its_angle_on(mcp_server, mock_config): + """The angle reaches the adapter and comes back in the reply (0 by default).""" + adapter = _SketchAdapterStub() + adapter.add_ellipse = AsyncMock( + return_value=AdapterResult(status=AdapterResultStatus.SUCCESS, data="E_1") + ) + await register_sketching_tools(mcp_server, adapter, mock_config) + tool = await _tool(mcp_server, "add_ellipse") + + turned = await tool(input_data={"major_axis": 13, "minor_axis": 2.6, "angle": 15}) + plain = await tool(input_data={"major_axis": 13, "minor_axis": 2.6}) + + assert adapter.add_ellipse.await_args_list[0].args == (0.0, 0.0, 13, 2.6, 15) + assert turned["ellipse"]["angle"] == 15 + assert plain["ellipse"]["angle"] == 0.0 + + @pytest.mark.asyncio async def test_sketching_tool_error_return_branches(mcp_server, mock_config): """Test sketching tool error return branches."""