diff --git a/CHANGELOG.md b/CHANGELOG.md index b15410b6..a141c653 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Colours** (queue item 36): `set_appearance` colours the whole part, one + feature, one body or the face at a point (`[r, g, b]` or `#rrggbb`, with + transparency), or with `reset` removes a level's own colour; + `get_appearance` reads the colour that shows and the level it comes from. + A face's colour shows over its feature's, a feature's over its body's, a + body's over the part's. Each colour is read back from SolidWorks, which + takes it as an array of doubles: a plain list was misread. +- **Reference and analysis extras** (queue item 39): + `create_coordinate_system` at a point, axes along the model's (its + transform read back); `create_center_of_mass_point`; + `create_bounding_box` with the stock size; `get_section_properties`, a + planar face's area, centroid and second moments of area. 171 tools in + all. Beta until the live demo; the live tests pass on SolidWorks 2026. - **Multi-body tools** (queue item 35): `list_bodies` names a part's solid bodies with each one's volume and bounding box; `combine_bodies` adds, subtracts or keeps the common volume of bodies (a mould core: a block @@ -91,6 +104,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A Bandit alert on the body tools.** The body operation's reply-fields + callback was named `extra`, which Bandit's rule B610 reads as Django's + `QuerySet.extra` (an SQL risk). There is no SQL; the callback is now + `own_fields`. - **Tools after `delete_feature` see the part again.** `list_features` (which `delete_feature` runs) and `get_selected_entities` took over SolidWorks's active document without flagging its methods, so the next tool read diff --git a/README.md b/README.md index d67b0672..c51ab390 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 165 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 171 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. [![115 MCP tools by support level (the 8 deprecated ones not counted), and how much of the core SolidWorks COM API they reach](docs/assets/progress/progress.svg)](https://andrewbartels1.com/SolidworksMCP-python/progress/) @@ -367,7 +367,7 @@ It works only with the circuit-breaker adapter wrapper (the default for real Sol ### A shorter tool list -All 165 tools cost about 69,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 171 tools cost about 72,000 tokens a turn. `SOLIDWORKS_MCP_TOOL_MODE=search` lists four instead (about 900 tokens); `SOLIDWORKS_MCP_TOOLSETS=core,drawing` lists only those groups. See [Choose which tools a client sees](https://andrewbartels1.com/SolidworksMCP-python/getting-started/installation/#4-choose-which-tools-a-client-sees). ## Teach your agent the workflow diff --git a/docs/assets/demos/appearance-and-reference/test_colours_on_a_block-motion.gif b/docs/assets/demos/appearance-and-reference/test_colours_on_a_block-motion.gif new file mode 100644 index 00000000..e7af47d1 Binary files /dev/null and b/docs/assets/demos/appearance-and-reference/test_colours_on_a_block-motion.gif differ diff --git a/docs/assets/demos/appearance-and-reference/test_reference_extras_on_a_block-motion.gif b/docs/assets/demos/appearance-and-reference/test_reference_extras_on_a_block-motion.gif new file mode 100644 index 00000000..361a04ac Binary files /dev/null and b/docs/assets/demos/appearance-and-reference/test_reference_extras_on_a_block-motion.gif differ diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index f9b15443..7d7986a0 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,9 +1,9 @@ { "tools": { - "total": 165, + "total": 171, "by_level": { "stable": 149, - "beta": 8, + "beta": 14, "experimental": 0, "planned": 0, "deprecated": 8 @@ -272,7 +272,7 @@ "name": "combine_bodies", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "Combine bodies of the active part: add them, subtract tool bodies from a main body, or keep their common volume." }, { @@ -310,6 +310,20 @@ "reason": "", "summary": "Start a sheet-metal part: a base flange from a sketch, with its thickness, bend radius and K-factor." }, + { + "name": "create_bounding_box", + "family": "reference_extras", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Add SolidWorks's Bounding Box feature around the active part's bodies and give the stock size." + }, + { + "name": "create_center_of_mass_point", + "family": "reference_extras", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Add SolidWorks's Center of Mass point to the active part, at its centre of mass." + }, { "name": "create_configuration", "family": "file_management", @@ -317,6 +331,13 @@ "reason": "", "summary": "Add a configuration to the active part or assembly, e.g. a long and a short version of one part." }, + { + "name": "create_coordinate_system", + "family": "reference_extras", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Add a coordinate system with its origin at a point, axes along the model's." + }, { "name": "create_cut_extrude", "family": "modeling", @@ -468,7 +489,7 @@ "name": "delete_bodies", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "Delete bodies from the active part, or with keep=true keep only the named ones." }, { @@ -660,6 +681,13 @@ "reason": "", "summary": "Look up a SolidWorks API enum's members and their integer values." }, + { + "name": "get_appearance", + "family": "appearance", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Read the colour the active part, a feature, a body or the face at a point shows, and where it comes from." + }, { "name": "get_custom_properties", "family": "engineering_data", @@ -702,6 +730,13 @@ "reason": "", "summary": "Report the active document's title, path, type, configuration, unsaved changes, feature count, rebuild status and file details." }, + { + "name": "get_section_properties", + "family": "reference_extras", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Read the area, centroid and second moments of area of a planar face, picked by a point on it." + }, { "name": "get_selected_entities", "family": "file_management", @@ -741,7 +776,7 @@ "name": "list_bodies", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "List the active part's solid bodies by name, with each one's volume and bounding box." }, { @@ -853,7 +888,7 @@ "name": "move_copy_body", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "Move bodies of the active part by a translation and a rotation, or copy them up to 50 times." }, { @@ -965,7 +1000,7 @@ "name": "scale_body", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "Scale bodies of the active part, uniformly or per axis, about their centroid or the origin." }, { @@ -989,6 +1024,13 @@ "reason": "", "summary": "Select a feature, sketch, plane or component by name in the active document." }, + { + "name": "set_appearance", + "family": "appearance", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Colour the active part, one feature, one body or the face at a point, or remove a colour." + }, { "name": "set_component_state", "family": "modeling", @@ -1126,7 +1168,7 @@ "name": "split_body", "family": "bodies", "level": "beta", - "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "reason": "new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.", "summary": "Split the active part's bodies with a plane or a sketch, keeping every piece in the part." }, { @@ -1169,11 +1211,11 @@ "com": { "type_library": "83A33D31-27C5-11CE-BFD4-00400513BB57x0x34x0", "core": { - "covered": 295, + "covered": 314, "total": 2838 }, "api": { - "covered": 338, + "covered": 350, "total": 5985 }, "interfaces": [ @@ -1261,7 +1303,9 @@ "GetUserPreferenceStringValue", "GetUserPreferenceToggle", "GraphicsRedraw2", + "Insert3DSketch", "InsertAxis2", + "InsertCoordinateSystem", "InsertDatumTag2", "InsertFeatureShell", "InsertGtol", @@ -1310,13 +1354,16 @@ "CustomPropertyManager", "DeleteSelection2", "GetAnnotations", + "GetCoordinateSystemTransformByName", "GetMassProperties", + "GetSectionProperties2", "GetUserPreferenceInteger", "GetUserPreferenceToggle", "GetWhatsWrong", "GetWhatsWrongCount", "InsertBomTable4", "IsExploded", + "RemoveMaterialProperty", "SaveAs", "SaveAs2", "SaveAs3", @@ -1416,11 +1463,14 @@ "GetFeatureCount", "GetFlatPatternFolder", "HoleWizard5", + "InsertCenterOfMass", "InsertCombineFeature", + "InsertCoordinateSystem", "InsertCosmeticThread3", "InsertCutSwept5", "InsertDeleteBody2", "InsertFeatureChamfer", + "InsertGlobalBoundingBox", "InsertMirrorFeature", "InsertMoveCopyBody2", "InsertMultiFaceDraft", @@ -1457,6 +1507,7 @@ "CreateSketchSlot", "CreateSpline2", "CreateTangentArc", + "Insert3DSketch", "InsertSketch", "SketchExtend", "SketchOffset2", @@ -1483,11 +1534,13 @@ "FeatureByName", "FirstFeature", "GetBodies2", + "GetBody", "GetBox", "GetChildren", "GetConfigurationNames", "GetConstrainedStatus", "GetID", + "GetMaterialPropertyValues2", "GetModelDoc2", "GetPathName", "GetSuppression2", @@ -1496,9 +1549,12 @@ "IsEnvelope", "IsFixed", "IsSuppressed", + "RemoveMaterialProperty", + "RemoveMaterialProperty2", "Select", "Select2", "Select4", + "SetMaterialPropertyValues2", "SetSuppression2" ], "total": 147 @@ -1506,6 +1562,7 @@ { "name": "IFeature", "covered": [ + "GetBody", "GetBox", "GetChildren", "GetDefinition", @@ -1514,6 +1571,7 @@ "GetFirstDisplayDimension", "GetFirstSubFeature", "GetID", + "GetMaterialPropertyValues2", "GetNameForSelection", "GetNextDisplayDimension", "GetNextFeature", @@ -1525,8 +1583,11 @@ "IsSuppressed2", "ModifyDefinition", "Parameter", + "RemoveMaterialProperty", + "RemoveMaterialProperty2", "Select", "Select2", + "SetMaterialPropertyValues2", "SetSuppression2" ], "total": 115 diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index a64f504e..fd1d494e 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,12 +21,12 @@ -MCP tools: 157 +MCP tools: 163 100% work on SolidWorks today - - + + @@ -35,21 +35,21 @@ stable 149 -beta 8 - -experimental 0 - -planned 0 - -deprecated 8 +beta 14 + +experimental 0 + +planned 0 + +deprecated 8 Core SolidWorks COM API (12 interfaces) -295 of 2,838 methods · 10.4% +314 of 2,838 methods · 11.1% - - - + + + -Whole API: 338 of 5,985 method names (5.6%), counted by a text scan of the adapters. +Whole API: 350 of 5,985 method names (5.8%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index e6f8f0fe..fbdd0563 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -39,13 +39,16 @@ check_sketch_fully_definedsketchingstableCheck whether a sketch is fully defined, under-defined or over-defined. classify_feature_treefile_managementstableClassify the active model's kind (part, sheet metal, assembly, drawing and so on) from its feature tree, and suggest how to work on it. close_modelmodelingstableClose the active document, saving it first only if asked. -combine_bodiesbodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Combine bodies of the active part: add them, subtract tool bodies from a main body, or keep their common volume. +combine_bodiesbodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.Combine bodies of the active part: add them, subtract tool bodies from a main body, or keep their common volume. compare_drawing_versionsdrawing_analysisstableCompare two drawing files on disk: whether they are byte-identical, and how their sizes differ. compare_templatestemplate_managementstableCompare two template files on disk: whether they are byte-identical, and how their sizes differ. create_assemblymodelingstableCreate a new, empty assembly document and make it active, ready for `insert_component`. create_axismodelingstableAdd a reference axis along the model's x, y or z direction, through the origin. create_base_flangemodelingstableStart a sheet-metal part: a base flange from a sketch, with its thickness, bend radius and K-factor. +create_bounding_boxreference_extrasbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Add SolidWorks's Bounding Box feature around the active part's bodies and give the stock size. +create_center_of_mass_pointreference_extrasbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Add SolidWorks's Center of Mass point to the active part, at its centre of mass. create_configurationfile_managementstableAdd a configuration to the active part or assembly, e.g. a long and a short version of one part. +create_coordinate_systemreference_extrasbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Add a coordinate system with its origin at a point, axes along the model's. create_cut_extrudemodelingstableCut material from the active part with a closed sketch profile: holes, slots, windows. create_cut_sweepmodelingbeta
new: checked live once (a thread cut on a rod), not yet in wide use.Sweep a closed profile along a path to remove material (Insert > Cut > Sweep). create_detail_viewdrawingstableMagnify a circular area of a drawing view as a detail view, at a scale. @@ -67,7 +70,7 @@ create_sketched_bendmodelingstableBend a sheet-metal part along a line sketched on one of its faces. create_sweepmodelingstableSweep a closed profile along a path to add material (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_bodiesbodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Delete bodies from the active part, or with keep=true keep only the named ones. +delete_bodiesbodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.Delete bodies from the active part, or with keep=true keep only the named ones. 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. @@ -95,18 +98,20 @@ generate_vba_part_modelingvba_generationstableWrite a VBA macro for a shell or a fillet on the active part. generate_vba_revolvevba_generationstableWrite a VBA macro that revolves the selected sketch, with both-direction and thin-wall options. get_api_enumdocs_discoverystableLook up a SolidWorks API enum's members and their integer values. +get_appearanceappearancebeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Read the colour the active part, a feature, a body or the face at a point shows, and where it comes from. get_custom_propertiesengineering_datastableRead the active document's custom properties, such as PartNo, Description or Revision. get_dimensionmodelingstableRead one dimension of the active model by its full name, e.g. "D1@Sketch1". get_file_propertiesfile_managementdeprecated
use `get_model_info`.Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes. get_mass_propertiesanalysisstableMeasure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. get_materialengineering_datastableReport the active part's material with its strength and stiffness, or any library material's. get_model_infofile_managementstableReport the active document's title, path, type, configuration, unsaved changes, feature count, rebuild status and file details. +get_section_propertiesreference_extrasbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Read the area, centroid and second moments of area of a planar face, picked by a point on it. get_selected_entitiesfile_managementstableDescribe the faces, edges and vertices selected in the SolidWorks window right now. insert_bom_tabledrawing_automationstableInsert a bill-of-materials table for an assembly view on the active drawing. insert_componentmodelingstableInsert a part or sub-assembly file into the active assembly at a position in mm. insert_model_dimensionsdrawing_automationstableBring the model's dimensions into the active drawing's views, each dimension shown once. list_available_materialsengineering_datastableList the materials in the installed SolidWorks material libraries. -list_bodiesbodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.List the active part's solid bodies by name, with each one's volume and bounding box. +list_bodiesbodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.List the active part's solid bodies by name, with each one's volume and bounding box. 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. @@ -122,7 +127,7 @@ measure_entitiesengineering_datastableMeasure faces, edges or vertices of the active model with SolidWorks' Measure tool. mirror_componentsassemblystableMirror assembly components about a plane, as instances of the same parts. mirror_featuremodelingstableMirror solid bodies or features of the active part about a plane. -move_copy_bodybodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Move bodies of the active part by a translation and a rotation, or copy them up to 50 times. +move_copy_bodybodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.Move bodies of the active part by a translation and a rotation, or copy them up to 50 times. open_modelmodelingstableOpen a part, assembly or drawing from disk and make it the active document. pack_and_go_assemblyfile_managementstableCopy an assembly and every file it uses into one folder that opens on its own. pattern_circularmodelingstableRepeat features of the active part around an axis, e.g. a ring of bosses or ribs. @@ -138,10 +143,11 @@ save_body_as_partfile_managementstableSave one solid body of the active multibody part as a new part file (Insert > Features > Save Bodies). save_filefile_managementstableSave the active part, assembly or drawing, to its own path or to a new path in its own format. save_partfile_managementdeprecated
use `save_file`.Save the active part in place, or as a new .sldprt with the target path checked first. -scale_bodybodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Scale bodies of the active part, uniformly or per axis, about their centroid or the origin. +scale_bodybodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.Scale bodies of the active part, uniformly or per axis, about their centroid or the origin. search_solidworks_api_helpdocs_discoverystableSearch SolidWorks API interface and member names by keyword. select_face_edgesmodelingstableSelect every edge of one face of the active part, ready for `add_fillet` or `add_chamfer` with no edge names. select_featuremodelingstableSelect a feature, sketch, plane or component by name in the active document. +set_appearanceappearancebeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Colour the active part, one feature, one body or the face at a point, or remove a colour. set_component_statemodelingstableFix or float an assembly component, make a sub-assembly flexible, or hide it or make it transparent. set_construction_geometrysketchingstableMake sketch entities construction geometry, or normal again, by id. set_custom_propertyengineering_datastableCreate or overwrite one text custom property on the active document, e.g. PartNo or DrawnBy. @@ -161,7 +167,7 @@ sketch_offsetsketchingstableOffset sketch entities by a distance in mm, outward or inward, e.g. for a wall or a clearance. sketch_trimsketchingstableTrim away the piece of a sketch entity at a point, back to where it meets others. sketch_tutorial_simple_holesketchingdeprecated
no replacement.Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch. -split_bodybodiesbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Split the active part's bodies with a plane or a sketch, keeping every piece in the part. +split_bodybodiesbeta
new: passed its live demo (boolean logic on a cube and a sphere), not yet in wide use.Split the active part's bodies with a plane or a sketch, keeping every piece in the part. suppress_featuremodelingstableSuppress or unsuppress a feature of the active model; suppressed features stay in the tree but are not built. undomodelingstableUndo the last operations in the active model (Edit > Undo). update_sheet_formatdrawingstableChange the active drawing sheet's format and paper size, keeping every view. @@ -176,16 +182,16 @@ 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
-IModelDoc289758
11.7%AddConfiguration2, AddDiameterDimension2, AddDimension, AddDimension2, AddHorizontalDimension2, AddRadialDimension2, AddRelation, AddVerticalDimension2, ClearSelection2, Create3PointArc, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreateTangentArc, DeleteConfiguration2, EditDelete, EditRebuild3, EditSketch, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetEquationMgr, GetFeatureCount, GetLineCount, GetMassProperties, GetModelViewNames, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertHelix, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertScale, InsertSketch, InsertSketchForEdgeFlange, InsertSketchText, IsExploded, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Scale, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchTrim, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
-IModelDocExtension19337
5.6%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetMassProperties, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, IsExploded, SaveAs, SaveAs2, SaveAs3, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
+IModelDoc291758
12.0%AddConfiguration2, AddDiameterDimension2, AddDimension, AddDimension2, AddHorizontalDimension2, AddRadialDimension2, AddRelation, AddVerticalDimension2, ClearSelection2, Create3PointArc, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreateTangentArc, DeleteConfiguration2, EditDelete, EditRebuild3, EditSketch, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetEquationMgr, GetFeatureCount, GetLineCount, GetMassProperties, GetModelViewNames, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, Insert3DSketch, InsertAxis2, InsertCoordinateSystem, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertHelix, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertScale, InsertSketch, InsertSketchForEdgeFlange, InsertSketchText, IsExploded, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Scale, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchTrim, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
+IModelDocExtension22337
6.5%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetCoordinateSystemTransformByName, GetMassProperties, GetSectionProperties2, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, IsExploded, RemoveMaterialProperty, SaveAs, SaveAs2, SaveAs3, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
IPartDoc16167
9.6%CreateExplodedView, ExportToDWG2, FeatureByName, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureRevolve2, FirstFeature, GetBodies2, GetExplodedViewNames, GetMaterialPropertyName2, GetPartBox, InsertCombineFeature, InsertMirrorFeature, SetMaterialPropertyName2, ShowExploded
IAssemblyDoc19198
9.6%AddComponent4, AddComponent5, AddMate5, AutoExplode, CompConfigProperties5, CreateExplodedView, FeatureByName, FixComponent, GetBox, GetComponentByName, GetComponentCount, GetComponents, GetExplodedViewNames, MirrorComponents3, ReplaceComponents2, SetComponentTransparent, ShowExploded, ShowExploded2, UnfixComponent
IDrawingDoc18272
6.6%ActivateView, AutoBalloon5, AutoDimension, Create1stAngleViews2, Create3rdAngleViews2, CreateAutoBalloonOptions, CreateDetailViewAt4, CreateDrawViewFromModelView3, CreateSectionViewAt5, EditSheet, EditSketch, EditTemplate, FeatureByName, GetCurrentSheet, GetFirstView, GetViews, InsertModelAnnotations3, SetupSheet5
-IFeatureManager34268
12.7%CreateCustomBendAllowance, CreateDefinition, CreateFeature, CreateSaveBodyFeature, FeatureCircularPattern5, FeatureCut3, FeatureCut4, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureFillet3, FeatureLinearPattern5, FeatureRevolve2, GetFeatureCount, GetFlatPatternFolder, HoleWizard5, InsertCombineFeature, InsertCosmeticThread3, InsertCutSwept5, InsertDeleteBody2, InsertFeatureChamfer, InsertMirrorFeature, InsertMoveCopyBody2, InsertMultiFaceDraft, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRefPlane, InsertReferencePoint, InsertRib, InsertScale, InsertSheetMetalBaseFlange2, InsertSheetMetalEdgeFlange2, PostSplitBody2, PreSplitBody2
-ISketchManager2383
27.7%Create3PointArc, CreateArc, CreateCenterLine, CreateCenterRectangle, CreateChamfer, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateCornerRectangle, CreateEllipse, CreateFillet, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreatePolygon, CreateSketchSlot, CreateSpline2, CreateTangentArc, InsertSketch, SketchExtend, SketchOffset2, SketchTrim, SketchUseEdge, SketchUseEdge3
+IFeatureManager37268
13.8%CreateCustomBendAllowance, CreateDefinition, CreateFeature, CreateSaveBodyFeature, FeatureCircularPattern5, FeatureCut3, FeatureCut4, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureFillet3, FeatureLinearPattern5, FeatureRevolve2, GetFeatureCount, GetFlatPatternFolder, HoleWizard5, InsertCenterOfMass, InsertCombineFeature, InsertCoordinateSystem, InsertCosmeticThread3, InsertCutSwept5, InsertDeleteBody2, InsertFeatureChamfer, InsertGlobalBoundingBox, InsertMirrorFeature, InsertMoveCopyBody2, InsertMultiFaceDraft, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRefPlane, InsertReferencePoint, InsertRib, InsertScale, InsertSheetMetalBaseFlange2, InsertSheetMetalEdgeFlange2, PostSplitBody2, PreSplitBody2
+ISketchManager2483
28.9%Create3PointArc, CreateArc, CreateCenterLine, CreateCenterRectangle, CreateChamfer, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateCornerRectangle, CreateEllipse, CreateFillet, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, CreatePolygon, CreateSketchSlot, CreateSpline2, CreateTangentArc, Insert3DSketch, InsertSketch, SketchExtend, SketchOffset2, SketchTrim, SketchUseEdge, SketchUseEdge3
ISelectionMgr461
6.6%CreateSelectData, GetSelectedObject6, GetSelectedObjectCount2, GetSelectedObjectType3
-IComponent221147
14.3%CustomPropertyManager, FeatureByName, FirstFeature, GetBodies2, GetBox, GetChildren, GetConfigurationNames, GetConstrainedStatus, 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
+IComponent226147
17.7%CustomPropertyManager, FeatureByName, FirstFeature, GetBodies2, GetBody, GetBox, GetChildren, GetConfigurationNames, GetConstrainedStatus, GetID, GetMaterialPropertyValues2, GetModelDoc2, GetPathName, GetSuppression2, GetType, GetXform, IsEnvelope, IsFixed, IsSuppressed, RemoveMaterialProperty, RemoveMaterialProperty2, Select, Select2, Select4, SetMaterialPropertyValues2, SetSuppression2
+IFeature27115
23.5%GetBody, GetBox, GetChildren, GetDefinition, GetErrorCode2, GetFaces, GetFirstDisplayDimension, GetFirstSubFeature, GetID, GetMaterialPropertyValues2, GetNameForSelection, GetNextDisplayDimension, GetNextFeature, GetNextSubFeature, GetParents, GetSpecificFeature2, GetTypeName2, IsSuppressed, IsSuppressed2, ModifyDefinition, Parameter, RemoveMaterialProperty, RemoveMaterialProperty2, Select, Select2, SetMaterialPropertyValues2, SetSuppression2
ISketch7102
6.9%AutoDimension, GetConstrainedStatus, GetLineCount, GetSketchContours, GetSketchPoints2, GetSketchSegments, GetSketchTextSegments
diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index b70f936b..d1721877 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` | 165 | 271 KB | 69,286 | 100% | -| `core` | `list` | 124 | 193 KB | 49,382 | 71% | -| `drawing` | `list` | 22 | 39 KB | 10,074 | 15% | +| `all` | `list` | 171 | 279 KB | 71,512 | 100% | +| `core` | `list` | 130 | 202 KB | 51,608 | 72% | +| `drawing` | `list` | 22 | 39 KB | 10,074 | 14% | | `automation` | `list` | 3 | 6 KB | 1,556 | 2% | | `vba` | `list` | 10 | 17 KB | 4,356 | 6% | -| `docs` | `list` | 6 | 15 KB | 3,916 | 6% | -| `core,drawing` | `list` | 146 | 232 KB | 59,457 | 86% | +| `docs` | `list` | 6 | 15 KB | 3,916 | 5% | +| `core,drawing` | `list` | 152 | 241 KB | 61,682 | 86% | | `all` | `search` | 4 | 4 KB | 908 | 1% | | `core` | `search` | 4 | 4 KB | 908 | 1% | diff --git a/docs/demos.md b/docs/demos.md index 7cde1fc1..b75bef30 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -1162,6 +1162,73 @@ material orange. 6. `combine_bodies` subtract on each pair, `move_copy_body` the sphere's piece back by `[-100, 0, 0]` 7. `verify_model({"volume_mm3": 80755.2, "solid_body_count": 2})` +## Colours and reference geometry {#appearance} + +Source: [`tests/live/test_live_sw_appearance_and_reference.py`](https://github.com/andrewbartels1/SolidworksMCP-python/blob/main/tests/live/test_live_sw_appearance_and_reference.py). + +### Colours on a block {#colours} + +![A 40 x 10 x 40 mm block coloured green by its feature, its top face blue, its body orange with the feature's green still showing, a refusal of two targets, and the top face's own colour removed](assets/demos/appearance-and-reference/test_colours_on_a_block-motion.gif) + +> *Example prompt:* Colour this block green, make its top face blue, then +> take the blue off again. + +**What it shows.** `set_appearance` colours a feature, a face, a body or the +whole part, and `get_appearance` reads back the colour that actually shows +on a face, with the level it comes from. SolidWorks shows the most specific +colour: a face's own colour over its feature's, a feature's over its +body's: + +| Step | Tools | Expected | Measured | +| --- | --- | --- | --- | +| The feature green | `set_appearance` | `#1fcc33` on Boss-Extrude1 | `#1fcc33` | +| The top face blue | `set_appearance` | `#194cf2` on the face at (0, 10, 0) | `#194cf2` | +| The body orange | `set_appearance` | `#f28c1a`; the feature's green still shows | `#f28c1a`; sides green | +| What shows | `get_appearance` | top: blue (face); side: green (feature) | top `#194cf2` (face); side `#1fcc33` (feature) | +| A feature and a face at once | `set_appearance` | refused, nothing changed | `invalid_input`: "Give one target" | +| The top face's colour removed | `set_appearance` | the feature's green shows | `#1fcc33` (feature) | + +Two targets are refused **on purpose**. + +**Tool calls** + +1. A 40 x 40 mm square on the Top Plane extruded 10 mm, then `list_bodies` +2. `set_appearance({"feature": "Boss-Extrude1", "color": "#1fcc33"})` +3. `set_appearance({"face_point": [0, 10, 0], "color": [25, 76, 242]})` +4. `set_appearance({"body": "Boss-Extrude1", "color": "#f28c1a"})` +5. `get_appearance({"face_point": [0, 10, 0]})`, `get_appearance({"face_point": [20, 5, 0]})` +6. `set_appearance` with a feature and a face, refused on purpose +7. `set_appearance({"face_point": [0, 10, 0], "reset": true})` + +### Reference extras on a block {#reference-extras} + +![The same block: its top face's section properties, a coordinate system at a corner, a Center of Mass point, a second one refused, and a bounding box](assets/demos/appearance-and-reference/test_reference_extras_on_a_block-motion.gif) + +> *Example prompt:* Give me the top face's section properties, put a +> coordinate system on the corner, and add the centre of mass and a bounding +> box. + +**What it shows.** Section properties of a face, and three pieces of +reference geometry, each checked against the block's own numbers: + +| Step | Tools | Expected | Measured | +| --- | --- | --- | --- | +| The top face's section | `get_section_properties` | 1,600 mm², centroid (0, 10, 0), Ixx = 40⁴/12 = 213,333.3 mm⁴ | 1,600 mm², (0, 10, 0), 213,333.33 mm⁴ | +| A coordinate system at the corner | `create_coordinate_system` | origin (20, 10, 20), axes along x, y, z | (20, 10, 20); x, y, z | +| The Center of Mass point | `create_center_of_mass_point` | (0, 5, 0) | (0, 5, 0) | +| A second Center of Mass point | `create_center_of_mass_point` | refused: a part has one at most | `invalid_input` | +| The bounding box | `create_bounding_box` | 40 x 10 x 40 mm | 40 x 10 x 40 mm | + +The second Center of Mass point is refused **on purpose**. + +**Tool calls** + +1. A 40 x 40 mm square on the Top Plane extruded 10 mm +2. `get_section_properties({"face_point": [0, 10, 0]})` +3. `create_coordinate_system({"origin": [20, 10, 20]})` +4. `create_center_of_mass_point()`, twice; the second is refused on purpose +5. `create_bounding_box()` + ## Run a demo yourself The demos need Windows, SolidWorks open and idle, and the project's `.venv`. diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 7c1b4fc0..3348795d 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -80,7 +80,7 @@ Every tool's name, description and inputs are sent to the model on every turn, s | Toolset | Tools | | --- | --- | -| `core` | Parts and assemblies: modelling, equations, multi-body tools, sketching, files, measuring and checking, materials and properties, export, the circuit-breaker reset | +| `core` | Parts and assemblies: modelling, equations, multi-body tools, colours, reference geometry, sketching, files, measuring and checking, materials and properties, export, the circuit-breaker reset | | `drawing` | Drawings: views, dimensions, the title block and sheet, the drawing package and check | | `automation` | Macros, recording and batch automation | | `vba` | The VBA code generators | diff --git a/docs/index.md b/docs/index.md index c381c03f..855acf76 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. -🚀 **165 Tools** | 🤖 **Agent-Ready Workflows** | ⚡ **Automatic COM/VBA Routing** | 🧪 **Schema-Validated Prompt Runs** +🚀 **171 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 -- 165 tools across modeling, multi-body parts, assemblies, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 171 tools across modeling, multi-body parts, colours, reference geometry, assemblies, 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 0d10c378..3263756b 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -36,10 +36,12 @@ ## Tool Catalog -- [Tool Catalog — All 165 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **165 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 171 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **171 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. - [Body Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/bodies/): See, combine, split, move, copy, delete and scale the solid bodies of a part. +- [Appearance Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/appearance/): Colour the part, a feature, a body or one face, and read a colour back. +- [Reference and Analysis Extras](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/reference-extras/): A coordinate system at a point, the centre-of-mass point, the bounding box, and a face's section properties. - [Assembly Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/assembly/): Explode an assembly, repeat and mirror its components, and swap one for another file, the edits between inserting parts and drawing the assembly. - [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. diff --git a/docs/user-guide/tool-catalog/appearance.md b/docs/user-guide/tool-catalog/appearance.md new file mode 100644 index 00000000..dcb1968d --- /dev/null +++ b/docs/user-guide/tool-catalog/appearance.md @@ -0,0 +1,62 @@ +# Appearance Tools + +Colour the part, a feature, a body or one face, and read a colour back. + +> **Prerequisite:** an open part. + +**Total tools in this category: 2** + +A colour shows from the nearest level that has one: a face's colour over its feature's, a feature's over its body's, a body's over the part's. Every part has a colour; a feature, body or face has one only once it is given one. `set_appearance` reads the colour back from SolidWorks after setting it, and `get_appearance` says which level the visible colour comes from. + +A target is one of `feature` (its name in the tree), `body` (as `list_bodies` names it) or `face_point` (`[x, y, z]` mm, a point on the face); none means the whole part. Giving two targets is refused. + +--- + +### `set_appearance` + +Colour the active part, one feature, one body or the face at a point, or remove a colour. + +`color` is `[r, g, b]`, each 0-255, or `#rrggbb`. `reset: true` removes a feature's, body's or face's own colour so the colour above it shows again; the reply's `showing` gives that colour and its level. The part's colour can't be reset, only changed. The geometry is never changed. + +**Prerequisite:** Active part. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `feature` | `str` | — | | A feature by its name in the tree, e.g. 'Boss-Extrude1' | +| `body` | `str` | — | | A solid body, as list_bodies names it | +| `face_point` | `list[float]` | — | | [x, y, z] in mm, a point on the face; give one target, or none for the whole part | +| `color` | `list[int] \| str` | — | | [r, g, b], each 0-255, or '#rrggbb', e.g. [31, 119, 180] or '#1f77b4' | +| `transparency` | `float` | — | `0.0` | 0 opaque (default) to 1 clear | +| `reset` | `bool` | — | `false` | Remove the feature's, body's or face's own colour so the one above it shows; give no color | + +**Sample call:** + +```json +{"color": "#1f77b4", "face_point": [0, 10, 0]} +``` + +--- + +### `get_appearance` + +Read the colour the active part, a feature, a body or the face at a point shows, and where it comes from. + +The reply's `level` is `face`, `feature`, `body` or `part`: the nearest level with a colour of its own. + +**Prerequisite:** Active part. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `feature` | `str` | — | | A feature by its name in the tree, e.g. 'Boss-Extrude1' | +| `body` | `str` | — | | A solid body, as list_bodies names it | +| `face_point` | `list[float]` | — | | [x, y, z] in mm, a point on the face; give one target, or none for the whole part | + +**Sample call:** + +```json +{"face_point": [20, 5, 0]} +``` diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index 2e44633f..e3734757 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,6 +1,6 @@ -# Tool Catalog — All 165 Tools +# Tool Catalog — All 171 Tools -This reference documents all **165 MCP tools** registered by the SolidWorks MCP server. +This reference documents all **171 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. ![Tool categories overview — 109 tools across 12 functional areas](../../assets/images/tool-categories-overview.svg) @@ -12,6 +12,8 @@ Each section covers one functional category with parameter tables and copy-paste | [Modeling Tools](modeling.md) | 44 | Parts, assemblies and drawings: extrusions, revolves, helices, sweeps and swept cuts, lofts, cuts, Hole Wizard holes, cosmetic threads, shells, drafts, ribs, sheet metal (flanges, bends, the flat pattern), fillets, chamfers, patterns, reference geometry, mates, dimensions, feature renaming and the document unit system. | | [Equation Tools](equations.md) | 3 | Equations and global variables: one value driving several dimensions, in all configurations or chosen ones. | | [Body Tools](bodies.md) | 6 | A part's solid bodies by name: add, subtract or intersect them, split them at a plane, move, copy, delete or scale them, each step measured. | +| [Appearance Tools](appearance.md) | 2 | Colour the part, a feature, a body or one face, and read back the colour that shows and where it comes from. | +| [Reference and Analysis Extras](reference-extras.md) | 4 | A coordinate system at a point, the centre-of-mass point, the bounding box with the stock size, and a planar face's section properties. | | [Assembly Tools](assembly.md) | 5 | Exploded views, component patterns and mirrors, and replacing a component with another file. | | [Sketching Tools](sketching.md) | 27 | Sketches on a plane or a flat face: lines, circles, arcs, slots, splines, polygons, text, fillets, chamfers, trim and extend, construction geometry, relations, dimensions, offsets, mirrors and patterns. | | [Drawing Tools](drawing.md) | 14 | Drawings from a model: standard, section, detail and exploded views, dimensions, notes, balloons, centre marks, the sheet format and title block, and a drawing check. | diff --git a/docs/user-guide/tool-catalog/reference-extras.md b/docs/user-guide/tool-catalog/reference-extras.md new file mode 100644 index 00000000..1cb1a5fd --- /dev/null +++ b/docs/user-guide/tool-catalog/reference-extras.md @@ -0,0 +1,93 @@ +# Reference and Analysis Extras + +A coordinate system at a point, the centre-of-mass point, the bounding box, and a face's section properties. + +> **Prerequisite:** an open part; all but the coordinate system need a solid body. + +**Total tools in this category: 4** + +Each reply is read back from SolidWorks: the coordinate system's transform, the centre of mass, the bodies' box and the face's section. For the numbers alone, without adding a feature, `get_mass_properties` gives the centre of mass and `verify_model` the box size. + +--- + +### `create_coordinate_system` + +Add a coordinate system with its origin at a point, axes along the model's. + +The origin is a point in a 3D sketch the tool draws for it. The axes lie along the model's; they can't yet be turned or reversed. Use the coordinate system as a frame for measurements, mass properties or exports. + +**Prerequisite:** Active part. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `origin` | `list[float]` | ✅ | | The origin [x, y, z] in mm | + +**Sample call:** + +```json +{"origin": [20, 10, 20]} +``` + +--- + +### `create_center_of_mass_point` + +Add SolidWorks's Center of Mass point to the active part, at its centre of mass. + +The point moves with the geometry. A part has one at most; a second call, or a part with no solid body, is refused. + +**Prerequisite:** Active part with a body. + +**Parameters:** none. + +**Sample call:** + +```json +{} +``` + +--- + +### `create_bounding_box` + +Add SolidWorks's Bounding Box feature around the active part's bodies and give the stock size. + +The box is SolidWorks's best fit and updates with the part. The reply's `size_mm`, `min_mm` and `max_mm` are the bodies' box in model axes. A part has one at most. + +**Prerequisite:** Active part with a body. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `include_hidden` | `bool` | — | `false` | Include hidden bodies in the box | + +**Sample call:** + +```json +{} +``` + +--- + +### `get_section_properties` + +Read the area, centroid and second moments of area of a planar face, picked by a point on it. + +Moments are about the face's centroid in model axes (`ixx` ... `iyz`, mm⁴), with the polar moment and the two principal moments. A 40 mm square face gives 1,600 mm² and 40⁴/12 = 213,333 mm⁴ about each in-plane axis. Changes nothing. + +**Prerequisite:** Active part. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `face_point` | `list[float]` | ✅ | | [x, y, z] in mm, a point on a planar face | + +**Sample call:** + +```json +{"face_point": [0, 10, 0]} +``` diff --git a/docs/user-guide/tools-overview.md b/docs/user-guide/tools-overview.md index f961fcd0..0ab80cac 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -71,6 +71,22 @@ These read SolidWorks' installed files and never start it [**6 tools available** :octicons-arrow-right-24:](tool-catalog/bodies.md) +- :material-palette:{ .lg .middle } **Appearance Tools** + + --- + + Colour the part, a feature, a body or one face, and read back the colour that shows. + + [**2 tools available** :octicons-arrow-right-24:](tool-catalog/appearance.md) + +- :material-axis-arrow:{ .lg .middle } **Reference and Analysis Extras** + + --- + + A coordinate system at a point, the centre-of-mass point, the bounding box and a face's section properties. + + [**4 tools available** :octicons-arrow-right-24:](tool-catalog/reference-extras.md) + - :material-cogs:{ .lg .middle } **Assembly Tools** --- @@ -201,7 +217,7 @@ These read SolidWorks' installed files and never start it -**Total: 165 Tools** +**Total: 171 Tools** ## Deprecated tools diff --git a/mkdocs.yml b/mkdocs.yml index c75dd830..8ffffcb8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -51,6 +51,8 @@ nav: - Modeling: user-guide/tool-catalog/modeling.md - Equations: user-guide/tool-catalog/equations.md - Bodies: user-guide/tool-catalog/bodies.md + - Appearance: user-guide/tool-catalog/appearance.md + - Reference Extras: user-guide/tool-catalog/reference-extras.md - Assembly: user-guide/tool-catalog/assembly.md - Sketching: user-guide/tool-catalog/sketching.md - Drawing: user-guide/tool-catalog/drawing.md diff --git a/openspec/changes/appearance-and-reference-tools/.openspec.yaml b/openspec/changes/appearance-and-reference-tools/.openspec.yaml new file mode 100644 index 00000000..8c7aa0b9 --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-27 diff --git a/openspec/changes/appearance-and-reference-tools/design.md b/openspec/changes/appearance-and-reference-tools/design.md new file mode 100644 index 00000000..1d018018 --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/design.md @@ -0,0 +1,84 @@ +## Context + +Motivation: see proposal.md, under "Why". + +**Probes (SolidWorks 2026 SP4, 2026-11-28; scratch part, closed unsaved):** + +- **Colour.** A colour is nine doubles: R, G, B (0-1), ambient, diffuse, + specular, shininess, transparency, emission. It must be passed as a + `VARIANT(VT_ARRAY | VT_R8)` (`com_utils.double_array`): a plain list was + misread (the boolean demo's bodies came out green and see-through). + - Part: `IModelDoc2.MaterialPropertyValues` (read/write property). Reads + `[0.894, 0.894, 0.894, 1, 1, 0.5, 0.3125, 0, 0]` on a new part. + - Feature: `IFeature.SetMaterialPropertyValues2(values, 1, None)` (1 = + this configuration); `GetMaterialPropertyValues2(1, None)` reads it, all + `-1` when the feature has none; `RemoveMaterialProperty2(1, None)` + removes it. + - Face: `IFace2.MaterialPropertyValues` (property), `None` when the face + has none; `RemoveMaterialProperty2(1, None)` removes it. + - Body: `IBody2.MaterialPropertyValues2` (property; set live in the + boolean demo). + - A face's colour shows over its feature's, a feature's over the part's + (image: blue top face, green sides, red part colour hidden). +- **Coordinate system.** `IFeatureManager.InsertCoordinateSystem(xFlip, + yFlip, zFlip)` with the origin selected with mark 1 and no axes selected + gives model-aligned axes. A vertex works, and so does a point in a 3D + sketch (`Insert3DSketch`, `CreatePoint(m)`, `Insert3DSketch` again; the + point selects as `Point1@3DSketch1`, type `EXTSKETCHPOINT`). An x axis + taken from an edge follows the edge's own direction (it came out + reversed), so edges are not offered. The transform reads back through + `IModelDocExtension.GetCoordinateSystemTransformByName(name).ArrayData`: + rotation rows `[0:9]`, origin in metres `[9:12]`. +- **Centre of mass.** `IFeatureManager.InsertCenterOfMass()` returns the + feature, named "Center of Mass". The centre comes from + `IModelDocExtension.CreateMassProperty().CenterOfMass` (metres), with the + extension flagged `IModelDocExtension` (unflagged, it was read as a + property and failed). +- **Bounding box.** `IFeatureManager.InsertGlobalBoundingBox(0, hidden, + surfaces, status)` needs `status` as `VARIANT(VT_BYREF | VT_I4, 0)`; + a plain `0` is a type mismatch. It makes "Bounding Box" (type + `BoundingBoxProfileFeat`). Type 0 is best fit. +- **Section properties.** `IModelDocExtension.GetSectionProperties2(None)` + reads the current selection; passing the face in an array returned + status 1 and zeros. The array: `[0]` status (0 = ok), `[1]` area m², + `[2:5]` centroid m, `[5:11]` Ixx, Iyy, Izz, Ixy, Izx, Iyz at the centroid + (m⁴), `[11]` polar moment, `[12]` the principal axes' angle, `[13:15]` + the principal moments. A 40 mm square: area 0.0016, centroid + `(0, 0.01, 0)`, Ixx = Izz = 2.133e-7, polar 4.267e-7. + +## Goals / Non-Goals + +**Goals:** colour any level and read it back; the four reference extras, +each read back from SolidWorks rather than echoed. + +**Non-Goals:** +- Appearances from the library (`.p2m` files, textures), decals, scenes. +- Colours in assemblies (component overrides). +- Coordinate systems from edges, faces or angles, or with reversed axes: + only a point with model-aligned axes. The flip flags of + `InsertCoordinateSystem` do nothing when no axis is selected (the live + test asked for z flipped and read +z back), so reversed axes need axis + lines drawn and selected, a later change. +- Bounding boxes on a custom plane (type 1) or in sheet-metal cut lists. +- Section properties of sketches or of a plane through a body. + +## Decisions + +1. **One `set_appearance`, a target by field.** Exactly one of `feature`, + `body`, `face_point`, or none for the part. Two targets are refused. + `reset` removes an override; resetting the part is refused. +2. **Colours as the user says them.** `[r, g, b]` 0-255 or `#rrggbb` in; + both out, plus transparency. The other six values keep SolidWorks's + defaults for shading (ambient 1, diffuse 1, specular 0.5, shininess + 0.3125, emission 0); only transparency is the caller's. +3. **Faces by point.** A face is picked by `SelectByID2("", "FACE", x, y, z)` + after a rebuild (pitfall #13), the way `select_face_edges` does. +4. **Read back, not echo.** Each reply reads SolidWorks: the colour after + setting it, the coordinate system's transform, the centre of mass, the + box's size (the part box after the feature), the section array. +5. **Module layout.** Appearance and the reference extras are separate + modules, adapter and mock, so neither grows `features.py` or + `modeling.py` (queue item 40). +6. **Errors.** Unknown targets and two targets are `invalid_input` + (`InputRefused`); a SolidWorks call that makes nothing raises a + message the classifier maps to `feature_not_built`. diff --git a/openspec/changes/appearance-and-reference-tools/proposal.md b/openspec/changes/appearance-and-reference-tools/proposal.md new file mode 100644 index 00000000..0dde5780 --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/proposal.md @@ -0,0 +1,62 @@ +## Why + +Two gaps in the COM coverage, queue items 36 and 39: + +- **Appearance.** An agent can't colour anything. A part, a feature, a body or + one face can't be given a colour, so a demo, a rendering or a multi-body + part can't show which piece is which, and a colour can't be read back. + The boolean-logic demo had to colour its bodies with direct COM in the + test (queue item 35). +- **Reference and analysis extras.** There is no coordinate system, no + centre-of-mass point, no bounding box feature and no section properties + of a face. These are what an agent needs to report stock size (bounding + box), place a measurement or export frame (coordinate system), mark where + the mass sits (centre of mass), or check a cross-section (area, centroid + and second moments of area of a face, for a beam or a bracket). + +## What Changes + +- **`set_appearance`**: colour the part, a feature, a body or the face at a + point, as `[r, g, b]` (0-255) or `#rrggbb`, with an optional + transparency; or with `reset: true` remove a feature's, body's or face's + colour so the one above it shows again. The reply reads the colour back. +- **`get_appearance`**: read the colour of the part, a feature, a body or a + face, and say which level it comes from. +- **`create_coordinate_system`**: a coordinate system with its origin at a + point given in mm, axes along the model's. + The reply reads its transform back. +- **`create_center_of_mass_point`**: the Center of Mass reference point, + with the centre of mass in mm. +- **`create_bounding_box`**: SolidWorks's Bounding Box feature around the + part's bodies, with the box size in mm. +- **`get_section_properties`**: area, centroid, second moments of area about + the centroid, the polar moment and the principal moments of a planar face, + picked by a point on it. +- Six new tools, beta until their live demo. + +## Capabilities + +### New Capabilities + +- `tools/appearance`: `set_appearance` and `get_appearance`. +- `tools/reference-extras`: `create_coordinate_system`, + `create_center_of_mass_point`, `create_bounding_box` and + `get_section_properties`. + +### Modified Capabilities + +None. + +## Impact + +- New adapter modules `adapters/solidworks/appearance.py` and + `adapters/solidworks/reference_extras.py`, with mocks + `adapters/mock_appearance.py` and `adapters/mock_reference_extras.py`. + New non-abstract methods in `adapters/base.py`, with wrappers in + `circuit_breaker.py` and `connection_pool.py`. +- New tool modules `tools/appearance.py` and `tools/reference_extras.py`, + registered in `tools/__init__.py`; the families join the core toolset. +- Docs: two tool-catalog pages, counts, the skill's workflow notes, the + CHANGELOG. +- Tests mirror `src`; a live test `tests/live/test_live_sw_appearance_and_reference.py` + with one refusal per tool family. diff --git a/openspec/changes/appearance-and-reference-tools/specs/tools/appearance/spec.md b/openspec/changes/appearance-and-reference-tools/specs/tools/appearance/spec.md new file mode 100644 index 00000000..36f6a86b --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/specs/tools/appearance/spec.md @@ -0,0 +1,52 @@ +## ADDED Requirements + +### Requirement: Colour the part, a feature, a body or a face +`set_appearance` SHALL take a `color`, either `[r, g, b]` with each value 0 +to 255 or a `#rrggbb` string, and an optional `transparency` from 0 (opaque, +the default) to 1. It SHALL colour exactly one target: the whole part when +no target is given, or the feature named by `feature`, the body named by +`body` (as `list_bodies` names it), or the face at `face_point` (`[x, y, z]` +mm, a point on the face). The reply SHALL read the colour back from +SolidWorks and give it as `color` `[r, g, b]` (0-255), `hex` and +`transparency`, with `target` saying what was coloured. + +A face's colour shows over its feature's, and a feature's over the part's +(checked live, SolidWorks 2026). + +#### Scenario: A blue top face on a green block +- **WHEN** a 40 × 40 × 10 mm block's feature `Boss-Extrude1` is set to + `#1fcc33` and the face at `[0, 10, 0]` to `[25, 76, 242]` +- **THEN** both calls succeed, each reply reads back the colour asked for + (to the nearest 1/255), and the top face shows blue over the green sides + +#### Scenario: Two targets at once +- **WHEN** `set_appearance` is given both `feature` and `face_point` +- **THEN** it fails with `invalid_input`, saying to give one target + +#### Scenario: A target that doesn't exist +- **WHEN** `feature` names no feature, `body` no body, or `face_point` + lies on no face +- **THEN** it fails with `invalid_input`; for a body the message lists the + bodies there are + +### Requirement: Remove a colour +`set_appearance` with `reset: true` and a `feature`, `body` or `face_point` +SHALL remove that target's own colour so the colour above it shows again, +and SHALL reply `color` null for it. `reset` on the whole part SHALL fail +with `invalid_input`: the part's colour is the base, not an override. + +#### Scenario: A face back to its feature's colour +- **WHEN** a coloured face is reset +- **THEN** the call succeeds and `get_appearance` on that face reports the + feature's colour, from `level` "feature" + +### Requirement: Read a colour back +`get_appearance` SHALL take the same targets (none for the part) and reply +`color`, `hex`, `transparency` and `level`: the level the visible colour +comes from (`face`, `body`, `feature` or `part`), walking up from the +target until one has a colour of its own. + +#### Scenario: An uncoloured face of a coloured feature +- **WHEN** only `Boss-Extrude1` is coloured and a side face is read +- **THEN** `get_appearance` gives the feature's colour with `level` + "feature" diff --git a/openspec/changes/appearance-and-reference-tools/specs/tools/reference-extras/spec.md b/openspec/changes/appearance-and-reference-tools/specs/tools/reference-extras/spec.md new file mode 100644 index 00000000..074918f5 --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/specs/tools/reference-extras/spec.md @@ -0,0 +1,54 @@ +## ADDED Requirements + +### Requirement: A coordinate system at a point +`create_coordinate_system` SHALL take `origin` (`[x, y, z]` mm) and SHALL +insert a coordinate system there with its axes along the model's. The origin is a +point in a 3D sketch the tool draws for it. The reply SHALL give the +feature's `name` and read its transform back as `origin_mm` and the three +axis directions `x_axis`, `y_axis` and `z_axis`. + +#### Scenario: At a corner of a block +- **WHEN** it is called with `origin` `[20, 10, 20]` on a 40 × 40 × 10 mm + block +- **THEN** it replies `name` "Coordinate System1", `origin_mm` + `[20, 10, 20]` and `x_axis` `[1, 0, 0]` + +#### Scenario: No turning yet +- **WHEN** a caller wants turned or reversed axes +- **THEN** the tool has no input for it: SolidWorks ignores the flip flags + when no axis is selected (checked live), so turned axes wait for axis + lines drawn and selected (a later change) + +### Requirement: The centre-of-mass point +`create_center_of_mass_point` SHALL insert SolidWorks's Center of Mass +reference point on the active part and reply with its `name` and +`center_of_mass_mm`. A part that has one already, or has no solid body, +SHALL fail with `invalid_input` saying so. + +#### Scenario: A block 10 mm tall on the Top Plane +- **WHEN** it is called on a 40 × 40 × 10 mm block +- **THEN** `center_of_mass_mm` is `[0, 5, 0]` + +### Requirement: The bounding box +`create_bounding_box` SHALL insert SolidWorks's Bounding Box feature around +the part's solid bodies (best fit), optionally including hidden bodies, and +reply with its `name` and the box's `size_mm` `[x, y, z]`, read from +SolidWorks. + +#### Scenario: A block +- **WHEN** it is called on a 40 × 40 × 10 mm block +- **THEN** `size_mm` holds 40, 10 and 40 (in model axes) + +### Requirement: Section properties of a planar face +`get_section_properties` SHALL take `face_point` (`[x, y, z]` mm on a planar +face) and reply with the face's `area_mm2`, `centroid_mm`, the second +moments of area about the centroid in model axes (`ixx`, `iyy`, `izz`, +`ixy`, `izx`, `iyz`, mm⁴), `polar_moment_mm4` and the principal moments +`principal_moments_mm4`. It changes nothing in the model. A point on no +face, or on a face SolidWorks can't take a section of, SHALL fail with +`invalid_input`. + +#### Scenario: A 40 mm square face +- **WHEN** it is given the top face of a 40 × 40 × 10 mm block +- **THEN** `area_mm2` is 1600, `centroid_mm` is `[0, 10, 0]`, and `ixx` and + `izz` are 40⁴/12 = 213,333.3 mm⁴ diff --git a/openspec/changes/appearance-and-reference-tools/tasks.md b/openspec/changes/appearance-and-reference-tools/tasks.md new file mode 100644 index 00000000..8d5182c0 --- /dev/null +++ b/openspec/changes/appearance-and-reference-tools/tasks.md @@ -0,0 +1,44 @@ +## 1. Probe + +- [x] 1.1 Probe colour (part, feature, face), the coordinate system (vertex, + edge, 3D-sketch point), the centre of mass, the bounding box and the + section properties on SolidWorks 2026 (two scripts; answers in + design.md) + +## 2. Adapter + +- [x] 2.1 `base.py`: parameter models and non-abstract methods for the six + operations; wrappers in `circuit_breaker.py` and `connection_pool.py` +- [x] 2.2 `adapters/solidworks/appearance.py`: set, reset and read colours +- [x] 2.3 `adapters/solidworks/reference_extras.py`: coordinate system, + centre-of-mass point, bounding box, section properties +- [x] 2.4 Mocks: `mock_appearance.py`, `mock_reference_extras.py` +- [x] 2.5 Pure helpers (colour parsing and conversion, the section array, + the transform) in `adapters/appearance_rules.py` + +## 3. Tools + +- [x] 3.1 `tools/appearance.py`: `set_appearance`, `get_appearance` +- [x] 3.2 `tools/reference_extras.py`: `create_coordinate_system`, + `create_center_of_mass_point`, `create_bounding_box`, + `get_section_properties` +- [x] 3.3 Register both; toolset families; support levels (beta); hints; + error classifier rules + +## 4. Tests + +- [x] 4.1 Unit tests mirroring src, 100% coverage +- [x] 4.2 Live test `tests/live/test_live_sw_appearance_and_reference.py`: + a block with a coloured feature and face, read back; a coordinate + system, the centre of mass, the bounding box, the section properties; + one refusal per family. Run it, look at the images. + (Both passed on SolidWorks 2026, 2026-11-28; the picture showed the + blue top face, green sides, an orange face, the coordinate system at + the corner and the box. The first run caught the flip flags doing + nothing; they were dropped.) + +## 5. Docs + +- [x] 5.1 Tool-catalog pages, index and counts, tools overview, skill + workflow notes, description standard verbs, CHANGELOG, llms.txt +- [x] 5.2 A demo section and GIF once the user has seen it diff --git a/openspec/changes/helix-and-swept-cuts/.openspec.yaml b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/.openspec.yaml similarity index 100% rename from openspec/changes/helix-and-swept-cuts/.openspec.yaml rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/.openspec.yaml diff --git a/openspec/changes/helix-and-swept-cuts/design.md b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/design.md similarity index 100% rename from openspec/changes/helix-and-swept-cuts/design.md rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/design.md diff --git a/openspec/changes/helix-and-swept-cuts/proposal.md b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/proposal.md similarity index 100% rename from openspec/changes/helix-and-swept-cuts/proposal.md rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/proposal.md diff --git a/openspec/changes/helix-and-swept-cuts/specs/tools/helix/spec.md b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/specs/tools/helix/spec.md similarity index 100% rename from openspec/changes/helix-and-swept-cuts/specs/tools/helix/spec.md rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/specs/tools/helix/spec.md diff --git a/openspec/changes/helix-and-swept-cuts/specs/tools/swept-features/spec.md b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/specs/tools/swept-features/spec.md similarity index 100% rename from openspec/changes/helix-and-swept-cuts/specs/tools/swept-features/spec.md rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/specs/tools/swept-features/spec.md diff --git a/openspec/changes/helix-and-swept-cuts/tasks.md b/openspec/changes/archive/2026-11-28-helix-and-swept-cuts/tasks.md similarity index 100% rename from openspec/changes/helix-and-swept-cuts/tasks.md rename to openspec/changes/archive/2026-11-28-helix-and-swept-cuts/tasks.md diff --git a/openspec/changes/multi-body-tools/.openspec.yaml b/openspec/changes/archive/2026-11-28-multi-body-tools/.openspec.yaml similarity index 100% rename from openspec/changes/multi-body-tools/.openspec.yaml rename to openspec/changes/archive/2026-11-28-multi-body-tools/.openspec.yaml diff --git a/openspec/changes/multi-body-tools/design.md b/openspec/changes/archive/2026-11-28-multi-body-tools/design.md similarity index 100% rename from openspec/changes/multi-body-tools/design.md rename to openspec/changes/archive/2026-11-28-multi-body-tools/design.md diff --git a/openspec/changes/multi-body-tools/proposal.md b/openspec/changes/archive/2026-11-28-multi-body-tools/proposal.md similarity index 100% rename from openspec/changes/multi-body-tools/proposal.md rename to openspec/changes/archive/2026-11-28-multi-body-tools/proposal.md diff --git a/openspec/changes/multi-body-tools/specs/tools/body-listing/spec.md b/openspec/changes/archive/2026-11-28-multi-body-tools/specs/tools/body-listing/spec.md similarity index 100% rename from openspec/changes/multi-body-tools/specs/tools/body-listing/spec.md rename to openspec/changes/archive/2026-11-28-multi-body-tools/specs/tools/body-listing/spec.md diff --git a/openspec/changes/multi-body-tools/specs/tools/body-operations/spec.md b/openspec/changes/archive/2026-11-28-multi-body-tools/specs/tools/body-operations/spec.md similarity index 100% rename from openspec/changes/multi-body-tools/specs/tools/body-operations/spec.md rename to openspec/changes/archive/2026-11-28-multi-body-tools/specs/tools/body-operations/spec.md diff --git a/openspec/changes/multi-body-tools/tasks.md b/openspec/changes/archive/2026-11-28-multi-body-tools/tasks.md similarity index 100% rename from openspec/changes/multi-body-tools/tasks.md rename to openspec/changes/archive/2026-11-28-multi-body-tools/tasks.md diff --git a/openspec/queue.md b/openspec/queue.md index 41af0849..75a33984 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -46,10 +46,10 @@ Last updated 2026-11-25. | 33 | Assembly depth and a ballooned drawing: exploded view, component patterns, mirror and replace components, hide/show/transparency, `AutoBalloon` on the drawing | #23 (part) | `assembly-depth` | Done (#260, archived 2026-11-22) | | 34 | Helix and swept cuts: helix/spiral, a swept cut (`create_sweep` only adds material), thicken; springs and modelled threads | none | `helix-and-swept-cuts` | Built 2026-11-25: `create_helix`, `create_cut_sweep`, named and circular sweep profiles, both sweeps measured. Live demos passed 2026-11-26; beta for now (the user's choice) | | 35 | Multi-body tools: combine (add, subtract, common), split, move/copy, delete/keep a body, scale | none | `multi-body-tools` | Done 2026-11-27: six tools, beta; the user ran the three demos (boolean logic on a cube and a sphere, split and keep, copies and scale) | -| 36 | Appearance and colour: set a part's, body's or face's colour and read it back | none | not yet written | Planned (small; may ride with another item) | +| 36 | Appearance and colour: set a part's, body's or face's colour and read it back | none | `appearance-and-reference-tools` | Built 2026-11-28 with item 39: `set_appearance`, `get_appearance`; live tests pass; beta until the user's demo | | 37 | Drawing sheets and callouts: new and active sheet, auxiliary, break and broken-out views, hole callouts, ordinate dimensions, surface finish, revision table | #158 (part) | not yet written | Planned | | 38 | Weldments: structural members, trim/extend, end caps, gussets, cut list | none | not yet written | Planned (needs live probes: the profile library location varies) | -| 39 | Reference and analysis extras: coordinate system, bounding box, centre-of-mass point, section properties; wrap (text on a curved face) | none | not yet written | Planned | +| 39 | Reference and analysis extras: coordinate system, bounding box, centre-of-mass point, section properties; wrap (text on a curved face) | none | `appearance-and-reference-tools` | Built 2026-11-28 except wrap: `create_coordinate_system` (model axes only; SolidWorks ignores the flips with no axis selected), `create_center_of_mass_point`, `create_bounding_box`, `get_section_properties`; live tests pass; beta until the user's demo. Wrap and turned axes are left | | 40 | Structure review (the user's request 2026-11-19), not a rewrite: the adapter wrappers (`base`, `circuit_breaker`, `connection_pool`, each about 2,500 lines of near-identical per-tool methods) repeat every adapter method, and the largest modules (`mock_adapter` 4,900, `io` 4,000, `features` 3,800, `modeling` 3,200, `sketch` 2,900 lines) should split by topic, as `adapters/solidworks/` already does. Measure the repetition, propose a SOLID structure (one generic forwarding path; one module per topic), and move to it in steps that keep every test passing. Widened 2026-11-25 (the user's request): also audit every function for full type hints, Google-style docstrings with every section (Args, Returns, Raises, and an Example where the use isn't obvious), and inline comments that explain the logic, so each function's job is obvious; and the code sprawl: files and helpers that have grown in miscellaneous places, and a layout that scales to more tools and features (where a new tool's adapter method, wrapper, mock, schema and tests go). Its own PR, separate from feature work | none | not yet written | Planned (last) | | 41 | Test in other SolidWorks languages: find how to switch SolidWorks' language on this machine (System Options > General > "Use English language", language packs from the Installation Manager, the registry), what that changes (UI, default template names, feature and sketch point names such as `Point1`, standard view names, `GetModelViewNames` order) and run the default-entity and selftest live tests in German and French. Prompted by #262: 2.2.0's language handling was only tested on English SolidWorks with renamed planes | #262 (follow-up) | not yet written | Planned | | 42 | U-joint replay differences: decide, call by call, whether each of the nine calls that end differently on today's server is variance in a long agent run or something to fix on our end (a clearer error, a better description, or accepting `axis_entity: "centerline"` when the sketch has one centreline); rerun the prompt on today's server and compare | #278 | not yet written | Planned | diff --git a/openspec/specs/tools/body-listing/spec.md b/openspec/specs/tools/body-listing/spec.md new file mode 100644 index 00000000..96abf3c5 --- /dev/null +++ b/openspec/specs/tools/body-listing/spec.md @@ -0,0 +1,32 @@ +# tools/body-listing Specification + +## Purpose +TBD - created by archiving change multi-body-tools. Update Purpose after archive. +## Requirements +### Requirement: The part's solid bodies, by name +`list_bodies` SHALL take no arguments and SHALL reply, for the active part, +with `bodies`, a list in the order SolidWorks gives them. Each entry SHALL carry `name` +(the name every body tool accepts), `volume_mm3` and `bounding_box_mm`, the +box's `min` and `max` corners `[x, y, z]` and its `size`. The reply SHALL +also carry `count` and `total_volume_mm3`. Only solid bodies are listed; +surface bodies are left out. + +#### Scenario: Two blocks not merged +- **WHEN** a part holds a 40 × 40 × 10 mm block and a second + 20 × 20 × 30 mm block extruded with `merge_result: false` +- **THEN** `list_bodies` replies `count` 2, with each body's name, the + volumes 16000 and 12000, and a `total_volume_mm3` of 28000 + +#### Scenario: A part with no body yet +- **WHEN** the active part has only sketches +- **THEN** `list_bodies` succeeds with `count` 0 and an empty `bodies` + +### Requirement: Only on a part +`list_bodies` SHALL fail with `invalid_input` when no document is open or +the active document is an assembly or a drawing, and the message SHALL say +a part must be active. + +#### Scenario: An assembly is active +- **WHEN** `list_bodies` is called with an assembly active +- **THEN** it fails with `invalid_input`, saying it reads a part's bodies + diff --git a/openspec/specs/tools/body-operations/spec.md b/openspec/specs/tools/body-operations/spec.md new file mode 100644 index 00000000..461d8b84 --- /dev/null +++ b/openspec/specs/tools/body-operations/spec.md @@ -0,0 +1,129 @@ +# tools/body-operations Specification + +## Purpose +TBD - created by archiving change multi-body-tools. Update Purpose after archive. +## Requirements +### Requirement: Bodies are named as list_bodies names them +Every body operation SHALL take bodies by the names `list_bodies` gives, +ignoring case. A name that matches no solid body SHALL fail with +`invalid_input` before anything changes. The message SHALL name the unknown +body and list the bodies that exist. + +#### Scenario: A misspelt body +- **WHEN** `combine_bodies` names a tool body `Boss-Extrude9` that doesn't + exist +- **THEN** the call fails with `invalid_input`, the message lists the + part's bodies, and the feature tree is unchanged + +### Requirement: Every operation is measured +On success, every body operation SHALL reply with the new feature's `name`, +`bodies_before` and `bodies_after` (the names), `body_count_before`, +`body_count_after`, `volume_before_mm3`, `volume_after_mm3` and +`volume_change_mm3`. When the result breaks the rule for its operation (in +the requirements below), the call SHALL fail with `feature_not_built`, the +new feature SHALL be deleted, and the message SHALL give the counts and +volumes it found. Volumes count as unchanged within 0.1%. + +#### Scenario: A subtract that removes nothing +- **WHEN** `combine_bodies` subtracts a tool body that doesn't touch the + main body, and SolidWorks still makes a feature +- **THEN** the call fails with `feature_not_built`, the combine feature is + deleted, and both bodies are back as they were + +### Requirement: Combine bodies +`combine_bodies` SHALL take `operation` (`add`, `subtract` or `common`), +`main_body` and `tool_bodies` (one or more names, none of them the main +body). The tool bodies are consumed. The result is measured by its own +volume: the part's volume after, less the bodies the combine didn't touch. +`add` SHALL leave fewer bodies and a result no larger than the combined +bodies were. `subtract` and `common` SHALL leave a result smaller than the +main body was. A tool lying elsewhere is consumed without cutting, so the +part's total alone can't show the cut. + +#### Scenario: A block minus a cylinder +- **WHEN** a 40 × 40 × 10 mm block has a 10 mm diameter cylinder through + it as a separate body, and `combine_bodies` subtracts the cylinder from + the block +- **THEN** one body remains, its volume is + `16000 - pi * 5^2 * 10` mm³, and the reply names the combine feature + +#### Scenario: The main body among the tools +- **WHEN** `tool_bodies` includes `main_body` +- **THEN** the call fails with `invalid_input` and nothing changes + +### Requirement: Split a body +`split_body` SHALL take `tool`, the name of a plane or a sketch, and SHALL +split every body the tool crosses, as SolidWorks does. The result SHALL +have more bodies than before and the same volume. The reply SHALL name the +bodies made. + +#### Scenario: A block split at its middle +- **WHEN** a 40 × 40 × 10 mm block centred on the origin is split by the + Right Plane +- **THEN** there are two bodies of 8000 mm³ each, and the volume is + unchanged + +#### Scenario: A plane that misses the body +- **WHEN** the tool is a plane that doesn't cross any body +- **THEN** the call fails, and no split feature remains + +### Requirement: Move or copy bodies +`move_copy_body` SHALL take `bodies`, a `translate` `[x, y, z]` in mm, and +optionally a `rotate` `[x, y, z]` in degrees about `rotation_point` +`[x, y, z]` mm (the origin by default). With `as_copy: true` and `copies` N +(1 by default, at most 50), the bodies SHALL be copied N times instead of +moved. + +- A move SHALL keep the body count and the volume, and SHALL change the + moved bodies' bounding boxes. +- A copy SHALL add N bodies per body copied, and N times their volume. +- A call with no translation and no rotation SHALL fail with + `invalid_input`. +- A call with both a translation and a rotation SHALL fail with + `invalid_input`, saying to move twice. SolidWorks would apply only the + rotation. + +#### Scenario: A block moved 50 mm along x +- **WHEN** a block is moved by `[50, 0, 0]` +- **THEN** its bounding box moves 50 mm along x, and the count and volume + are unchanged + +#### Scenario: Three copies +- **WHEN** a 1000 mm³ body is copied with `copies` 3 and `translate` + `[20, 0, 0]` +- **THEN** there are 3 more bodies and 3000 mm³ more volume + +### Requirement: Delete or keep bodies +`delete_bodies` SHALL take `bodies` and `keep` (false by default). With +`keep` false the named bodies SHALL be removed. With `keep` true every +other body SHALL be removed. In both cases the volume SHALL fall by the +removed bodies' volumes. Removing every body SHALL fail with +`invalid_input` before anything changes. + +#### Scenario: Keep one of three +- **WHEN** a part has three bodies and `delete_bodies` keeps one +- **THEN** one body remains, with its own volume + +### Requirement: Scale bodies +`scale_body` SHALL take `scale` (one factor, uniform) or `scale_xyz` +`[x, y, z]`, all above 0, `about` (`centroid`, the default, or `origin`), +and optionally `bodies` (all by default). The volume of the scaled bodies +SHALL be multiplied by the product of the factors, within 0.5%. A factor of +exactly 1 on every axis SHALL fail with `invalid_input`. + +#### Scenario: A block scaled by 2 +- **WHEN** a 16000 mm³ block is scaled by 2 about its centroid +- **THEN** its volume is 128000 mm³, and its centroid stays where it was + +### Requirement: Mock adapter +The mock adapter SHALL keep a list of bodies with volumes and boxes, made +by unmerged extrusions. It SHALL apply each operation to that list by the +rules above, and SHALL refuse what the real adapter refuses, with the same +messages. + +#### Scenario: Subtract on the mock +- **WHEN** the mock part has two bodies and one is subtracted from the + other +- **THEN** one body remains, and the reply carries the counts and volumes + before and after + diff --git a/openspec/specs/tools/helix/spec.md b/openspec/specs/tools/helix/spec.md new file mode 100644 index 00000000..38fe0375 --- /dev/null +++ b/openspec/specs/tools/helix/spec.md @@ -0,0 +1,41 @@ +# tools/helix Specification + +## Purpose +TBD - created by archiving change helix-and-swept-cuts. Update Purpose after archive. +## Requirements +### Requirement: A helix from a base circle +`create_helix` SHALL make a helix (or a flat spiral) from a named sketch +that holds exactly one circle. The circle's diameter is the helix's +diameter and its centre is on the helix's axis, which is normal to the +sketch. The helix is defined by two of height, pitch and revolutions, +chosen by `defined_by`: `height_and_pitch` (the default), +`height_and_revolutions` or `pitch_and_revolutions`; `spiral` takes pitch +and revolutions and stays in the sketch's plane. Lengths are in mm and +angles in degrees. Options: `clockwise`, `reverse` (the other side of the +sketch), `start_angle`, and `taper_angle` with `taper_outward`. + +The reply SHALL give the helix's name, its height, pitch and revolutions +(the two given and the one worked out from them), its diameter, its length, +and the point where it starts in model mm, so a profile can be drawn there. + +#### Scenario: A helix by height and pitch +- **WHEN** a sketch holds a 20 mm circle and `create_helix` is called with + `height` 48 and `pitch` 6 +- **THEN** a helix is made, and the reply gives 8 revolutions, a 20 mm + diameter, its length and its start point + +#### Scenario: The values that define it are checked first +- **WHEN** `defined_by` is `height_and_revolutions` and `revolutions` is + missing, or any of height, pitch or revolutions is zero or negative +- **THEN** the call fails as `invalid_input` naming the field, and nothing + is made + +#### Scenario: The base sketch must be one circle +- **WHEN** the named sketch doesn't exist, or holds anything other than + exactly one circle +- **THEN** the call fails, saying what the sketch holds, and nothing is made + +#### Scenario: A flat spiral +- **WHEN** `defined_by` is `spiral` with `pitch` 5 and `revolutions` 3 +- **THEN** a spiral is made in the sketch's plane and the reply's height is 0 + diff --git a/openspec/specs/tools/swept-features/spec.md b/openspec/specs/tools/swept-features/spec.md new file mode 100644 index 00000000..8ef2a945 --- /dev/null +++ b/openspec/specs/tools/swept-features/spec.md @@ -0,0 +1,48 @@ +# tools/swept-features Specification + +## Purpose +TBD - created by archiving change helix-and-swept-cuts. Update Purpose after archive. +## Requirements +### Requirement: Sweeps that add or remove material +`create_sweep` SHALL sweep a closed profile along a path and add material; +`create_cut_sweep` SHALL do the same and remove material. The path is a +sketch or a curve such as a helix, named by `path`. The profile is, in +order of preference: a circle of `circular_profile_diameter` mm (no profile +sketch), the sketch named by `profile`, or the sketch closed last that +isn't the path. Both take `twist_along_path` and `twist_angle` (degrees); +`create_sweep` keeps `merge_result`. + +#### Scenario: A named profile +- **WHEN** `create_sweep` is called with `path` and `profile` naming two + sketches +- **THEN** that profile is swept along that path, whatever sketch was + closed last + +#### Scenario: A circle with no profile sketch +- **WHEN** `create_sweep` is called with a helix as `path` and + `circular_profile_diameter` 2 +- **THEN** a 2 mm wire is swept along the helix, and the reply says the + profile was a 2 mm circle + +#### Scenario: A cut sweep removes material +- **WHEN** `create_cut_sweep` sweeps a closed profile that overlaps a solid + along a helix +- **THEN** the part's volume goes down, and the reply gives the volume + before, after and the change + +#### Scenario: The profile is unclear +- **WHEN** neither `profile` nor `circular_profile_diameter` is given and + no sketch other than the path exists, or `profile` names the path itself +- **THEN** the call fails as `invalid_input`, naming the sketches found + +### Requirement: A sweep is judged by the volume +Both sweeps SHALL report the part's volume before and after and the change +in mm³. A sweep that changes nothing, or changes it the wrong way (a cut +that adds), SHALL be removed again and reported as an error, so a failed +sweep never stays in the tree. + +#### Scenario: A cut that misses the part +- **WHEN** `create_cut_sweep` sweeps a profile that doesn't touch the solid +- **THEN** the call fails saying the volume didn't change, and the feature + is not left in the tree + diff --git a/src/solidworks_mcp/adapters/appearance_rules.py b/src/solidworks_mcp/adapters/appearance_rules.py new file mode 100644 index 00000000..1f535f5a --- /dev/null +++ b/src/solidworks_mcp/adapters/appearance_rules.py @@ -0,0 +1,255 @@ +"""Rules shared by the appearance and reference-extras adapters (queue items 36, 39). + +Pure functions, used by the SolidWorks adapter and the mock alike, so both +refuse the same inputs with the same words and shape replies the same way: + +- :func:`target_kind` says which one target a call names, refusing two. +- :func:`parse_color` reads ``[r, g, b]`` or ``#rrggbb``; + :func:`material_values` and :func:`color_reply` convert to and from + SolidWorks's nine material values. +- :func:`section_reply` and :func:`transform_reply` read SolidWorks's + section-property and coordinate-system arrays (metres) into mm. + +The array layouts were measured on SolidWorks 2026 (design.md). +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence +from typing import Any + +from ..exceptions import InputRefused +from .base import AppearanceParameters, AppearanceTarget + +#: SolidWorks's shading values a new colour keeps: ambient, diffuse, +#: specular, shininess (read from a new part's colour on SolidWorks 2026). +SHADING = (1.0, 1.0, 0.5, 0.3125) +#: The levels a colour can come from, the one that shows first: SolidWorks's +#: appearance hierarchy (a face over its feature over its body over the part). +LEVELS = ("face", "feature", "body", "part") +_HEX = re.compile(r"^#?([0-9a-fA-F]{6})$") +#: ``GetSectionProperties2``'s status for a section it computed. +SECTION_OK = 0 + + +def target_kind(target: AppearanceTarget) -> str: + """The one target a call names: ``part``, ``feature``, ``body`` or ``face``. + + Args: + target: The call's target fields. + + Returns: + str: The target's kind; ``part`` when none is given. + + Raises: + InputRefused: More than one target, or a ``face_point`` that isn't + three numbers. + + Example: + >>> target_kind(AppearanceTarget(feature="Boss-Extrude1")) + 'feature' + """ + given = [ + kind + for kind, value in ( + ("feature", target.feature), + ("body", target.body), + ("face", target.face_point), + ) + if value is not None + ] + if len(given) > 1: + raise InputRefused( + f"Give one target, not {' and '.join(given)}: a feature, a body, " + "a face_point, or none for the whole part." + ) + if target.face_point is not None and len(target.face_point) != 3: + raise InputRefused("face_point must be [x, y, z] in mm.") + return given[0] if given else "part" + + +def parse_color(value: Sequence[int] | str | None) -> tuple[int, int, int]: + """An ``[r, g, b]`` (0-255) or ``#rrggbb`` colour as three ints. + + Args: + value: The colour as the caller gave it. + + Returns: + tuple[int, int, int]: Red, green and blue, 0-255. + + Raises: + InputRefused: No colour, or one that isn't three 0-255 values or a + six-digit hex string. + + Example: + >>> parse_color("#1fcc33") + (31, 204, 51) + """ + if value is None: + raise InputRefused( + "Give a color, [r, g, b] 0-255 or '#rrggbb', or reset: true to remove one." + ) + if isinstance(value, str): + match = _HEX.match(value.strip()) + if not match: + raise InputRefused(f"color '{value}' is not '#rrggbb'.") + digits = match.group(1) + red, green, blue = (int(digits[i : i + 2], 16) for i in (0, 2, 4)) + return red, green, blue + if len(value) != 3 or not all(0 <= int(v) <= 255 for v in value): + raise InputRefused(f"color {list(value)} must be [r, g, b], each 0 to 255.") + return int(value[0]), int(value[1]), int(value[2]) + + +def check_set(params: AppearanceParameters) -> str: + """Refuse a ``set_appearance`` call that can't work; return its target kind. + + Args: + params: The call. + + Returns: + str: The target's kind. + + Raises: + InputRefused: Two targets, a reset of the whole part, a colour with + a reset, no colour without one, or a transparency outside 0-1. + """ + kind = target_kind(params) + if params.reset: + if kind == "part": + raise InputRefused( + "reset removes a feature's, body's or face's own colour; the " + "part's colour is the base. Give the part a colour instead." + ) + if params.color is not None: + raise InputRefused("Give a color or reset: true, not both.") + return kind + parse_color(params.color) + if not 0.0 <= params.transparency <= 1.0: + raise InputRefused( + f"transparency must be 0 (opaque) to 1 (clear), not {params.transparency}." + ) + return kind + + +def material_values(rgb: tuple[int, int, int], transparency: float) -> list[float]: + """SolidWorks's nine material values for a colour. + + Args: + rgb: Red, green and blue, 0-255. + transparency: 0 to 1. + + Returns: + list[float]: R, G, B (0-1), ambient, diffuse, specular, shininess, + transparency, emission. + """ + return [c / 255.0 for c in rgb] + [*SHADING, float(transparency), 0.0] + + +def color_reply(values: Any) -> dict[str, Any] | None: + """A colour read from SolidWorks, or None when the target has none. + + SolidWorks gives no colour as ``None`` (a face) or nine ``-1`` (a + feature). + + Args: + values: The nine material values, or None. + + Returns: + dict[str, Any] | None: ``color`` ``[r, g, b]`` 0-255, ``hex`` and + ``transparency``; None when there is no colour. + + Example: + >>> color_reply([0.1, 0.8, 0.2, 1, 1, 0.5, 0.3125, 0, 0])["hex"] + '#1acc33' + """ + if not isinstance(values, (list, tuple)) or len(values) < 8: + return None + if all(float(v) < 0 for v in values[:3]): + return None + rgb = [round(float(v) * 255) for v in values[:3]] + return { + "color": rgb, + "hex": "#{:02x}{:02x}{:02x}".format(*rgb), + "transparency": round(float(values[7]), 3), + } + + +def section_reply(values: Any) -> dict[str, Any]: + """A face's section properties, in mm, from ``GetSectionProperties2``. + + Args: + values: SolidWorks's array: status, area (m²), centroid (m), six + moments at the centroid (m⁴), the polar moment, the principal + axes' angle, the two principal moments. + + Returns: + dict[str, Any]: ``area_mm2``, ``centroid_mm``, ``ixx`` ... ``iyz`` + (mm⁴), ``polar_moment_mm4`` and ``principal_moments_mm4``. + + Raises: + InputRefused: SolidWorks returned nothing or a status other than ok. + """ + if not isinstance(values, (list, tuple)) or len(values) < 15: + raise InputRefused( + "SolidWorks gave no section properties for that face; pick a " + "point on a planar face." + ) + if int(values[0]) != SECTION_OK: + raise InputRefused( + f"SolidWorks couldn't take a section of that face (status " + f"{int(values[0])}); pick a point on a planar face." + ) + mm4 = 1e12 + names = ("ixx", "iyy", "izz", "ixy", "izx", "iyz") + reply: dict[str, Any] = { + "area_mm2": round(float(values[1]) * 1e6, 4), + "centroid_mm": [round(float(v) * 1000, 4) for v in values[2:5]], + } + reply.update( + { + name: round(float(v) * mm4, 2) + for name, v in zip(names, values[5:11], strict=True) + } + ) + reply["polar_moment_mm4"] = round(float(values[11]) * mm4, 2) + reply["principal_moments_mm4"] = [round(float(v) * mm4, 2) for v in values[13:15]] + return reply + + +def transform_reply(array: Any) -> dict[str, Any]: + """A coordinate system's origin and axes from its transform's ``ArrayData``. + + Args: + array: SolidWorks's 16 values: the 3x3 rotation by rows, the origin + (m), the scale and three unused. + + Returns: + dict[str, Any]: ``origin_mm`` and ``x_axis``, ``y_axis``, ``z_axis``. + + Raises: + RuntimeError: The transform couldn't be read. + """ + if not isinstance(array, (list, tuple)) or len(array) < 12: + raise RuntimeError("Could not read the coordinate system's transform.") + axes = [[round(float(v), 6) + 0.0 for v in array[i : i + 3]] for i in (0, 3, 6)] + return { + "origin_mm": [round(float(v) * 1000, 4) for v in array[9:12]], + "x_axis": axes[0], + "y_axis": axes[1], + "z_axis": axes[2], + } + + +def model_axes() -> dict[str, list[float]]: + """The axes of a coordinate system along the model's. + + Returns: + dict[str, list[float]]: ``x_axis``, ``y_axis`` and ``z_axis``. + """ + return { + "x_axis": [1.0, 0.0, 0.0], + "y_axis": [0.0, 1.0, 0.0], + "z_axis": [0.0, 0.0, 1.0], + } diff --git a/src/solidworks_mcp/adapters/base.py b/src/solidworks_mcp/adapters/base.py index a43b5772..f7628ea4 100644 --- a/src/solidworks_mcp/adapters/base.py +++ b/src/solidworks_mcp/adapters/base.py @@ -397,6 +397,64 @@ class ScaleBodyParameters(BaseModel): bodies: list[str] | None = None +class AppearanceTarget(BaseModel): + """What a colour is read from or set on: one of these, or none for the part. + + Attributes: + feature (str | None): A feature, by its name in the tree. + body (str | None): A solid body, as ``list_bodies`` names it. + face_point (list[float] | None): ``[x, y, z]`` mm on a face. + """ + + feature: str | None = None + body: str | None = None + face_point: list[float] | None = None + + +class AppearanceParameters(AppearanceTarget): + """A colour to set on a target, or ``reset`` to remove the target's own. + + Attributes: + color (list[int] | str | None): ``[r, g, b]`` 0-255 or ``#rrggbb``. + transparency (float): 0 opaque to 1 clear. + reset (bool): Remove the target's own colour instead. + """ + + color: list[int] | str | None = None + transparency: float = 0.0 + reset: bool = False + + +class CoordinateSystemParameters(BaseModel): + """A coordinate system at a point, with the model's axes. + + Attributes: + origin (list[float]): ``[x, y, z]`` mm. + """ + + origin: list[float] + + +class BoundingBoxParameters(BaseModel): + """SolidWorks's Bounding Box feature around the part's bodies. + + Attributes: + include_hidden (bool): Include hidden bodies. + """ + + include_hidden: bool = False + + +class SectionPropertiesParameters(BaseModel): + """A planar face, picked by a point on it. + + Attributes: + face_point (list[float]): ``[x, y, z]`` mm on the face. + """ + + face_point: list[float] + + class LoftParameters(BaseModel): """Parameters for loft operations. @@ -926,6 +984,97 @@ async def scale_body( error="scale_body is not implemented by this adapter", ) + async def set_appearance( + self, params: AppearanceParameters + ) -> AdapterResult[dict[str, Any]]: + """Colour the part, a feature, a body or a face, or remove a colour. + + Args: + params: The target, the colour and transparency, or ``reset``. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="set_appearance is not implemented by this adapter", + ) + + async def get_appearance( + self, params: AppearanceTarget + ) -> AdapterResult[dict[str, Any]]: + """Read the colour a target shows, and the level it comes from. + + Args: + params: The target; none for the part. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="get_appearance is not implemented by this adapter", + ) + + async def create_coordinate_system( + self, params: CoordinateSystemParameters + ) -> AdapterResult[dict[str, Any]]: + """A coordinate system at a point, with the model's axes. + + Args: + params: The origin. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="create_coordinate_system is not implemented by this adapter", + ) + + async def create_center_of_mass_point(self) -> AdapterResult[dict[str, Any]]: + """SolidWorks's Center of Mass reference point on the active part. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="create_center_of_mass_point is not implemented by this adapter", + ) + + async def create_bounding_box( + self, params: BoundingBoxParameters + ) -> AdapterResult[dict[str, Any]]: + """SolidWorks's Bounding Box feature around the part's bodies. + + Args: + params: Whether to include hidden bodies. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="create_bounding_box is not implemented by this adapter", + ) + + async def get_section_properties( + self, params: SectionPropertiesParameters + ) -> AdapterResult[dict[str, Any]]: + """Area, centroid and second moments of area of a planar face. + + Args: + params: A point on the face. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="get_section_properties is not implemented by this adapter", + ) + @abstractmethod async def create_loft( self, params: LoftParameters diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index d91b92db..8d3a0e41 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -17,7 +17,11 @@ AdapterHealth, AdapterResult, AdapterResultStatus, + AppearanceParameters, + AppearanceTarget, + BoundingBoxParameters, CombineBodiesParameters, + CoordinateSystemParameters, DeleteBodiesParameters, ExtrusionParameters, HelixParameters, @@ -26,6 +30,7 @@ MoveCopyBodyParameters, RevolveParameters, ScaleBodyParameters, + SectionPropertiesParameters, SolidWorksAdapter, SolidWorksFeature, SolidWorksModel, @@ -1353,6 +1358,64 @@ async def scale_body( input_dict=_to_input_dict(params), ) + async def set_appearance( + self, params: AppearanceParameters + ) -> AdapterResult[dict[str, Any]]: + """Colour a target, or remove its colour. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "set_appearance", + lambda: self.adapter.set_appearance(params), + input_dict=_to_input_dict(params), + ) + + async def get_appearance( + self, params: AppearanceTarget + ) -> AdapterResult[dict[str, Any]]: + """Read a target's colour. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "get_appearance", + lambda: self.adapter.get_appearance(params), + input_dict=_to_input_dict(params), + ) + + async def create_coordinate_system( + self, params: CoordinateSystemParameters + ) -> AdapterResult[dict[str, Any]]: + """A coordinate system at a point. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "create_coordinate_system", + lambda: self.adapter.create_coordinate_system(params), + input_dict=_to_input_dict(params), + ) + + async def create_center_of_mass_point(self) -> AdapterResult[dict[str, Any]]: + """The Center of Mass point. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "create_center_of_mass_point", + lambda: self.adapter.create_center_of_mass_point(), + input_dict={}, + ) + + async def create_bounding_box( + self, params: BoundingBoxParameters + ) -> AdapterResult[dict[str, Any]]: + """The Bounding Box feature. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "create_bounding_box", + lambda: self.adapter.create_bounding_box(params), + input_dict=_to_input_dict(params), + ) + + async def get_section_properties( + self, params: SectionPropertiesParameters + ) -> AdapterResult[dict[str, Any]]: + """A face's section properties. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "get_section_properties", + lambda: self.adapter.get_section_properties(params), + input_dict=_to_input_dict(params), + ) + async def create_loft( self, params: LoftParameters ) -> AdapterResult[SolidWorksFeature]: diff --git a/src/solidworks_mcp/adapters/connection_pool.py b/src/solidworks_mcp/adapters/connection_pool.py index 26dfea53..5a3143e7 100644 --- a/src/solidworks_mcp/adapters/connection_pool.py +++ b/src/solidworks_mcp/adapters/connection_pool.py @@ -16,7 +16,11 @@ AdapterHealth, AdapterResult, AdapterResultStatus, + AppearanceParameters, + AppearanceTarget, + BoundingBoxParameters, CombineBodiesParameters, + CoordinateSystemParameters, DeleteBodiesParameters, ExtrusionParameters, HelixParameters, @@ -25,6 +29,7 @@ MoveCopyBodyParameters, RevolveParameters, ScaleBodyParameters, + SectionPropertiesParameters, SolidWorksAdapter, SolidWorksFeature, SolidWorksModel, @@ -1171,6 +1176,55 @@ async def scale_body( "scale_body", lambda adapter: adapter.scale_body(params) ) + async def set_appearance( + self, params: AppearanceParameters + ) -> AdapterResult[dict[str, Any]]: + """Colour a target, or remove its colour. Using the pool.""" + return await self._execute_with_pool( + "set_appearance", lambda adapter: adapter.set_appearance(params) + ) + + async def get_appearance( + self, params: AppearanceTarget + ) -> AdapterResult[dict[str, Any]]: + """Read a target's colour. Using the pool.""" + return await self._execute_with_pool( + "get_appearance", lambda adapter: adapter.get_appearance(params) + ) + + async def create_coordinate_system( + self, params: CoordinateSystemParameters + ) -> AdapterResult[dict[str, Any]]: + """A coordinate system at a point. Using the pool.""" + return await self._execute_with_pool( + "create_coordinate_system", + lambda adapter: adapter.create_coordinate_system(params), + ) + + async def create_center_of_mass_point(self) -> AdapterResult[dict[str, Any]]: + """The Center of Mass point. Using the pool.""" + return await self._execute_with_pool( + "create_center_of_mass_point", + lambda adapter: adapter.create_center_of_mass_point(), + ) + + async def create_bounding_box( + self, params: BoundingBoxParameters + ) -> AdapterResult[dict[str, Any]]: + """The Bounding Box feature. Using the pool.""" + return await self._execute_with_pool( + "create_bounding_box", lambda adapter: adapter.create_bounding_box(params) + ) + + async def get_section_properties( + self, params: SectionPropertiesParameters + ) -> AdapterResult[dict[str, Any]]: + """A face's section properties. Using the pool.""" + return await self._execute_with_pool( + "get_section_properties", + lambda adapter: adapter.get_section_properties(params), + ) + async def create_loft( self, params: LoftParameters ) -> AdapterResult[SolidWorksFeature]: diff --git a/src/solidworks_mcp/adapters/mock_adapter.py b/src/solidworks_mcp/adapters/mock_adapter.py index 1b1e5a69..d278aefd 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -29,9 +29,11 @@ SolidWorksFeature, SolidWorksModel, ) +from .mock_appearance import MockAppearanceMixin from .mock_bodies import MockBodiesMixin from .mock_drawing_pack import MockDrawingPackMixin from .mock_equations import MockEquationsMixin +from .mock_reference_extras import MockReferenceExtrasMixin from .mock_sheet_metal import MockSheetMetalMixin from .mock_swept import MockSweptMixin from .mock_templates import MockTemplatesMixin @@ -145,6 +147,8 @@ def __bool__(self) -> bool: class MockSolidWorksAdapter( + MockAppearanceMixin, + MockReferenceExtrasMixin, MockBodiesMixin, MockSheetMetalMixin, MockSweptMixin, diff --git a/src/solidworks_mcp/adapters/mock_appearance.py b/src/solidworks_mcp/adapters/mock_appearance.py new file mode 100644 index 00000000..5392fff5 --- /dev/null +++ b/src/solidworks_mcp/adapters/mock_appearance.py @@ -0,0 +1,192 @@ +"""The mock adapter's colours (queue item 36). + +Colours are held per open part, by level: the part's, each feature's, each +body's and each face's (a face by the point that picked it, on one of the +mock's box bodies, :mod:`mock_bodies`). A face belongs to the body whose box +it lies on, and to the feature of the same name, as the mock names a body +after the feature that made it. Refusals use the real adapter's rules +(:mod:`appearance_rules`). +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from ..exceptions import InputRefused +from . import appearance_rules as rules +from . import body_rules +from .base import ( + AdapterResult, + AdapterResultStatus, + AppearanceParameters, + AppearanceTarget, +) +from .body_rules import BodyState + +#: A new part's colour, as SolidWorks 2026 reads it. +_DEFAULT_PART = [0.894118, 0.894118, 0.894118, 1.0, 1.0, 0.5, 0.3125, 0.0, 0.0] +#: How close a point must be to a box's face to lie on it, mm. +_ON_FACE = 1e-6 + + +def _error(message: str) -> AdapterResult[Any]: + """An error result.""" + return AdapterResult(status=AdapterResultStatus.ERROR, error=message) + + +def face_of(bodies: list[BodyState], point: list[float]) -> tuple[BodyState, int, int]: + """The box face a point lies on: the body, the face's normal axis and side. + + Args: + bodies: The part's box bodies. + point: ``[x, y, z]`` mm. + + Returns: + tuple[BodyState, int, int]: The body, the axis (0-2) the face is + normal to, and 0 for its low side or 1 for its high side. + + Raises: + InputRefused: The point lies on no face. + """ + for body in bodies: + inside = all( + body.box_min[i] - _ON_FACE <= point[i] <= body.box_max[i] + _ON_FACE + for i in range(3) + ) + if not inside: + continue + for axis in range(3): + for side, plane in enumerate((body.box_min[axis], body.box_max[axis])): + if abs(point[axis] - plane) <= _ON_FACE: + return body, axis, side + raise InputRefused( + f"No face at {list(point)} mm; give a point on the face's surface." + ) + + +class MockAppearanceMixin: + """``set_appearance`` and ``get_appearance``, in memory.""" + + _current_model: Any + _features: dict[str, Any] + #: From :class:`MockBodiesMixin`: the active part's box bodies. + _bodies: Callable[[], list[BodyState]] + + def _colour_store(self) -> dict[tuple[int, str, str], list[float]]: + """Each part's colours by ``(part, level, key)``.""" + if "_mock_colours" not in self.__dict__: + self._mock_colours: dict[tuple[int, str, str], list[float]] = {} + return self._mock_colours + + def _resolve_target( + self, kind: str, target: AppearanceTarget + ) -> list[tuple[str, str]]: + """The target and the levels above it, as ``(level, key)``, nearest first. + + Raises: + InputRefused: The feature, body or face isn't there. + """ + if kind == "feature": + names = [f.name for f in self._features.values()] + if target.feature not in names: + raise InputRefused( + f"No feature named '{target.feature}'; list_features names them." + ) + return [("feature", str(target.feature)), ("part", "")] + if kind == "body": + real = body_rules.resolve_bodies(self._bodies(), [str(target.body)])[0] + return [("body", real), ("part", "")] + if kind == "face": + point = list(target.face_point or []) + body, axis, side = face_of(self._bodies(), point) + return [ + ("face", f"{body.name}:{axis}:{side}"), + ("feature", body.name), + ("body", body.name), + ("part", ""), + ] + return [("part", "")] + + def _values(self, level: str, key: str) -> list[float] | None: + """A level's own colour; the part has the default when unset.""" + own = self._colour_store().get((id(self._current_model), level, key)) + if own is None and level == "part": + return list(_DEFAULT_PART) + return own + + def _showing(self, chain: list[tuple[str, str]]) -> dict[str, Any]: + """The colour that shows, walking up the chain. + + Every chain ends at the part, which always has a colour here. + """ + level, color = next( + (level, color) + for level, key in chain + if (color := rules.color_reply(self._values(level, key))) is not None + ) + return {**color, "level": level} + + def _named(self, kind: str, target: AppearanceTarget) -> dict[str, Any]: + """The reply field naming the target.""" + field = {"feature": "feature", "body": "body", "face": "face_point"}.get(kind) + return {field: getattr(target, field)} if field else {} + + async def set_appearance( + self, params: AppearanceParameters + ) -> AdapterResult[dict[str, Any]]: + """Mock: colour a target, or remove its colour. + + Args: + params: The target, the colour and transparency, or ``reset``. + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + try: + kind = rules.check_set(params) + chain = self._resolve_target(kind, params) + except InputRefused as refused: + return _error(str(refused)) + level, key = chain[0] + store = self._colour_store() + if params.reset: + store.pop((id(self._current_model), level, key), None) + reply: dict[str, Any] = {"reset": True, "showing": self._showing(chain)} + else: + rgb = rules.parse_color(params.color) + store[(id(self._current_model), level, key)] = rules.material_values( + rgb, params.transparency + ) + reply = dict( + rules.color_reply(store[(id(self._current_model), level, key)]) or {} + ) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"target": kind, **self._named(kind, params), **reply}, + ) + + async def get_appearance( + self, params: AppearanceTarget + ) -> AdapterResult[dict[str, Any]]: + """Mock: the colour a target shows and its level. + + Args: + params: The target; none for the part. + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + try: + kind = rules.target_kind(params) + chain = self._resolve_target(kind, params) + except InputRefused as refused: + return _error(str(refused)) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={"target": kind, **self._named(kind, params), **self._showing(chain)}, + ) diff --git a/src/solidworks_mcp/adapters/mock_bodies.py b/src/solidworks_mcp/adapters/mock_bodies.py index 30bb941e..47452384 100644 --- a/src/solidworks_mcp/adapters/mock_bodies.py +++ b/src/solidworks_mcp/adapters/mock_bodies.py @@ -183,7 +183,7 @@ async def _body_operation( operation: str, change: Callable[[list[BodyState], str], list[BodyState]], verdict: Callable[[list[BodyState], list[BodyState]], tuple[str, bool]], - extra: Callable[[], dict[str, Any]], + own_fields: Callable[[], dict[str, Any]], ) -> AdapterResult[dict[str, Any]]: """Apply one body operation and judge it by its rule. @@ -193,7 +193,7 @@ async def _body_operation( change: Gives the bodies after, from those before and the feature's name; raises InputRefused to refuse. verdict: The rule: the expectation in words and whether it held. - extra: The reply's own fields, read after ``change``. + own_fields: The reply's own fields, read after ``change``. Returns: AdapterResult[dict[str, Any]]: The measured reply, or the @@ -217,7 +217,7 @@ async def _body_operation( self._body_store()[id(self._current_model)] = after return AdapterResult( status=AdapterResultStatus.SUCCESS, - data={**rules.measured_reply(feature, before, after), **extra()}, + data={**rules.measured_reply(feature, before, after), **own_fields()}, execution_time=self._delays["feature_operation"], ) diff --git a/src/solidworks_mcp/adapters/mock_reference_extras.py b/src/solidworks_mcp/adapters/mock_reference_extras.py new file mode 100644 index 00000000..6000c793 --- /dev/null +++ b/src/solidworks_mcp/adapters/mock_reference_extras.py @@ -0,0 +1,215 @@ +"""The mock adapter's reference and analysis extras (queue item 39). + +Worked out from the mock's box bodies (:mod:`mock_bodies`): + +- the centre of mass is the volume-weighted centre of the boxes; +- the bounding box is the box around them; +- a face's section is a rectangle (the box face the point lies on), its + second moments those of a rectangle about its centroid; +- a coordinate system has the model's axes. + +A part has one Center of Mass point and one bounding box at most, as on +SolidWorks. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from ..exceptions import InputRefused +from . import appearance_rules as rules +from .base import ( + AdapterResult, + AdapterResultStatus, + BoundingBoxParameters, + CoordinateSystemParameters, + SectionPropertiesParameters, +) +from .body_rules import BodyState +from .mock_appearance import face_of + + +def _error(message: str) -> AdapterResult[Any]: + """An error result.""" + return AdapterResult(status=AdapterResultStatus.ERROR, error=message) + + +def _ok(data: dict[str, Any]) -> AdapterResult[dict[str, Any]]: + """A success result.""" + return AdapterResult(status=AdapterResultStatus.SUCCESS, data=data) + + +def rectangle_section(body: BodyState, axis: int, side: int) -> dict[str, Any]: + """A box face's section properties, in mm, as ``section_reply`` gives them. + + Args: + body: The box. + axis: The axis the face is normal to. + side: 0 for the box's low face, 1 for its high face. + + Returns: + dict[str, Any]: ``area_mm2``, ``centroid_mm``, the six moments, + ``polar_moment_mm4`` and ``principal_moments_mm4``. + """ + lengths = [body.box_max[i] - body.box_min[i] for i in range(3)] + lengths[axis] = 0.0 + centroid = [(body.box_min[i] + body.box_max[i]) / 2 for i in range(3)] + centroid[axis] = (body.box_min[axis], body.box_max[axis])[side] + area = 1.0 + for i in range(3): + if i != axis: + area *= lengths[i] + # S_j: the integral of the squared distance along axis j over the face. + spread = [area * length**2 / 12 for length in lengths] + moments = [sum(spread[j] for j in range(3) if j != i) for i in range(3)] + in_plane = sorted(moments[i] for i in range(3) if i != axis) + return { + "area_mm2": round(area, 4), + "centroid_mm": [round(v, 4) for v in centroid], + "ixx": round(moments[0], 2), + "iyy": round(moments[1], 2), + "izz": round(moments[2], 2), + "ixy": 0.0, + "izx": 0.0, + "iyz": 0.0, + "polar_moment_mm4": round(moments[axis], 2), + "principal_moments_mm4": [round(v, 2) for v in in_plane], + } + + +class MockReferenceExtrasMixin: + """Coordinate system, centre of mass, bounding box, section properties.""" + + _current_model: Any + #: From :class:`MockBodiesMixin`: the active part's box bodies. + _bodies: Callable[[], list[BodyState]] + + def _reference_store(self) -> dict[int, dict[str, Any]]: + """Each part's coordinate-system count, COM point and bounding box.""" + if "_mock_reference" not in self.__dict__: + self._mock_reference: dict[int, dict[str, Any]] = {} + return self._mock_reference + + def _part_reference(self) -> dict[str, Any]: + """The active part's entry.""" + return self._reference_store().setdefault( + id(self._current_model), {"systems": 0} + ) + + async def create_coordinate_system( + self, params: CoordinateSystemParameters + ) -> AdapterResult[dict[str, Any]]: + """Mock: a coordinate system at a point. + + Args: + params: The origin (mm). + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + if len(params.origin) != 3: + return _error("origin must be [x, y, z] in mm.") + entry = self._part_reference() + entry["systems"] += 1 + count = entry["systems"] + return _ok( + { + "name": f"Coordinate System{count}", + "sketch": f"3DSketch{count}", + "origin_mm": [float(v) for v in params.origin], + **rules.model_axes(), + } + ) + + async def create_center_of_mass_point(self) -> AdapterResult[dict[str, Any]]: + """Mock: the Center of Mass point. + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + bodies = self._bodies() + if not bodies: + return _error("The part has no solid body, so no centre of mass.") + entry = self._part_reference() + if entry.get("com"): + return _error( + "The part has a Center of Mass point already ('Center of Mass'); " + "a part has one at most." + ) + entry["com"] = True + total = sum(b.volume for b in bodies) + centre = [ + sum(b.volume * (b.box_min[i] + b.box_max[i]) / 2 for b in bodies) / total + for i in range(3) + ] + return _ok( + { + "name": "Center of Mass", + "center_of_mass_mm": [round(v, 4) for v in centre], + } + ) + + async def create_bounding_box( + self, params: BoundingBoxParameters + ) -> AdapterResult[dict[str, Any]]: + """Mock: the Bounding Box feature. + + Args: + params: Whether to include hidden bodies (the mock has none). + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + bodies = self._bodies() + if not bodies: + return _error("The part has no solid body to box.") + entry = self._part_reference() + if entry.get("box"): + return _error( + "The part has a bounding box already ('Bounding Box'); a part " + "has one at most." + ) + entry["box"] = True + low = [min(b.box_min[i] for b in bodies) for i in range(3)] + high = [max(b.box_max[i] for b in bodies) for i in range(3)] + return _ok( + { + "name": "Bounding Box", + "size_mm": [round(high[i] - low[i], 4) for i in range(3)], + "min_mm": low, + "max_mm": high, + } + ) + + async def get_section_properties( + self, params: SectionPropertiesParameters + ) -> AdapterResult[dict[str, Any]]: + """Mock: a box face's section properties. + + Args: + params: A point on the face (mm). + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + if len(params.face_point) != 3: + return _error("face_point must be [x, y, z] in mm.") + try: + body, axis, side = face_of(self._bodies(), list(params.face_point)) + except InputRefused as refused: + return _error(str(refused)) + return _ok( + { + "face_point": list(params.face_point), + **rectangle_section(body, axis, side), + } + ) diff --git a/src/solidworks_mcp/adapters/pywin32_adapter.py b/src/solidworks_mcp/adapters/pywin32_adapter.py index 1192a29e..55067365 100644 --- a/src/solidworks_mcp/adapters/pywin32_adapter.py +++ b/src/solidworks_mcp/adapters/pywin32_adapter.py @@ -25,6 +25,7 @@ SolidWorksAdapter, ) from .solidworks import ( + SolidWorksAppearanceMixin, SolidWorksAssemblyMixin, SolidWorksBodiesMixin, SolidWorksConfigurationsMixin, @@ -35,6 +36,7 @@ SolidWorksFeaturesMixin, SolidWorksIOMixin, SolidWorksPartFeaturesMixin, + SolidWorksReferenceExtrasMixin, SolidWorksSelectionMixin, SolidWorksSheetMetalMixin, SolidWorksSketchMixin, @@ -1724,6 +1726,8 @@ def _is_feature_suppressed(self, feature: Any) -> bool: class PyWin32Adapter( + SolidWorksAppearanceMixin, + SolidWorksReferenceExtrasMixin, SolidWorksAssemblyMixin, SolidWorksBodiesMixin, SolidWorksSheetMetalMixin, diff --git a/src/solidworks_mcp/adapters/solidworks/__init__.py b/src/solidworks_mcp/adapters/solidworks/__init__.py index 74b88d9c..85c03529 100644 --- a/src/solidworks_mcp/adapters/solidworks/__init__.py +++ b/src/solidworks_mcp/adapters/solidworks/__init__.py @@ -1,5 +1,6 @@ """Grouped SolidWorks mixins for the PyWin32 adapter.""" +from .appearance import SolidWorksAppearanceMixin from .assembly import SolidWorksAssemblyMixin from .bodies import SolidWorksBodiesMixin from .configurations import SolidWorksConfigurationsMixin @@ -10,6 +11,7 @@ from .features import SolidWorksFeaturesMixin from .io import SolidWorksIOMixin from .part_features import SolidWorksPartFeaturesMixin +from .reference_extras import SolidWorksReferenceExtrasMixin from .selection import SolidWorksSelectionMixin from .sheet_metal import SolidWorksSheetMetalMixin from .sketch import SolidWorksSketchMixin @@ -17,6 +19,7 @@ from .templates import SolidWorksTemplatesMixin __all__ = [ + "SolidWorksAppearanceMixin", "SolidWorksAssemblyMixin", "SolidWorksBodiesMixin", "SolidWorksConfigurationsMixin", @@ -27,6 +30,7 @@ "SolidWorksFeaturesMixin", "SolidWorksIOMixin", "SolidWorksPartFeaturesMixin", + "SolidWorksReferenceExtrasMixin", "SolidWorksSelectionMixin", "SolidWorksSheetMetalMixin", "SolidWorksSketchMixin", diff --git a/src/solidworks_mcp/adapters/solidworks/appearance.py b/src/solidworks_mcp/adapters/solidworks/appearance.py new file mode 100644 index 00000000..9fe5480a --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/appearance.py @@ -0,0 +1,269 @@ +"""Colours on SolidWorks: set, remove and read a part's, feature's, body's or face's. + +A colour is SolidWorks's nine material values, passed as a ``VT_R8`` array +(a plain list is misread). Each level has its own call, measured on +SolidWorks 2026 (design.md of the ``appearance-and-reference-tools`` change): + +- part: ``IModelDoc2.MaterialPropertyValues`` (a property); +- feature: ``IFeature.SetMaterialPropertyValues2`` / + ``GetMaterialPropertyValues2`` / ``RemoveMaterialProperty2`` (nine ``-1`` + when it has none); +- body: ``IBody2.MaterialPropertyValues2`` / ``RemoveMaterialProperty``; +- face: ``IFace2.MaterialPropertyValues`` (``None`` when it has none) / + ``RemoveMaterialProperty2``. + +Every call runs inside :meth:`_handle_com_operation`, on the connect thread. +""" + +from __future__ import annotations + +from typing import Any, cast + +from ...exceptions import InputRefused +from .. import appearance_rules as rules +from .. import body_rules, sw_type_info +from ..base import ( + AdapterResult, + AdapterResultStatus, + AppearanceParameters, + AppearanceTarget, +) +from .com_utils import double_array +from .features import _null_callout + +#: ``swInConfigurationOpts_e.swThisConfiguration``. +_THIS_CONFIGURATION = 1 + + +class SolidWorksAppearanceMixin: + """``set_appearance`` and ``get_appearance`` on SolidWorks.""" + + def _face_at(self, point: list[float]) -> Any: + """The face at ``point`` (mm), with the selection cleared after. + + Args: + point: ``[x, y, z]`` mm on the face. + + Returns: + Any: The ``IFace2`` dispatch. + + Raises: + InputRefused: No face lies at the point. + """ + adapter: Any = self + face = select_face_at(adapter, point) + adapter._attempt(lambda: adapter.currentModel.ClearSelection2(True)) + return face + + def _feature_named(self, name: str) -> Any: + """The feature ``name``, flagged, or a refusal.""" + adapter: Any = self + feature = adapter._attempt(lambda: adapter.currentModel.FeatureByName(name)) + if feature is None: + raise InputRefused(f"No feature named '{name}'; list_features names them.") + return sw_type_info.flagged(feature, "IFeature") + + def _body_named(self, name: str) -> Any: + """The body ``name`` (ignoring case), flagged, or a refusal listing them.""" + adapter: Any = self + measured = adapter._measure_bodies() + real = body_rules.resolve_bodies([state for state, _ in measured], [name])[0] + body = next(body for state, body in measured if state.name == real) + return sw_type_info.flagged(body, "IBody2") + + def _appearance_target(self, kind: str, target: AppearanceTarget) -> Any: + """The dispatch a target names: the model, a feature, a body or a face.""" + adapter: Any = self + if kind == "feature": + return self._feature_named(str(target.feature)) + if kind == "body": + return self._body_named(str(target.body)) + if kind == "face": + return self._face_at(list(target.face_point or [])) + return adapter.currentModel + + def _own_values(self, kind: str, dispatch: Any) -> Any: + """The target's own nine material values, or None/-1s when it has none.""" + adapter: Any = self + readers = { + "part": lambda: dispatch.MaterialPropertyValues, + "feature": lambda: dispatch.GetMaterialPropertyValues2( + _THIS_CONFIGURATION, None + ), + "body": lambda: dispatch.MaterialPropertyValues2, + "face": lambda: dispatch.MaterialPropertyValues, + } + return adapter._attempt(readers[kind]) + + def _write_values(self, kind: str, dispatch: Any, values: list[float]) -> None: + """Set the target's own colour.""" + array = double_array(values) + if kind == "feature": + dispatch.SetMaterialPropertyValues2(array, _THIS_CONFIGURATION, None) + elif kind == "body": + dispatch.MaterialPropertyValues2 = array + else: + dispatch.MaterialPropertyValues = array + + def _remove_values(self, kind: str, dispatch: Any) -> None: + """Remove a feature's, body's or face's own colour.""" + if kind == "body": + dispatch.RemoveMaterialProperty(_THIS_CONFIGURATION, None) + else: + dispatch.RemoveMaterialProperty2(_THIS_CONFIGURATION, None) + + def _showing(self, kind: str, dispatch: Any) -> dict[str, Any]: + """The colour a target shows and the level it comes from. + + Walks up from the target in SolidWorks's order (face, feature, body, + part) until a level has a colour of its own. + """ + adapter: Any = self + chain: list[tuple[str, Any]] = [(kind, dispatch)] + if kind == "face": + feature = adapter._attempt(lambda: dispatch.GetFeature()) + body = adapter._attempt(lambda: dispatch.GetBody()) + if feature is not None: + chain.append(("feature", sw_type_info.flagged(feature, "IFeature"))) + if body is not None: + chain.append(("body", sw_type_info.flagged(body, "IBody2"))) + if kind != "part": + chain.append(("part", adapter.currentModel)) + for level, item in chain: + color = rules.color_reply(self._own_values(level, item)) + if color is not None: + return {**color, "level": level} + return {"color": None, "hex": None, "transparency": None, "level": None} + + def _appearance_call( + self, + operation: str, + target: AppearanceTarget, + act: Any, + check: Any = rules.target_kind, + ) -> AdapterResult[dict[str, Any]]: + """Run ``act(kind, dispatch)`` for the target inside the COM boundary. + + Args: + operation: The operation's name, for the boundary and errors. + target: The call's target fields. + act: Does the work on the target's dispatch; returns reply fields. + check: Refuses the call before anything is touched; returns the + target's kind. + + Returns: + AdapterResult[dict[str, Any]]: ``target``, its name or point and + ``act``'s fields. + """ + adapter: Any = self + if not adapter.currentModel: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active model" + ) + + def build() -> dict[str, Any]: + kind = check(target) + dispatch = self._appearance_target(kind, target) + reply = act(kind, dispatch) + adapter._attempt(lambda: adapter.currentModel.GraphicsRedraw2()) + return {"target": kind, **_target_name(kind, target), **reply} + + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation(operation, build), + ) + + async def set_appearance( + self, params: AppearanceParameters + ) -> AdapterResult[dict[str, Any]]: + """Colour the part, a feature, a body or a face, or remove a colour. + + Args: + params: The target, the colour and transparency, or ``reset``. + + Returns: + AdapterResult[dict[str, Any]]: The target and the colour read + back; for a reset, ``color`` None and what now ``showing``. + """ + + def act(kind: str, dispatch: Any) -> dict[str, Any]: + if params.reset: + self._remove_values(kind, dispatch) + return {"reset": True, "showing": self._showing(kind, dispatch)} + rgb = rules.parse_color(params.color) + self._write_values( + kind, dispatch, rules.material_values(rgb, params.transparency) + ) + read = rules.color_reply(self._own_values(kind, dispatch)) + if read is None: + raise RuntimeError(f"SolidWorks did not keep the colour on the {kind}.") + return read + + return self._appearance_call( + "set_appearance", params, act, check=lambda _: rules.check_set(params) + ) + + async def get_appearance( + self, params: AppearanceTarget + ) -> AdapterResult[dict[str, Any]]: + """Read the colour a target shows, and the level it comes from. + + Args: + params: The target; none for the part. + + Returns: + AdapterResult[dict[str, Any]]: ``color``, ``hex``, + ``transparency`` and ``level``. + """ + return self._appearance_call( + "get_appearance", + params, + lambda kind, dispatch: self._showing(kind, dispatch), + ) + + +def _target_name(kind: str, target: AppearanceTarget) -> dict[str, Any]: + """The reply field naming the target: its name or point.""" + if kind == "feature": + return {"feature": target.feature} + if kind == "body": + return {"body": target.body} + if kind == "face": + return {"face_point": target.face_point} + return {} + + +def select_face_at(adapter: Any, point: list[float]) -> Any: + """Select the face at ``point`` (mm) and return it, left selected. + + Args: + adapter: The connected adapter. + point: ``[x, y, z]`` mm on the face. + + Returns: + Any: The ``IFace2`` dispatch, still selected. + + Raises: + InputRefused: No face lies at the point. + """ + model = adapter.currentModel + # New faces are not selectable by coordinates until a rebuild + # (COM pitfall #13). + adapter._attempt(lambda: model.ForceRebuild3(True)) + adapter._attempt(lambda: model.ClearSelection2(True)) + extension = sw_type_info.flagged(model.Extension, "IModelDocExtension") + x, y, z = (float(v) / 1000.0 for v in point) + picked = adapter._attempt( + lambda: extension.SelectByID2( + "", "FACE", x, y, z, False, 0, _null_callout(), 0 + ), + default=False, + ) + manager = sw_type_info.flagged(model.SelectionManager, "ISelectionMgr") + face = adapter._attempt(lambda: manager.GetSelectedObject6(1, -1)) + if not picked or face is None: + adapter._attempt(lambda: model.ClearSelection2(True)) + raise InputRefused( + f"No face at {list(point)} mm; give a point on the face's surface." + ) + return sw_type_info.flagged(face, "IFace2") diff --git a/src/solidworks_mcp/adapters/solidworks/bodies.py b/src/solidworks_mcp/adapters/solidworks/bodies.py index ded4fbef..a22351e7 100644 --- a/src/solidworks_mcp/adapters/solidworks/bodies.py +++ b/src/solidworks_mcp/adapters/solidworks/bodies.py @@ -167,7 +167,7 @@ def _body_operation( operation: str, act: Callable[[list[Measured]], tuple[Any, str]], verdict: Callable[[list[BodyState], list[BodyState]], tuple[str, bool]], - extra: Callable[[list[BodyState], list[BodyState]], dict[str, Any]], + own_fields: Callable[[list[BodyState], list[BodyState]], dict[str, Any]], ) -> AdapterResult[dict[str, Any]]: """Measure, act, measure again and judge one body operation. @@ -177,7 +177,7 @@ def _body_operation( when SolidWorks made nothing) and what it did in words, for the "made nothing" message. Raises InputRefused to refuse. verdict: The rule: the expectation in words and whether it held. - extra: The reply's own fields, from the bodies before and after. + own_fields: The reply's own fields, from the bodies before and after. Returns: AdapterResult[dict[str, Any]]: The measured reply, or the refusal. @@ -208,7 +208,7 @@ def build() -> dict[str, Any]: raise RuntimeError(failed) return { **rules.measured_reply(name, before, after), - **extra(before, after), + **own_fields(before, after), } return cast( diff --git a/src/solidworks_mcp/adapters/solidworks/com_utils.py b/src/solidworks_mcp/adapters/solidworks/com_utils.py index 838ae0a6..548636a8 100644 --- a/src/solidworks_mcp/adapters/solidworks/com_utils.py +++ b/src/solidworks_mcp/adapters/solidworks/com_utils.py @@ -114,3 +114,18 @@ def dispatch_array(values: list[Any]) -> Any: return w32.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, list(values)) except ImportError: # non-Windows return tuple(values) + + +def long_ref(value: int = 0) -> Any: + """``VARIANT(VT_BYREF | VT_I4)`` for a ``Long`` out-parameter (int when pywin32 is absent). + + ``IFeatureManager.InsertGlobalBoundingBox``'s ``Status`` is a type + mismatch as a plain int (checked on SolidWorks 2026). + """ + try: + import pythoncom + import win32com.client as w32 + + return w32.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, int(value)) + except ImportError: # non-Windows + return int(value) diff --git a/src/solidworks_mcp/adapters/solidworks/reference_extras.py b/src/solidworks_mcp/adapters/solidworks/reference_extras.py new file mode 100644 index 00000000..5ca91c72 --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/reference_extras.py @@ -0,0 +1,258 @@ +"""Reference and analysis extras on SolidWorks (queue item 39). + +A coordinate system at a point, the Center of Mass point, the Bounding Box +feature and a face's section properties. How each call behaves was measured +on SolidWorks 2026 (design.md of the ``appearance-and-reference-tools`` +change): + +- ``InsertCoordinateSystem(xFlip, yFlip, zFlip)`` takes its origin selected + with mark 1; with no axes selected they lie along the model's, and the + three flip flags are ignored (checked live: ``True`` for z left +z). The origin + is a point in a 3D sketch drawn for it, selected as ``Point1@``. + The transform reads back via ``GetCoordinateSystemTransformByName``. +- ``InsertCenterOfMass()``; the centre from ``CreateMassProperty`` on the + flagged extension. +- ``InsertGlobalBoundingBox(0, hidden, surfaces, status)`` with ``status`` + passed by reference. +- ``GetSectionProperties2(None)`` reads the selected face. + +Every call runs inside :meth:`_handle_com_operation`, on the connect thread. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, cast + +from ...exceptions import InputRefused +from .. import appearance_rules as rules +from .. import sw_type_info +from ..base import ( + AdapterResult, + AdapterResultStatus, + BoundingBoxParameters, + CoordinateSystemParameters, + SectionPropertiesParameters, +) +from .appearance import select_face_at +from .com_utils import long_ref +from .features import _null_callout + +#: ``swGlobalBoundingBoxFitOptions_e.swBoundingBoxType_BestFit``. +_BEST_FIT = 0 +#: The selection mark ``InsertCoordinateSystem`` reads its origin by. +_MARK_ORIGIN = 1 +#: ``IFeature.GetTypeName2`` of the Center of Mass point. +_CENTER_OF_MASS_TYPE = "CenterOfMass" +#: ``IFeature.GetTypeName2`` of the Bounding Box feature. +_BOUNDING_BOX_TYPE = "BoundingBoxProfileFeat" + + +class SolidWorksReferenceExtrasMixin: + """Coordinate system, centre of mass, bounding box, section properties.""" + + def _reference_call( + self, operation: str, build: Callable[[], dict[str, Any]] + ) -> AdapterResult[dict[str, Any]]: + """Run ``build`` inside the COM boundary, on an open document.""" + adapter: Any = self + if not adapter.currentModel: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active model" + ) + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation(operation, build), + ) + + def _extension(self) -> Any: + """The model's ``IModelDocExtension``, flagged (unflagged, its methods + read as properties).""" + adapter: Any = self + return sw_type_info.flagged( + adapter.currentModel.Extension, "IModelDocExtension" + ) + + def _features_of_type(self, type_name: str) -> list[str]: + """The names of the features whose ``GetTypeName2`` is ``type_name``.""" + adapter: Any = self + found: list[str] = [] + feature = adapter._attempt(lambda: adapter.currentModel.FirstFeature()) + while feature is not None: + flagged = sw_type_info.flagged(feature, "IFeature") + if adapter._attempt(lambda f=flagged: f.GetTypeName2()) == type_name: + found.append(str(adapter._attempt(lambda f=flagged: f.Name))) + feature = adapter._attempt(lambda f=flagged: f.GetNextFeature()) + return found + + async def create_coordinate_system( + self, params: CoordinateSystemParameters + ) -> AdapterResult[dict[str, Any]]: + """A coordinate system at a point, with the model's axes. + + Args: + params: The origin (mm). + + Returns: + AdapterResult[dict[str, Any]]: ``name``, ``sketch`` (the 3D sketch + holding the origin point), and the transform read back: + ``origin_mm`` and ``x_axis``, ``y_axis``, ``z_axis``. + """ + adapter: Any = self + + def build() -> dict[str, Any]: + if len(params.origin) != 3: + raise InputRefused("origin must be [x, y, z] in mm.") + model = adapter.currentModel + sketcher = sw_type_info.flagged(model.SketchManager, "ISketchManager") + x, y, z = (float(v) / 1000.0 for v in params.origin) + sketcher.Insert3DSketch(True) + point = adapter._attempt(lambda: sketcher.CreatePoint(x, y, z)) + sketcher.Insert3DSketch(True) + last = adapter._attempt(lambda: model.FeatureByPositionReverse(0)) + sketch = str( + adapter._attempt(lambda: sw_type_info.flagged(last, "IFeature").Name) + ) + if point is None or not sketch: + raise RuntimeError( + "SolidWorks drew no origin point for the coordinate system." + ) + adapter._attempt(lambda: model.ClearSelection2(True)) + extension = self._extension() + extension.SelectByID2( + f"Point1@{sketch}", + "EXTSKETCHPOINT", + 0, + 0, + 0, + False, + _MARK_ORIGIN, + _null_callout(), + 0, + ) + manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager") + feature = manager.InsertCoordinateSystem(False, False, False) + adapter._attempt(lambda: model.ClearSelection2(True)) + if feature is None: + raise RuntimeError("SolidWorks made no coordinate system.") + name = str(sw_type_info.flagged(feature, "IFeature").Name) + transform = extension.GetCoordinateSystemTransformByName(name) + return { + "name": name, + "sketch": sketch, + **rules.transform_reply(adapter._attempt(lambda: transform.ArrayData)), + } + + return self._reference_call("create_coordinate_system", build) + + async def create_center_of_mass_point(self) -> AdapterResult[dict[str, Any]]: + """SolidWorks's Center of Mass point on the active part. + + Returns: + AdapterResult[dict[str, Any]]: ``name`` and + ``center_of_mass_mm``. + """ + adapter: Any = self + + def build() -> dict[str, Any]: + if not adapter._measure_bodies(): + raise InputRefused("The part has no solid body, so no centre of mass.") + existing = self._features_of_type(_CENTER_OF_MASS_TYPE) + if existing: + raise InputRefused( + f"The part has a Center of Mass point already (" + f"'{existing[0]}'); a part has one at most." + ) + model = adapter.currentModel + manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager") + feature = manager.InsertCenterOfMass() + if feature is None: + raise RuntimeError("SolidWorks made no Center of Mass point.") + mass = sw_type_info.flagged( + self._extension().CreateMassProperty(), "IMassProperty" + ) + centre = adapter._attempt(lambda: mass.CenterOfMass) + return { + "name": str(sw_type_info.flagged(feature, "IFeature").Name), + "center_of_mass_mm": [round(float(v) * 1000, 4) for v in centre] + if isinstance(centre, (list, tuple)) + else None, + } + + return self._reference_call("create_center_of_mass_point", build) + + async def create_bounding_box( + self, params: BoundingBoxParameters + ) -> AdapterResult[dict[str, Any]]: + """SolidWorks's Bounding Box feature around the part's bodies. + + Args: + params: Whether to include hidden bodies. + + Returns: + AdapterResult[dict[str, Any]]: ``name``, ``size_mm`` and the box's + ``min_mm`` and ``max_mm`` corners (the bodies' box in model axes). + """ + adapter: Any = self + + def build() -> dict[str, Any]: + measured = adapter._measure_bodies() + if not measured: + raise InputRefused("The part has no solid body to box.") + existing = self._features_of_type(_BOUNDING_BOX_TYPE) + if existing: + raise InputRefused( + f"The part has a bounding box already ('{existing[0]}'); a " + "part has one at most." + ) + model = adapter.currentModel + manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager") + status = long_ref(0) + feature = manager.InsertGlobalBoundingBox( + _BEST_FIT, params.include_hidden, False, status + ) + if feature is None: + code = adapter._attempt(lambda: status.value, default=status) + raise RuntimeError(f"SolidWorks made no bounding box (status {code}).") + states = [state for state, _ in measured] + low = [min(s.box_min[i] for s in states) for i in range(3)] + high = [max(s.box_max[i] for s in states) for i in range(3)] + return { + "name": str(sw_type_info.flagged(feature, "IFeature").Name), + "size_mm": [round(high[i] - low[i], 4) for i in range(3)], + "min_mm": [round(v, 4) for v in low], + "max_mm": [round(v, 4) for v in high], + } + + return self._reference_call("create_bounding_box", build) + + async def get_section_properties( + self, params: SectionPropertiesParameters + ) -> AdapterResult[dict[str, Any]]: + """Area, centroid and second moments of area of a planar face. + + Args: + params: A point on the face (mm). + + Returns: + AdapterResult[dict[str, Any]]: ``face_point`` and the properties + from :func:`..appearance_rules.section_reply`. + """ + adapter: Any = self + + def build() -> dict[str, Any]: + if len(params.face_point) != 3: + raise InputRefused("face_point must be [x, y, z] in mm.") + select_face_at(adapter, params.face_point) + # GetSectionProperties2 reads the selection; an array of the + # face returned status 1 and zeros (probe, SolidWorks 2026). + values = adapter._attempt( + lambda: self._extension().GetSectionProperties2(None) + ) + adapter._attempt(lambda: adapter.currentModel.ClearSelection2(True)) + return { + "face_point": list(params.face_point), + **rules.section_reply(values), + } + + return self._reference_call("get_section_properties", build) diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md index a7ffd9aa..c6a01113 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md @@ -143,6 +143,22 @@ A cut or a `create_hole` hole that already exists can be repeated instead: did nothing fails and is undone. `save_body_as_part` saves one body as its own part. +## Colours, frames and measurements + +1. Colour with `set_appearance`: `color` [r, g, b] 0-255 or '#rrggbb', on + the whole part (no target), a `feature`, a `body` or the face at a + `face_point`. A face's colour shows over its feature's, a feature's + over its body's, a body's over the part's; `reset: true` removes a + level's own colour. `get_appearance` says which level shows. +2. `create_coordinate_system` puts a frame at an `origin` (mm), axes along + the model's. +3. `create_bounding_box` adds SolidWorks's box and gives the stock size + (`size_mm`); `create_center_of_mass_point` marks the centre of mass + (`center_of_mass_mm`). A part has one of each at most. +4. `get_section_properties` reads a planar face's `area_mm2`, centroid and + second moments of area, picked by a point on the face. It changes + nothing. + ## Changing an existing model 1. `open_model`, then `list_features` and `list_model_dimensions`. diff --git a/src/solidworks_mcp/tools/__init__.py b/src/solidworks_mcp/tools/__init__.py index e1072404..d7c8539e 100644 --- a/src/solidworks_mcp/tools/__init__.py +++ b/src/solidworks_mcp/tools/__init__.py @@ -9,6 +9,7 @@ from loguru import logger from .analysis import register_analysis_tools +from .appearance import register_appearance_tools from .assembly import register_assembly_tools from .automation import register_automation_tools from .bodies import register_body_tools @@ -22,6 +23,7 @@ from .file_management import register_file_management_tools from .macro_recording import register_macro_recording_tools from .modeling import register_modeling_tools +from .reference_extras import register_reference_extras_tools from .server_admin import register_server_admin_tools from .sketching import register_sketching_tools from .template_management import register_template_management_tools @@ -45,6 +47,8 @@ async def register_tools(mcp: FastMCP, adapter: Any, config: Any) -> int: await register_modeling_tools(mcp, adapter, config) await register_equation_tools(mcp, adapter, config) await register_body_tools(mcp, adapter, config) + await register_appearance_tools(mcp, adapter, config) + await register_reference_extras_tools(mcp, adapter, config) await register_assembly_tools(mcp, adapter, config) await register_sketching_tools(mcp, adapter, config) await register_drawing_tools(mcp, adapter, config) diff --git a/src/solidworks_mcp/tools/appearance.py b/src/solidworks_mcp/tools/appearance.py new file mode 100644 index 00000000..3e91381c --- /dev/null +++ b/src/solidworks_mcp/tools/appearance.py @@ -0,0 +1,180 @@ +"""Appearance tools: colour the part, a feature, a body or a face, and read it back. + +A colour shows from the nearest level that has one: a face over its feature, +a feature over its body, a body over the part (SolidWorks's appearance +hierarchy). ``set_appearance`` sets or removes a level's colour and reads it +back; ``get_appearance`` says what shows and where it comes from (queue +item 36). +""" + +from __future__ import annotations + +from typing import Any + +from fastmcp import FastMCP +from pydantic import Field + +from ..adapters.base import AppearanceParameters, AppearanceTarget, SolidWorksAdapter +from .input_compat import CompatInput +from .tool_boundary import ( + normalize_input, + require_capability, + require_success, + with_tool_boundary, +) + + +class AppearanceTargetInput(CompatInput): + """Input schema naming what a colour is read from or set on. + + Attributes: + feature (str | None): A feature by name. + body (str | None): A body by name. + face_point (list[float] | None): ``[x, y, z]`` mm on a face. + """ + + feature: str | None = Field( + default=None, + min_length=1, + description="A feature by its name in the tree, e.g. 'Boss-Extrude1'", + ) + body: str | None = Field( + default=None, min_length=1, description="A solid body, as list_bodies names it" + ) + face_point: list[float] | None = Field( + default=None, + min_length=3, + max_length=3, + description="[x, y, z] in mm, a point on the face; give one target, or " + "none for the whole part", + ) + + +class SetAppearanceInput(AppearanceTargetInput): + """Input schema for setting or removing a colour. + + Attributes: + color (list[int] | str | None): ``[r, g, b]`` 0-255 or ``#rrggbb``. + transparency (float): 0 opaque to 1 clear. + reset (bool): Remove the target's own colour. + """ + + color: list[int] | str | None = Field( + default=None, + description="[r, g, b], each 0-255, or '#rrggbb', e.g. [31, 119, 180] " + "or '#1f77b4'", + ) + transparency: float = Field( + default=0.0, ge=0.0, le=1.0, description="0 opaque (default) to 1 clear" + ) + reset: bool = Field( + default=False, + description="Remove the feature's, body's or face's own colour so the " + "one above it shows; give no color", + ) + + +def _brief(data: dict[str, Any]) -> str: + """'#1f77b4 on feature Boss-Extrude1'.""" + target = data.get("target", "part") + named = data.get(target) or data.get("face_point") + where = ( + f"{target} {named}" if named is not None and target != "part" else "the part" + ) + return f"{data.get('hex')} on {where}" + + +async def register_appearance_tools( + mcp: FastMCP, adapter: SolidWorksAdapter, config: Any +) -> int: + """Register the appearance tools with FastMCP. + + Args: + mcp (FastMCP): The server. + adapter (SolidWorksAdapter): The adapter the tools call. + config (Any): Configuration values (unused). + + Returns: + int: How many tools were registered. + """ + mcp = with_tool_boundary(mcp) + + @mcp.tool() + async def set_appearance(input_data: SetAppearanceInput) -> dict[str, Any]: + """Colour the active part, one feature, one body or the face at a point, or remove a colour. + + Give `color` ([r, g, b] 0-255 or '#rrggbb') and at most one target: + `feature`, `body` (as `list_bodies` names it) or `face_point`; none + colours the whole part. A face's colour shows over its feature's, a + feature's over its body's, a body's over the part's. `reset: true` + removes a feature's, body's or face's own colour. Fails, changing + nothing, for two targets, an unknown feature or body, or a point on no + face. Needs: an open part. Changes: the colour only, not the geometry. + Returns: `appearance` with `target`, the colour read back (`color`, + `hex`, `transparency`), or after a reset what now `showing`. + + Args: + input_data: `color` and an optional target and `transparency`, + or a target and `reset`. + + Returns: + dict[str, Any]: The colour as SolidWorks now holds it. + """ + input_data = normalize_input(input_data, SetAppearanceInput) + require_capability( + adapter, "set_appearance", "Active adapter can't set colours" + ) + result = await adapter.set_appearance( + AppearanceParameters(**input_data.model_dump()) + ) + require_success(result, "Failed to set the colour") + data = result.data or {} + if data.get("reset"): + showing = data.get("showing") or {} + message = ( + f"Removed the {data.get('target')}'s colour; " + f"{showing.get('hex')} from the {showing.get('level')} shows" + ) + else: + message = f"Coloured: {_brief(data)}" + return { + "status": "success", + "message": message, + "appearance": data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def get_appearance( + input_data: AppearanceTargetInput | None = None, + ) -> dict[str, Any]: + """Read the colour the active part, a feature, a body or the face at a point shows, and where it comes from. + + Give at most one target (`feature`, `body` or `face_point`); none reads + the part. Needs: an open part. Read-only. Returns: `appearance` with + `target`, `color` ([r, g, b] 0-255), `hex`, `transparency` and + `level`: the face, feature, body or part the colour comes from. + + Args: + input_data: An optional target. + + Returns: + dict[str, Any]: The colour showing and its level. + """ + input_data = normalize_input(input_data or {}, AppearanceTargetInput) + require_capability( + adapter, "get_appearance", "Active adapter can't read colours" + ) + result = await adapter.get_appearance( + AppearanceTarget(**input_data.model_dump()) + ) + require_success(result, "Failed to read the colour") + data = result.data or {} + return { + "status": "success", + "message": f"{_brief(data)}, from the {data.get('level')}", + "appearance": data, + "execution_time": result.execution_time, + } + + return 2 diff --git a/src/solidworks_mcp/tools/error_classifier.py b/src/solidworks_mcp/tools/error_classifier.py index 9ce8323b..2047d7a9 100644 --- a/src/solidworks_mcp/tools/error_classifier.py +++ b/src/solidworks_mcp/tools/error_classifier.py @@ -252,6 +252,50 @@ def matches(self, message: str, hresult: int | None) -> bool: r"(translate|rotate|rotation_point|scale_xyz) must be \[x, y, z\]", ), ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "Give one target: a feature (list_features), a body (list_bodies) " + "or a face_point [x, y, z] mm on a face, or none for the part. A " + "color is [r, g, b] 0-255 or '#rrggbb'; reset removes a feature's, " + "body's or face's own colour." + ), + patterns=( + r"Give one target, not", + r"No feature named '[^']*'; list_features names them", + r"No face at \[", + r"color .* (is not '#rrggbb'|must be \[r, g, b\])", + r"Give a color", + r"reset removes a feature's", + r"transparency must be 0", + r"(face_point|origin) must be \[x, y, z\]", + ), + ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "A part has one Center of Mass point and one bounding box at most, " + "and both need a solid body. Section properties need a point on a " + "planar face." + ), + patterns=( + r"The part has no solid body", + r"The part has (a Center of Mass point|a bounding box) already", + r"(couldn't take a section of|gave no section properties for) that face", + ), + ), + ErrorRule( + error_type="feature_not_built", + hint=( + "SolidWorks made nothing. Check the part has a solid body and the " + "inputs, then read the tree with list_features." + ), + patterns=( + r"SolidWorks (made no|drew no) (coordinate system|Center of Mass " + r"point|bounding box|origin point)", + r"SolidWorks did not keep the colour", + ), + ), ErrorRule( error_type=INVALID_INPUT, hint=( diff --git a/src/solidworks_mcp/tools/reference_extras.py b/src/solidworks_mcp/tools/reference_extras.py new file mode 100644 index 00000000..20feba8e --- /dev/null +++ b/src/solidworks_mcp/tools/reference_extras.py @@ -0,0 +1,228 @@ +"""Reference and analysis extras: coordinate system, centre of mass, bounding box, section. + +Each reply is read back from SolidWorks, not echoed: the coordinate system's +transform, the centre of mass, the bodies' box and a face's section +properties (queue item 39). +""" + +from __future__ import annotations + +from typing import Any + +from fastmcp import FastMCP +from pydantic import Field + +from ..adapters.base import ( + BoundingBoxParameters, + CoordinateSystemParameters, + SectionPropertiesParameters, + SolidWorksAdapter, +) +from .input_compat import CompatInput +from .tool_boundary import ( + normalize_input, + require_capability, + require_success, + with_tool_boundary, +) + + +class CoordinateSystemInput(CompatInput): + """Input schema for a coordinate system at a point. + + Attributes: + origin (list[float]): ``[x, y, z]`` mm. + """ + + origin: list[float] = Field( + min_length=3, max_length=3, description="The origin [x, y, z] in mm" + ) + + +class BoundingBoxInput(CompatInput): + """Input schema for the bounding box. + + Attributes: + include_hidden (bool): Include hidden bodies. + """ + + include_hidden: bool = Field( + default=False, description="Include hidden bodies in the box" + ) + + +class SectionPropertiesInput(CompatInput): + """Input schema for a face's section properties. + + Attributes: + face_point (list[float]): ``[x, y, z]`` mm on the face. + """ + + face_point: list[float] = Field( + min_length=3, + max_length=3, + description="[x, y, z] in mm, a point on a planar face", + ) + + +def _mm(values: Any) -> str: + """'(20, 10, 20)' from a list of mm.""" + return "(" + ", ".join(f"{float(v):g}" for v in values or []) + ")" + + +async def register_reference_extras_tools( + mcp: FastMCP, adapter: SolidWorksAdapter, config: Any +) -> int: + """Register the reference and analysis extras with FastMCP. + + Args: + mcp (FastMCP): The server. + adapter (SolidWorksAdapter): The adapter the tools call. + config (Any): Configuration values (unused). + + Returns: + int: How many tools were registered. + """ + mcp = with_tool_boundary(mcp) + + @mcp.tool() + async def create_coordinate_system( + input_data: CoordinateSystemInput, + ) -> dict[str, Any]: + """Add a coordinate system with its origin at a point, axes along the model's. + + Use it as a frame for measurements, mass properties or exports. The + origin is a point in a 3D sketch the tool draws for it; the axes + can't yet be turned. Needs: an open part. + Changes: adds a 3D sketch and a Coordinate System feature. Returns: + `coordinate_system` with `name`, `sketch`, and the transform read + back: `origin_mm`, `x_axis`, `y_axis`, `z_axis`. + + Args: + input_data: `origin` in mm. + + Returns: + dict[str, Any]: The coordinate system as SolidWorks holds it. + """ + input_data = normalize_input(input_data, CoordinateSystemInput) + require_capability( + adapter, + "create_coordinate_system", + "Active adapter can't add coordinate systems", + ) + result = await adapter.create_coordinate_system( + CoordinateSystemParameters(**input_data.model_dump()) + ) + require_success(result, "Failed to add the coordinate system") + data = result.data or {} + return { + "status": "success", + "message": f"{data.get('name')} at {_mm(data.get('origin_mm'))} mm", + "coordinate_system": data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def create_center_of_mass_point() -> dict[str, Any]: + """Add SolidWorks's Center of Mass point to the active part, at its centre of mass. + + The point moves with the geometry; dimension to it or read it in + drawings. A part has one at most. Fails when the part has one already + or has no solid body. For the numbers alone, `get_mass_properties` + changes nothing. Needs: an open part with a body. Changes: adds a + Center of Mass feature. Returns: `center_of_mass` with `name` and + `center_of_mass_mm`. + """ + require_capability( + adapter, + "create_center_of_mass_point", + "Active adapter can't add a centre-of-mass point", + ) + result = await adapter.create_center_of_mass_point() + require_success(result, "Failed to add the centre-of-mass point") + data = result.data or {} + return { + "status": "success", + "message": ( + f"{data.get('name')} at {_mm(data.get('center_of_mass_mm'))} mm" + ), + "center_of_mass": data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def create_bounding_box( + input_data: BoundingBoxInput | None = None, + ) -> dict[str, Any]: + """Add SolidWorks's Bounding Box feature around the active part's bodies and give the stock size. + + The box is SolidWorks's best fit and updates with the part. A part has + one at most. For the size alone, `verify_model` changes nothing. + Needs: an open part with a body. Changes: adds a Bounding Box feature. + Returns: `bounding_box` with `name`, `size_mm` [x, y, z] and the + `min_mm` and `max_mm` corners, in model axes. + + Args: + input_data: Optional `include_hidden`. + + Returns: + dict[str, Any]: The box and its size. + """ + input_data = normalize_input(input_data or {}, BoundingBoxInput) + require_capability( + adapter, "create_bounding_box", "Active adapter can't add a bounding box" + ) + result = await adapter.create_bounding_box( + BoundingBoxParameters(**input_data.model_dump()) + ) + require_success(result, "Failed to add the bounding box") + data = result.data or {} + size = " x ".join(f"{float(v):g}" for v in data.get("size_mm") or []) + return { + "status": "success", + "message": f"{data.get('name')}: {size} mm", + "bounding_box": data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def get_section_properties( + input_data: SectionPropertiesInput, + ) -> dict[str, Any]: + """Read the area, centroid and second moments of area of a planar face, picked by a point on it. + + E.g. a beam's cross-section or a bracket's mounting face. Moments are + about the face's centroid, in model axes. Fails when the point is on + no face or the face isn't planar. Needs: an open part. Read-only. + Returns: `section` with `area_mm2`, `centroid_mm`, `ixx`, `iyy`, + `izz`, `ixy`, `izx`, `iyz` (mm⁴), `polar_moment_mm4` and + `principal_moments_mm4`. + + Args: + input_data: `face_point` in mm. + + Returns: + dict[str, Any]: The face's section properties. + """ + input_data = normalize_input(input_data, SectionPropertiesInput) + require_capability( + adapter, + "get_section_properties", + "Active adapter can't read section properties", + ) + result = await adapter.get_section_properties( + SectionPropertiesParameters(**input_data.model_dump()) + ) + require_success(result, "Failed to read the section properties") + data = result.data or {} + return { + "status": "success", + "message": ( + f"Area {float(data.get('area_mm2') or 0):,.2f} mm², centroid " + f"{_mm(data.get('centroid_mm'))} mm" + ), + "section": data, + "execution_time": result.execution_time, + } + + return 4 diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index 4d18126d..ae7f33a7 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -296,28 +296,59 @@ def _deprecated(replacement: str | None) -> Support: SupportLevel.BETA, "new: checked live once (a spring and a threaded rod), not yet in wide use.", ), - # Queue item 35: beta until the multi-body live demo. + # Queue item 35: passed the live demo 2026-11-27; beta for a release. "combine_bodies": Support( SupportLevel.BETA, - "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", ), "delete_bodies": Support( SupportLevel.BETA, - "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", ), "list_bodies": Support( SupportLevel.BETA, - "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", ), "move_copy_body": Support( SupportLevel.BETA, - "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", ), "scale_body": Support( SupportLevel.BETA, - "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", ), "split_body": Support( + SupportLevel.BETA, + "new: passed its live demo (boolean logic on a cube and a sphere), " + "not yet in wide use.", + ), + # Queue items 36 and 39: beta until their live demo. + "create_bounding_box": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "create_center_of_mass_point": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "create_coordinate_system": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "get_appearance": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "get_section_properties": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "set_appearance": Support( SupportLevel.BETA, "new: checked on SolidWorks by a scratch run, not yet by a live demo.", ), diff --git a/src/solidworks_mcp/tools/tool_hints.py b/src/solidworks_mcp/tools/tool_hints.py index 43e9ff23..80a52c91 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -208,6 +208,12 @@ def _discards(title: str) -> ToolHints: "move_copy_body": _adds("Move/Copy Body"), "delete_bodies": _discards("Delete/Keep Bodies"), "scale_body": _adds("Scale Body"), + "set_appearance": _sets("Set Appearance"), + "get_appearance": _reads("Get Appearance"), + "create_coordinate_system": _adds("Create Coordinate System"), + "create_center_of_mass_point": _adds("Create Center of Mass Point"), + "create_bounding_box": _adds("Create Bounding Box"), + "get_section_properties": _reads("Get Section Properties"), "create_loft": _adds("Create Loft"), "insert_component": _adds("Insert Component"), "add_mate": _adds("Add Mate"), diff --git a/src/solidworks_mcp/tools/toolsets.py b/src/solidworks_mcp/tools/toolsets.py index 6f3f7d8c..f068a3f5 100644 --- a/src/solidworks_mcp/tools/toolsets.py +++ b/src/solidworks_mcp/tools/toolsets.py @@ -20,6 +20,8 @@ "modeling", "equations", "bodies", + "appearance", + "reference_extras", "assembly", "sketching", "file_management", diff --git a/tests/integration/test_skill_content.py b/tests/integration/test_skill_content.py index 0fe32473..e8866c9b 100644 --- a/tests/integration/test_skill_content.py +++ b/tests/integration/test_skill_content.py @@ -31,14 +31,17 @@ #: Response keys the skill quotes; they are not input fields or tools. _RESPONSE_KEYS = { "area_m2", + "area_mm2", "bodies_after", "center_mm", + "center_of_mass_mm", "direction_flipped", "distance_m", "error_type", "length_m", "length_mm", "measured_change", + "size_mm", "start_point_mm", "system_value", "usage_instructions", diff --git a/tests/integration/test_tool_descriptions.py b/tests/integration/test_tool_descriptions.py index 2e7bece8..86f8f764 100644 --- a/tests/integration/test_tool_descriptions.py +++ b/tests/integration/test_tool_descriptions.py @@ -19,6 +19,7 @@ _MODULES = [ "analysis", + "appearance", "assembly", "automation", "bodies", @@ -32,6 +33,7 @@ "file_management", "macro_recording", "modeling", + "reference_extras", "server_admin", "sketching", "template_management", diff --git a/tests/live/test_live_sw_appearance_and_reference.py b/tests/live/test_live_sw_appearance_and_reference.py new file mode 100644 index 00000000..6abad0ae --- /dev/null +++ b/tests/live/test_live_sw_appearance_and_reference.py @@ -0,0 +1,197 @@ +"""Colours and reference extras (queue items 36 and 39), checked on real SolidWorks. + +1. Colours: a 40 x 40 x 10 mm block. Its feature green, its top face blue, its + body orange: the top face shows blue (face), a side face green (the + feature shows over the body). The face's colour removed: green again. On + purpose: two targets at once are refused. +2. Reference extras on the same block: the top face's section (1,600 mm², + centroid (0, 10, 0), 40⁴/12 = 213,333.3 mm⁴ about x and z), a coordinate + system at the corner (20, 10, 20), the centre of mass + (0, 5, 0) and the bounding box 40 x 10 x 40. On purpose: a second Center + of Mass point is refused. + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_appearance_and_reference.py::test_colours_on_a_block + +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_material_properties import _tools as _base_tools + +pytestmark = pytest.mark.asyncio + +GREEN = "#1fcc33" +BLUE = [25, 76, 242] +ORANGE = "#f28c1a" +_ISO_VIEW = 7 # swStandardViews_e.swIsometricView + + +async def _tools(adapter: Any) -> dict[str, Any]: + """The modelling tools plus the body, appearance and reference tools.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.appearance import register_appearance_tools + from solidworks_mcp.tools.bodies import register_body_tools + from solidworks_mcp.tools.reference_extras import ( + register_reference_extras_tools, + ) + + tools = await _base_tools(adapter) + mcp = FastMCP("appearance-live") + for register in ( + register_body_tools, + register_appearance_tools, + register_reference_extras_tools, + ): + await register(mcp, adapter, {}) + tools.update({t.name: t.fn for t in await mcp.list_tools()}) + return tools + + +async def _ok(reply: dict[str, Any]) -> dict[str, Any]: + assert reply["status"] == "success", reply + return reply + + +def _iso(adapter: Any) -> None: + """Turn the camera isometric, zoomed to fit (staging, not a tool call).""" + model = adapter.currentModel + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + adapter._attempt(lambda: model.ShowNamedView2("", _ISO_VIEW), default=None) + adapter._zoom_to_fit(model) + + +async def _block(tools: dict[str, Any], name: str) -> None: + """A 40 x 40 x 10 mm block on the Top Plane: y 0 to 10.""" + await _ok(await tools["create_part"]({"name": name})) + await _ok(await tools["create_sketch"]({"plane": "Top"})) + await _ok(await tools["add_rectangle"]({"x1": -20, "y1": -20, "x2": 20, "y2": 20})) + await _ok(await tools["exit_sketch"]()) + await _ok(await tools["create_extrusion"]({"depth": 10})) + + +async def test_colours_on_a_block(scratch: Any) -> None: + """Feature, face and body colours, which one shows, and a reset.""" + adapter = scratch.adapter + tools = await _tools(adapter) + await _block(tools, "colours") + body = (await _ok(await tools["list_bodies"]()))["bodies"][0]["name"] + + call = {"feature": "Boss-Extrude1", "color": GREEN} + green = await _ok(await tools["set_appearance"](call)) + _iso(adapter) + evidence("the feature green", green["appearance"], call=f"set_appearance({call})") + assert green["appearance"]["hex"] == GREEN + + call = {"face_point": [0, 10, 0], "color": BLUE} + blue = await _ok(await tools["set_appearance"](call)) + _iso(adapter) + evidence("the top face blue", blue["appearance"], call=f"set_appearance({call})") + assert blue["appearance"]["color"] == BLUE + + call = {"body": body, "color": ORANGE} + orange = await _ok(await tools["set_appearance"](call)) + _iso(adapter) + evidence( + "the body orange: the feature's green still shows on the sides", + orange["appearance"], + call=f"set_appearance({call})", + ) + assert orange["appearance"]["hex"] == ORANGE + + top = await _ok(await tools["get_appearance"]({"face_point": [0, 10, 0]})) + side = await _ok(await tools["get_appearance"]({"face_point": [20, 5, 0]})) + evidence( + "what shows: the top face's own blue, a side face's feature green", + {"top": top["appearance"], "side": side["appearance"]}, + ) + assert top["appearance"]["level"] == "face" + assert side["appearance"]["level"] == "feature" + assert side["appearance"]["hex"] == GREEN + + # On purpose: two targets. + refused = await tools["set_appearance"]( + {"feature": "Boss-Extrude1", "face_point": [0, 10, 0], "color": BLUE} + ) + evidence("two targets are refused", refused) + assert refused["status"] == "error" and refused["error_type"] == "invalid_input" + + call = {"face_point": [0, 10, 0], "reset": True} + reset = await _ok(await tools["set_appearance"](call)) + _iso(adapter) + evidence( + "the top face's colour removed: the feature's green shows", + reset["appearance"], + call=f"set_appearance({call})", + ) + assert reset["appearance"]["showing"]["level"] == "feature" + assert reset["appearance"]["showing"]["hex"] == GREEN + + +async def test_reference_extras_on_a_block(scratch: Any) -> None: + """Section, coordinate systems, centre of mass and bounding box of a block.""" + adapter = scratch.adapter + tools = await _tools(adapter) + await _block(tools, "reference") + _iso(adapter) + + call = {"face_point": [0, 10, 0]} + section = await _ok(await tools["get_section_properties"](call)) + evidence( + "the top face's section (expect 1,600 mm², 213,333.3 mm⁴)", + section["section"], + call=f"get_section_properties({call})", + ) + data = section["section"] + assert data["area_mm2"] == pytest.approx(1600, rel=1e-6) + assert data["centroid_mm"] == pytest.approx([0, 10, 0], abs=1e-6) + assert data["ixx"] == pytest.approx(40**4 / 12, rel=1e-4) + assert data["izz"] == pytest.approx(40**4 / 12, rel=1e-4) + assert data["polar_moment_mm4"] == pytest.approx(40**4 / 6, rel=1e-4) + + call = {"origin": [20, 10, 20]} + corner = await _ok(await tools["create_coordinate_system"](call)) + _iso(adapter) + evidence( + "a coordinate system at the corner (20, 10, 20)", + corner["coordinate_system"], + call=f"create_coordinate_system({call})", + ) + assert corner["coordinate_system"]["origin_mm"] == pytest.approx( + [20, 10, 20], abs=1e-6 + ) + assert corner["coordinate_system"]["x_axis"] == pytest.approx([1, 0, 0]) + + com = await _ok(await tools["create_center_of_mass_point"]()) + _iso(adapter) + evidence( + "the Center of Mass point (expect (0, 5, 0))", + com["center_of_mass"], + call="create_center_of_mass_point()", + ) + assert com["center_of_mass"]["center_of_mass_mm"] == pytest.approx( + [0, 5, 0], abs=1e-6 + ) + + # On purpose: a second one. + refused = await tools["create_center_of_mass_point"]() + evidence("a second Center of Mass point is refused", refused) + assert refused["status"] == "error" and refused["error_type"] == "invalid_input" + + box = await _ok(await tools["create_bounding_box"]()) + _iso(adapter) + evidence( + "the bounding box (expect 40 x 10 x 40)", + box["bounding_box"], + call="create_bounding_box()", + ) + assert box["bounding_box"]["size_mm"] == pytest.approx([40, 10, 40], abs=1e-6) diff --git a/tests/solidworks_mcp/adapters/appearance_calls.py b/tests/solidworks_mcp/adapters/appearance_calls.py new file mode 100644 index 00000000..9d8deb83 --- /dev/null +++ b/tests/solidworks_mcp/adapters/appearance_calls.py @@ -0,0 +1,39 @@ +"""One call of each adapter method queue items 36 and 39 add, shared by the layer tests.""" + +from __future__ import annotations + +from typing import Any + +from solidworks_mcp.adapters.base import ( + AppearanceParameters, + AppearanceTarget, + BoundingBoxParameters, + CoordinateSystemParameters, + SectionPropertiesParameters, +) + +from .body_calls import recorder_for + +CALLS: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [ + ("set_appearance", (AppearanceParameters(color="#1f77b4"),), {}), + ("get_appearance", (AppearanceTarget(feature="Boss-Extrude1"),), {}), + ( + "create_coordinate_system", + (CoordinateSystemParameters(origin=[20, 10, 20]),), + {}, + ), + ("create_center_of_mass_point", (), {}), + ("create_bounding_box", (BoundingBoxParameters(),), {}), + ( + "get_section_properties", + (SectionPropertiesParameters(face_point=[0, 10, 0]),), + {}, + ), +] + +IDS = [call[0] for call in CALLS] + + +def recorder() -> Any: + """A mock adapter whose appearance and reference methods record their arguments.""" + return recorder_for(IDS) diff --git a/tests/solidworks_mcp/adapters/body_calls.py b/tests/solidworks_mcp/adapters/body_calls.py index 091ae1fe..afbc6ab4 100644 --- a/tests/solidworks_mcp/adapters/body_calls.py +++ b/tests/solidworks_mcp/adapters/body_calls.py @@ -38,6 +38,11 @@ def recorder() -> Any: """A mock adapter whose body methods record their arguments.""" + return recorder_for(IDS) + + +def recorder_for(names: list[str]) -> Any: + """A mock adapter whose methods ``names`` record their arguments.""" from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter @@ -49,5 +54,5 @@ async def call(self: Any, *args: Any, **kwargs: Any) -> AdapterResult[Any]: return call - body = {name: method(name) for name in IDS} + body = {name: method(name) for name in names} return type("_Recorder", (MockSolidWorksAdapter,), body)({}) diff --git a/tests/solidworks_mcp/adapters/solidworks/appearance_fakes.py b/tests/solidworks_mcp/adapters/solidworks/appearance_fakes.py new file mode 100644 index 00000000..63108224 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/appearance_fakes.py @@ -0,0 +1,220 @@ +"""Fake SolidWorks COM objects for the appearance and reference-extras tests. + +Shaped like the calls the probes of 2026-11-28 measured (design.md of the +``appearance-and-reference-tools`` change): colours as nine values, a face +picked with ``SelectByID2`` and read with ``GetSelectedObject6``, section +properties of the selection, a transform's ``ArrayData``. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus +from solidworks_mcp.adapters.solidworks.appearance import SolidWorksAppearanceMixin +from solidworks_mcp.adapters.solidworks.bodies import SolidWorksBodiesMixin +from solidworks_mcp.adapters.solidworks.reference_extras import ( + SolidWorksReferenceExtrasMixin, +) + +#: A 40 mm square face at y = 10, as GetSectionProperties2 gave it. +SQUARE_SECTION = ( + [0.0, 0.0016, 0.0, 0.01, 0.0] + + [2.1333e-7, 4.2667e-7, 2.1333e-7, 0.0, 0.0, 0.0, 4.2667e-7, 0.0] + + [2.1333e-7, 2.1333e-7] + + [0.0] * 9 +) +NO_COLOUR = [-1.0] * 9 + + +class Coloured: + """A feature, body or face holding its own colour (None when it has none).""" + + def __init__(self, name: str = "", values: Any = None) -> None: + self.Name = name + self.values = values + self.removed = 0 + + # IFace2 / IModelDoc2 style property. + @property + def MaterialPropertyValues(self) -> Any: + return self.values + + @MaterialPropertyValues.setter + def MaterialPropertyValues(self, values: Any) -> None: + self.values = list(values) + + # IBody2 style property. + @property + def MaterialPropertyValues2(self) -> Any: + return self.values + + @MaterialPropertyValues2.setter + def MaterialPropertyValues2(self, values: Any) -> None: + self.values = list(values) + + # IFeature style methods. + def GetMaterialPropertyValues2(self, option: int, names: Any) -> Any: + return self.values if self.values is not None else NO_COLOUR + + def SetMaterialPropertyValues2(self, values: Any, option: int, names: Any) -> None: + self.values = list(values) + + def RemoveMaterialProperty2(self, option: int, names: Any) -> bool: + self.values, self.removed = None, self.removed + 1 + return True + + def RemoveMaterialProperty(self, option: int, names: Any) -> bool: + return self.RemoveMaterialProperty2(option, names) + + +class Body(Coloured): + """IBody2: a 40 x 10 x 40 mm block's volume and box, and its colour.""" + + def __init__(self, name: str = "Boss-Extrude1") -> None: + super().__init__(name) + + def GetMassProperties(self, density: float) -> tuple[float, ...]: + return (0.0, 0.0, 0.0, 16000 / 1e9, 0.0, 0.0) + + def GetBodyBox(self) -> tuple[float, ...]: + return (-0.02, 0.0, -0.02, 0.02, 0.01, 0.02) + + +class Face(Coloured): + """IFace2 with its feature and body.""" + + def __init__(self, feature: Coloured | None, body: Body | None) -> None: + super().__init__("face") + self.feature, self.body = feature, body + + def GetFeature(self) -> Any: + return self.feature + + def GetBody(self) -> Any: + return self.body + + +class TreeFeature: + """IFeature as the tree walk reads it.""" + + def __init__(self, name: str, type_name: str, nxt: Any = None) -> None: + self.Name, self.type_name, self.nxt = name, type_name, nxt + + def GetTypeName2(self) -> str: + return self.type_name + + def GetNextFeature(self) -> Any: + return self.nxt + + +class Model(Coloured): + """IModelDoc2 (a part) with its extension, managers and one block.""" + + def __init__(self, bodies: list[Body] | None = None) -> None: + super().__init__("Part1", [0.894118] * 3 + [1.0, 1.0, 0.5, 0.3125, 0.0, 0.0]) + self.bodies = [Body()] if bodies is None else bodies + self.feature = Coloured("Boss-Extrude1") + self.face = Face(self.feature, self.bodies[0] if self.bodies else None) + self.faces: dict[tuple[float, float, float], Face] = { + (0.0, 0.01, 0.0): self.face + } + self.selected: Any = None + self.section: Any = SQUARE_SECTION + self.inserted: list[tuple[str, tuple[Any, ...]]] = [] + self.tree: Any = TreeFeature("Origin", "OriginProfileFeature") + self.made: dict[str, Any] = { + "coordinate": SimpleNamespace(Name="Coordinate System1"), + "com": SimpleNamespace(Name="Center of Mass"), + "box": SimpleNamespace(Name="Bounding Box"), + } + self.point: Any = object() + self.last_sketch = SimpleNamespace(Name="3DSketch1") + self.transform = SimpleNamespace( + ArrayData=[1, 0, 0, 0, 1, 0, 0, 0, 1, 0.02, 0.01, 0.02, 1, 0, 0, 0] + ) + self.centre: Any = (0.0, 0.005, 0.0) + self.Extension = SimpleNamespace( + SelectByID2=self._select, + GetSectionProperties2=lambda sections: self.section, + CreateMassProperty=lambda: SimpleNamespace(CenterOfMass=self.centre), + GetCoordinateSystemTransformByName=lambda name: self.transform, + ) + self.SelectionManager = SimpleNamespace( + GetSelectedObject6=lambda index, mark: self.selected + ) + self.FeatureManager = SimpleNamespace( + InsertCoordinateSystem=lambda *a: self._insert("coordinate", a), + InsertCenterOfMass=lambda: self._insert("com", ()), + InsertGlobalBoundingBox=lambda *a: self._insert("box", a), + ) + self.SketchManager = SimpleNamespace( + Insert3DSketch=lambda update: None, + CreatePoint=lambda x, y, z: self.point, + ) + + def _select( + self, name: str, kind: str, x: float, y: float, z: float, *rest: Any + ) -> bool: + self.inserted.append(("select", (name, kind, x, y, z, *rest))) + if kind == "FACE": + self.selected = self.faces.get((round(x, 6), round(y, 6), round(z, 6))) + return self.selected is not None + return True + + def _insert(self, what: str, args: tuple[Any, ...]) -> Any: + self.inserted.append((what, args)) + return self.made[what] + + def GetType(self) -> int: + return 1 + + def GetBodies2(self, kind: int, visible_only: bool) -> Any: + return tuple(self.bodies) or None + + def FeatureByName(self, name: str) -> Any: + return self.feature if name == "Boss-Extrude1" else None + + def FeatureByPositionReverse(self, index: int) -> Any: + return self.last_sketch + + def FirstFeature(self) -> Any: + return self.tree + + def ForceRebuild3(self, top_only: bool) -> bool: + return True + + def ClearSelection2(self, everything: bool) -> None: + self.selected = None + + def GraphicsRedraw2(self) -> None: + return None + + +class Harness( + SolidWorksAppearanceMixin, SolidWorksReferenceExtrasMixin, SolidWorksBodiesMixin +): + """The three mixins plus the PyWin32Adapter members they use.""" + + def __init__(self, model: Any) -> None: + self.currentModel = model + + def _attempt(self, operation: Any, default: Any = None) -> Any: + try: + return operation() + except Exception: + return default + + def _get_attr_or_call(self, obj: Any, attr_name: str) -> Any: + attr = getattr(obj, attr_name, None) + return attr() if callable(attr) else attr + + def _handle_com_operation(self, name: str, operation: Any) -> AdapterResult[Any]: + try: + data = operation() + except Exception as e: # mirrors PyWin32Adapter._handle_com_operation + return AdapterResult( + status=AdapterResultStatus.ERROR, error=f"Error in {name}: {e}" + ) + return AdapterResult(status=AdapterResultStatus.SUCCESS, data=data) diff --git a/tests/solidworks_mcp/adapters/solidworks/test_appearance.py b/tests/solidworks_mcp/adapters/solidworks/test_appearance.py new file mode 100644 index 00000000..2a95592f --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_appearance.py @@ -0,0 +1,177 @@ +"""Colours on fake COM objects shaped like SolidWorks 2026's (queue item 36). + +Spec: tools/appearance. The calls are the ones the probes of 2026-11-28 +measured (design.md of the appearance-and-reference-tools change). +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from solidworks_mcp.adapters import sw_type_info +from solidworks_mcp.adapters.base import AppearanceParameters, AppearanceTarget +from solidworks_mcp.adapters.solidworks import appearance + +from .appearance_fakes import Body, Coloured, Face, Harness, Model + +GREEN = [31 / 255, 204 / 255, 51 / 255, 1.0, 1.0, 0.5, 0.3125, 0.0, 0.0] + + +@pytest.fixture(autouse=True) +def plain_com(monkeypatch: pytest.MonkeyPatch) -> None: + """No flagging; arrays as lists.""" + monkeypatch.setattr(sw_type_info, "flagged", lambda obj, *_: obj) + monkeypatch.setattr(appearance, "double_array", list) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "holder"), + [ + (AppearanceParameters(color="#1fcc33"), lambda m: m), + ( + AppearanceParameters(feature="Boss-Extrude1", color="#1fcc33"), + lambda m: m.feature, + ), + ( + AppearanceParameters(body="boss-extrude1", color="#1fcc33"), + lambda m: m.bodies[0], + ), + ( + AppearanceParameters(face_point=[0, 10, 0], color="#1fcc33"), + lambda m: m.face, + ), + ], +) +async def test_each_level_is_coloured_and_read_back( + call: AppearanceParameters, holder: Any +) -> None: + model = Model() + + result = await Harness(model).set_appearance(call) + + assert result.is_success, result.error + assert result.data["hex"] == "#1fcc33" + assert holder(model).values == pytest.approx(GREEN) + + +@pytest.mark.asyncio +async def test_a_face_reads_the_nearest_level() -> None: + model = Model() + model.feature.values = GREEN + model.bodies[0].values = [0.9, 0.5, 0.1, 1, 1, 0.5, 0.3125, 0, 0] + + face = await Harness(model).get_appearance(AppearanceTarget(face_point=[0, 10, 0])) + body = await Harness(model).get_appearance(AppearanceTarget(body="Boss-Extrude1")) + part = await Harness(model).get_appearance(AppearanceTarget()) + + assert (face.data["level"], face.data["hex"]) == ("feature", "#1fcc33") + assert body.data["level"] == "body" + assert part.data["level"] == "part" + assert face.data["face_point"] == [0, 10, 0] + + +@pytest.mark.asyncio +async def test_a_face_with_nothing_above_it_reads_nothing() -> None: + model = Model() + model.values = None + model.face = Face(None, None) + model.faces[(0.0, 0.01, 0.0)] = model.face + + result = await Harness(model).get_appearance( + AppearanceTarget(face_point=[0, 10, 0]) + ) + + assert result.data["level"] is None and result.data["color"] is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "holder"), + [ + (AppearanceParameters(feature="Boss-Extrude1", reset=True), "feature"), + (AppearanceParameters(body="Boss-Extrude1", reset=True), "body"), + (AppearanceParameters(face_point=[0, 10, 0], reset=True), "face"), + ], +) +async def test_a_reset_removes_the_level_and_shows_the_next( + call: AppearanceParameters, holder: str +) -> None: + model = Model() + target: Coloured = { + "feature": model.feature, + "body": model.bodies[0], + "face": model.face, + }[holder] + target.values = GREEN + + result = await Harness(model).set_appearance(call) + + assert target.removed == 1 + assert result.data["reset"] is True + assert result.data["showing"]["level"] == "part" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "words"), + [ + (AppearanceParameters(feature="Nope", color="#000000"), "No feature named"), + (AppearanceParameters(body="Nope", color="#000000"), "No body named"), + (AppearanceParameters(face_point=[5, 5, 5], color="#000000"), "No face at"), + (AppearanceParameters(reset=True), "the part's colour is the base"), + ( + AppearanceParameters(feature="Boss-Extrude1", body="B", color="#000000"), + "Give one target", + ), + ], +) +async def test_refusals(call: AppearanceParameters, words: str) -> None: + result = await Harness(Model()).set_appearance(call) + + assert not result.is_success + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_a_colour_solidworks_drops_fails() -> None: + model = Model() + + class Forgetful(Coloured): + def SetMaterialPropertyValues2(self, values: Any, *rest: Any) -> None: + return None + + model.feature = Forgetful("Boss-Extrude1") + + result = await Harness(model).set_appearance( + AppearanceParameters(feature="Boss-Extrude1", color="#000000") + ) + + assert "did not keep the colour on the feature" in str(result.error) + + +@pytest.mark.asyncio +async def test_no_document() -> None: + harness = Harness(None) + + set_result = await harness.set_appearance(AppearanceParameters(color="#000000")) + get_result = await harness.get_appearance(AppearanceTarget()) + + assert set_result.error == get_result.error == "No active model" + + +def test_a_face_found_by_point_is_left_unselected() -> None: + model = Model() + + face = Harness(model)._face_at([0, 10, 0]) + + assert face is model.face + assert model.selected is None + + +def test_a_body_found_by_name_ignores_case() -> None: + body = Body("Block") + + assert Harness(Model([body]))._body_named("BLOCK") is body diff --git a/tests/solidworks_mcp/adapters/solidworks/test_com_utils.py b/tests/solidworks_mcp/adapters/solidworks/test_com_utils.py index ae46200e..28831ab6 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_com_utils.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_com_utils.py @@ -13,6 +13,7 @@ dispatch_array, double_array, long_array, + long_ref, string_array, strip_op_prefix, ) @@ -128,3 +129,25 @@ def no_pythoncom(name, *args, **kwargs): monkeypatch.setattr(builtins, "__import__", no_pythoncom) assert long_array([0, 1]) == (0, 1) + + +class TestLongRef: + def test_variant_on_windows(self, monkeypatch) -> None: + fake_w32 = SimpleNamespace(VARIANT=lambda vt, value: ("VARIANT", vt, value)) + monkeypatch.setitem( + sys.modules, "pythoncom", SimpleNamespace(VT_BYREF=0x4000, VT_I4=3) + ) + monkeypatch.setitem(sys.modules, "win32com", SimpleNamespace(client=fake_w32)) + monkeypatch.setitem(sys.modules, "win32com.client", fake_w32) + assert long_ref(2.0) == ("VARIANT", 0x4003, 2) + + def test_plain_int_without_pywin32(self, monkeypatch) -> None: + real_import = builtins.__import__ + + def no_pythoncom(name, *args, **kwargs): + if name == "pythoncom": + raise ImportError(name) + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", no_pythoncom) + assert long_ref() == 0 diff --git a/tests/solidworks_mcp/adapters/solidworks/test_reference_extras.py b/tests/solidworks_mcp/adapters/solidworks/test_reference_extras.py new file mode 100644 index 00000000..419a3529 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_reference_extras.py @@ -0,0 +1,208 @@ +"""Reference and analysis extras on fake COM objects shaped like SolidWorks 2026's. + +Spec: tools/reference-extras (queue item 39). The calls are the ones the +probes of 2026-11-28 measured. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from solidworks_mcp.adapters import sw_type_info +from solidworks_mcp.adapters.base import ( + BoundingBoxParameters, + CoordinateSystemParameters, + SectionPropertiesParameters, +) +from solidworks_mcp.adapters.solidworks import reference_extras + +from .appearance_fakes import Harness, Model, TreeFeature + + +@pytest.fixture(autouse=True) +def plain_com(monkeypatch: pytest.MonkeyPatch) -> None: + """No flagging; the by-reference status as a namespace.""" + monkeypatch.setattr(sw_type_info, "flagged", lambda obj, *_: obj) + monkeypatch.setattr( + reference_extras, "long_ref", lambda value=0: SimpleNamespace(value=7) + ) + + +@pytest.mark.asyncio +async def test_a_coordinate_system_at_a_sketch_point() -> None: + model = Model() + + result = await Harness(model).create_coordinate_system( + CoordinateSystemParameters(origin=[20, 10, 20]) + ) + + assert result.data == { + "name": "Coordinate System1", + "sketch": "3DSketch1", + "origin_mm": [20.0, 10.0, 20.0], + "x_axis": [1.0, 0.0, 0.0], + "y_axis": [0.0, 1.0, 0.0], + "z_axis": [0.0, 0.0, 1.0], + } + select = next(args for what, args in model.inserted if what == "select") + assert select[:2] == ("Point1@3DSketch1", "EXTSKETCHPOINT") + assert select[6] == 1 # the origin's mark + assert ("coordinate", (False, False, False)) in model.inserted + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("change", "words"), + [ + ({"origin": [0, 0]}, "origin must be"), + ({"point": None}, "drew no origin point"), + ({"made": None}, "made no coordinate system"), + ], +) +async def test_coordinate_system_failures(change: dict, words: str) -> None: + model = Model() + origin = change.pop("origin", [0, 0, 0]) + if "point" in change: + model.point = None + if "made" in change: + model.made["coordinate"] = None + + result = await Harness(model).create_coordinate_system( + CoordinateSystemParameters(origin=origin) + ) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_the_centre_of_mass_point() -> None: + result = await Harness(Model()).create_center_of_mass_point() + + assert result.data == { + "name": "Center of Mass", + "center_of_mass_mm": [0.0, 5.0, 0.0], + } + + +@pytest.mark.asyncio +async def test_an_unreadable_centre_is_none() -> None: + model = Model() + model.centre = None + + result = await Harness(model).create_center_of_mass_point() + + assert result.data["center_of_mass_mm"] is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("setup", "words"), + [ + ("no body", "no solid body"), + ("one already", "has a Center of Mass point already ('Center of Mass')"), + ("not made", "made no Center of Mass point"), + ], +) +async def test_centre_of_mass_failures(setup: str, words: str) -> None: + model = Model([] if setup == "no body" else None) + if setup == "one already": + model.tree = TreeFeature( + "Origin", + "OriginProfileFeature", + TreeFeature("Center of Mass", "CenterOfMass"), + ) + if setup == "not made": + model.made["com"] = None + + result = await Harness(model).create_center_of_mass_point() + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_the_bounding_box() -> None: + model = Model() + + result = await Harness(model).create_bounding_box( + BoundingBoxParameters(include_hidden=True) + ) + + assert result.data["size_mm"] == [40.0, 10.0, 40.0] + assert result.data["min_mm"] == [-20.0, 0.0, -20.0] + box_call = next(args for what, args in model.inserted if what == "box") + assert box_call[:3] == (0, True, False) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("setup", "words"), + [ + ("no body", "no solid body to box"), + ("one already", "has a bounding box already ('Bounding Box')"), + ("not made", "made no bounding box (status 7)"), + ], +) +async def test_bounding_box_failures(setup: str, words: str) -> None: + model = Model([] if setup == "no body" else None) + if setup == "one already": + model.tree = TreeFeature("Bounding Box", "BoundingBoxProfileFeat") + if setup == "not made": + model.made["box"] = None + + result = await Harness(model).create_bounding_box(BoundingBoxParameters()) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_a_face_section() -> None: + model = Model() + + result = await Harness(model).get_section_properties( + SectionPropertiesParameters(face_point=[0, 10, 0]) + ) + + assert result.data["area_mm2"] == pytest.approx(1600) + assert result.data["face_point"] == [0, 10, 0] + assert model.selected is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("point", "section", "words"), + [ + ([0, 0], None, "face_point must be"), + ([5, 5, 5], None, "No face at"), + ([0, 10, 0], [1.0] + [0.0] * 23, "couldn't take a section"), + ], +) +async def test_section_failures(point: list, section: list | None, words: str) -> None: + model = Model() + if section is not None: + model.section = section + + result = await Harness(model).get_section_properties( + SectionPropertiesParameters(face_point=point) + ) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_no_document() -> None: + harness = Harness(None) + + results = [ + await harness.create_coordinate_system( + CoordinateSystemParameters(origin=[0, 0, 0]) + ), + await harness.create_center_of_mass_point(), + await harness.create_bounding_box(BoundingBoxParameters()), + await harness.get_section_properties( + SectionPropertiesParameters(face_point=[0, 0, 0]) + ), + ] + + assert {r.error for r in results} == {"No active model"} diff --git a/tests/solidworks_mcp/adapters/test_appearance_rules.py b/tests/solidworks_mcp/adapters/test_appearance_rules.py new file mode 100644 index 00000000..cd81a21b --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_appearance_rules.py @@ -0,0 +1,155 @@ +"""The rules the appearance and reference-extras adapters share (queue items 36, 39). + +Spec: tools/appearance and tools/reference-extras. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from solidworks_mcp.adapters import appearance_rules as rules +from solidworks_mcp.adapters.base import AppearanceParameters, AppearanceTarget +from solidworks_mcp.exceptions import InputRefused + + +@pytest.mark.parametrize( + ("target", "kind"), + [ + (AppearanceTarget(), "part"), + (AppearanceTarget(feature="Boss-Extrude1"), "feature"), + (AppearanceTarget(body="Body1"), "body"), + (AppearanceTarget(face_point=[0, 10, 0]), "face"), + ], +) +def test_one_target(target: AppearanceTarget, kind: str) -> None: + assert rules.target_kind(target) == kind + + +@pytest.mark.parametrize( + ("target", "words"), + [ + (AppearanceTarget(feature="F", body="B"), "not feature and body"), + (AppearanceTarget(face_point=[1, 2]), "face_point must be [x, y, z]"), + ], +) +def test_bad_targets_are_refused(target: AppearanceTarget, words: str) -> None: + with pytest.raises(InputRefused, match=words.replace("[", r"\[")): + rules.target_kind(target) + + +@pytest.mark.parametrize( + ("value", "rgb"), + [ + ("#1fcc33", (31, 204, 51)), + ("1FCC33", (31, 204, 51)), + ([25, 76, 242], (25, 76, 242)), + ], +) +def test_colours_parse(value: Any, rgb: tuple[int, int, int]) -> None: + assert rules.parse_color(value) == rgb + + +@pytest.mark.parametrize( + ("value", "words"), + [ + (None, "Give a color"), + ("#12", "is not '#rrggbb'"), + ([1, 2], r"must be \[r, g, b\]"), + ([0, 0, 256], r"must be \[r, g, b\]"), + ], +) +def test_bad_colours_are_refused(value: Any, words: str) -> None: + with pytest.raises(InputRefused, match=words): + rules.parse_color(value) + + +def test_a_set_call_returns_its_target() -> None: + assert rules.check_set(AppearanceParameters(color="#000000")) == "part" + assert rules.check_set(AppearanceParameters(feature="F", reset=True)) == "feature" + + +@pytest.mark.parametrize( + ("params", "words"), + [ + (AppearanceParameters(reset=True), "the part's colour is the base"), + ( + AppearanceParameters(feature="F", reset=True, color="#000000"), + "not both", + ), + (AppearanceParameters(color="#000000", transparency=1.5), "transparency"), + (AppearanceParameters(), "Give a color"), + ], +) +def test_bad_set_calls_are_refused(params: AppearanceParameters, words: str) -> None: + with pytest.raises(InputRefused, match=words): + rules.check_set(params) + + +def test_material_values_keep_solidworks_shading() -> None: + values = rules.material_values((255, 0, 51), 0.25) + + assert values == [1.0, 0.0, 0.2, 1.0, 1.0, 0.5, 0.3125, 0.25, 0.0] + + +@pytest.mark.parametrize( + ("values", "reply"), + [ + (None, None), + ([-1.0] * 9, None), + ([1, 2], None), + ( + [0.1, 0.8, 0.2, 1, 1, 0.5, 0.3125, 0.4, 0], + {"color": [26, 204, 51], "hex": "#1acc33", "transparency": 0.4}, + ), + ], +) +def test_colours_read_back(values: Any, reply: dict[str, Any] | None) -> None: + assert rules.color_reply(values) == reply + + +def test_a_section_in_mm() -> None: + # A 40 mm square at y = 10, as SolidWorks 2026 gave it. + values = [0.0, 0.0016, 0.0, 0.01, 0.0] + values += [2.1333e-7, 4.2667e-7, 2.1333e-7, 0.0, 0.0, 0.0, 4.2667e-7, 0.0] + values += [2.1333e-7, 2.1333e-7] + [0.0] * 9 + + reply = rules.section_reply(values) + + assert reply["area_mm2"] == pytest.approx(1600) + assert reply["centroid_mm"] == pytest.approx([0, 10, 0]) + assert reply["ixx"] == pytest.approx(213330) + assert reply["polar_moment_mm4"] == pytest.approx(426670) + assert reply["principal_moments_mm4"] == pytest.approx([213330, 213330]) + + +@pytest.mark.parametrize( + ("values", "words"), + [(None, "gave no section properties"), ([1.0] + [0.0] * 23, "status 1")], +) +def test_a_failed_section_is_refused(values: Any, words: str) -> None: + with pytest.raises(InputRefused, match=words): + rules.section_reply(values) + + +def test_a_transform_in_mm() -> None: + array = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0.02, 0.01, -0.005, 1, 0, 0, 0] + + reply = rules.transform_reply(array) + + assert reply == { + "origin_mm": [20.0, 10.0, -5.0], + "x_axis": [1.0, 0.0, 0.0], + "y_axis": [0.0, 1.0, 0.0], + "z_axis": [0.0, 0.0, 1.0], + } + + +def test_an_unreadable_transform_fails() -> None: + with pytest.raises(RuntimeError, match="transform"): + rules.transform_reply(None) + + +def test_model_axes() -> None: + assert rules.model_axes()["z_axis"] == [0.0, 0.0, 1.0] diff --git a/tests/solidworks_mcp/adapters/test_base_appearance.py b/tests/solidworks_mcp/adapters/test_base_appearance.py new file mode 100644 index 00000000..ca0f85d8 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_base_appearance.py @@ -0,0 +1,20 @@ +"""The appearance and reference methods (queue items 36, 39) on the base adapter: none is implemented there.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from .appearance_calls import CALLS, IDS +from .test_base_part_features import _bare + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_method_names_itself_as_missing( + name: str, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> None: + result = await getattr(_bare(), name)(*args, **kwargs) + + assert result.error == f"{name} is not implemented by this adapter" diff --git a/tests/solidworks_mcp/adapters/test_circuit_breaker_appearance.py b/tests/solidworks_mcp/adapters/test_circuit_breaker_appearance.py new file mode 100644 index 00000000..aa03a3b0 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_circuit_breaker_appearance.py @@ -0,0 +1,25 @@ +"""The appearance and reference methods (queue items 36, 39) pass through the circuit breaker unchanged.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from solidworks_mcp.adapters.circuit_breaker import CircuitBreakerAdapter + +from .appearance_calls import CALLS, IDS, recorder + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_method_passes_through( + name: str, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> None: + result = await getattr(CircuitBreakerAdapter(adapter=recorder()), name)( + *args, **kwargs + ) + + received = result.data[name][0] + assert received[: len(args)] == args + assert all(value in received for value in kwargs.values()) diff --git a/tests/solidworks_mcp/adapters/test_connection_pool_appearance.py b/tests/solidworks_mcp/adapters/test_connection_pool_appearance.py new file mode 100644 index 00000000..aad75c06 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_connection_pool_appearance.py @@ -0,0 +1,28 @@ +"""The appearance and reference methods (queue items 36, 39) pass through the connection pool unchanged.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from solidworks_mcp.adapters.connection_pool import ConnectionPoolAdapter + +from .appearance_calls import CALLS, IDS, recorder + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_method_passes_through( + name: str, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> None: + pool = ConnectionPoolAdapter(adapter_factory=recorder, max_size=1) + await pool.connect() + try: + result = await getattr(pool, name)(*args, **kwargs) + finally: + await pool.disconnect() + + received = result.data[name][0] + assert received[: len(args)] == args + assert all(value in received for value in kwargs.values()) diff --git a/tests/solidworks_mcp/adapters/test_mock_appearance.py b/tests/solidworks_mcp/adapters/test_mock_appearance.py new file mode 100644 index 00000000..3768596d --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_mock_appearance.py @@ -0,0 +1,127 @@ +"""The mock adapter's colours (queue item 36). Spec: tools/appearance.""" + +from __future__ import annotations + +import pytest + +from solidworks_mcp.adapters.base import ( + AppearanceParameters, + AppearanceTarget, + ExtrusionParameters, +) +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.adapters.mock_appearance import face_of +from solidworks_mcp.exceptions import InputRefused + + +@pytest.fixture +async def block() -> MockSolidWorksAdapter: + """A mock 40 x 40 x 10 block, its box from z 0 to 10.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + await adapter.add_rectangle(-20, -20, 20, 20) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=10)) + return adapter + + +@pytest.mark.asyncio +async def test_a_new_part_shows_its_default_colour( + block: MockSolidWorksAdapter, +) -> None: + result = await block.get_appearance(AppearanceTarget()) + + assert result.data["level"] == "part" + assert result.data["hex"] == "#e4e4e4" + + +@pytest.mark.asyncio +async def test_a_face_over_its_feature_over_its_body( + block: MockSolidWorksAdapter, +) -> None: + feature = (await block.list_bodies()).data["bodies"][0]["name"] + await block.set_appearance(AppearanceParameters(body=feature, color="#f28c1a")) + await block.set_appearance(AppearanceParameters(feature=feature, color="#1fcc33")) + top = await block.set_appearance( + AppearanceParameters(face_point=[0, 0, 10], color=[25, 76, 242]) + ) + + side = await block.get_appearance(AppearanceTarget(face_point=[20, 0, 5])) + face = await block.get_appearance(AppearanceTarget(face_point=[0, 0, 10])) + body = await block.get_appearance(AppearanceTarget(body=feature)) + + assert top.data == { + "target": "face", + "face_point": [0, 0, 10], + "color": [25, 76, 242], + "hex": "#194cf2", + "transparency": 0.0, + } + assert (side.data["level"], side.data["hex"]) == ("feature", "#1fcc33") + assert (face.data["level"], face.data["hex"]) == ("face", "#194cf2") + assert (body.data["level"], body.data["hex"]) == ("body", "#f28c1a") + + +@pytest.mark.asyncio +async def test_a_reset_shows_the_level_above(block: MockSolidWorksAdapter) -> None: + feature = (await block.list_bodies()).data["bodies"][0]["name"] + await block.set_appearance(AppearanceParameters(feature=feature, color="#1fcc33")) + await block.set_appearance( + AppearanceParameters(face_point=[0, 0, 10], color="#000000") + ) + + result = await block.set_appearance( + AppearanceParameters(face_point=[0, 0, 10], reset=True) + ) + + assert result.data["reset"] is True + assert result.data["showing"]["level"] == "feature" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "words"), + [ + (AppearanceParameters(feature="Nope", color="#000000"), "No feature named"), + (AppearanceParameters(body="Nope", color="#000000"), "No body named"), + (AppearanceParameters(face_point=[99, 0, 0], color="#000000"), "No face at"), + (AppearanceParameters(reset=True), "the part's colour is the base"), + ], +) +async def test_refusals( + block: MockSolidWorksAdapter, call: AppearanceParameters, words: str +) -> None: + result = await block.set_appearance(call) + + assert not result.is_success + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_a_bad_target_is_refused_on_read(block: MockSolidWorksAdapter) -> None: + result = await block.get_appearance(AppearanceTarget(feature="F", body="B")) + + assert "Give one target" in str(result.error) + + +@pytest.mark.asyncio +async def test_no_document() -> None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + + set_result = await adapter.set_appearance(AppearanceParameters(color="#000000")) + get_result = await adapter.get_appearance(AppearanceTarget()) + + assert set_result.error == get_result.error == "No active model" + + +def test_a_point_inside_a_box_is_on_no_face() -> None: + from solidworks_mcp.adapters.body_rules import BodyState + + box = BodyState("B", 1000.0, (0, 0, 0), (10, 10, 10)) + + assert face_of([box], [10, 5, 5])[1:] == (0, 1) + with pytest.raises(InputRefused): + face_of([box], [5, 5, 5]) diff --git a/tests/solidworks_mcp/adapters/test_mock_reference_extras.py b/tests/solidworks_mcp/adapters/test_mock_reference_extras.py new file mode 100644 index 00000000..160c8e2d --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_mock_reference_extras.py @@ -0,0 +1,145 @@ +"""The mock adapter's reference and analysis extras (queue item 39). + +Spec: tools/reference-extras. +""" + +from __future__ import annotations + +import pytest + +from solidworks_mcp.adapters.base import ( + BoundingBoxParameters, + CoordinateSystemParameters, + ExtrusionParameters, + SectionPropertiesParameters, +) +from solidworks_mcp.adapters.body_rules import BodyState +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.adapters.mock_reference_extras import rectangle_section + + +async def _part(boxes: int) -> MockSolidWorksAdapter: + """A mock part with ``boxes`` 40 x 40 x 10 blocks (0 for none).""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + for _ in range(boxes): + await adapter.create_sketch("Top") + await adapter.add_rectangle(-20, -20, 20, 20) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=10)) + return adapter + + +@pytest.mark.asyncio +async def test_a_coordinate_system_counts_up() -> None: + adapter = await _part(1) + + first = await adapter.create_coordinate_system( + CoordinateSystemParameters(origin=[20, 10, 20]) + ) + second = await adapter.create_coordinate_system( + CoordinateSystemParameters(origin=[0, 0, 0]) + ) + + assert first.data["name"] == "Coordinate System1" + assert first.data["origin_mm"] == [20.0, 10.0, 20.0] + assert first.data["x_axis"] == [1.0, 0.0, 0.0] + assert second.data["sketch"] == "3DSketch2" + + +@pytest.mark.asyncio +async def test_the_centre_of_mass_once() -> None: + adapter = await _part(1) + + first = await adapter.create_center_of_mass_point() + second = await adapter.create_center_of_mass_point() + + assert first.data == {"name": "Center of Mass", "center_of_mass_mm": [0, 0, 5]} + assert "already" in str(second.error) + + +@pytest.mark.asyncio +async def test_the_bounding_box_once() -> None: + adapter = await _part(1) + + first = await adapter.create_bounding_box(BoundingBoxParameters()) + second = await adapter.create_bounding_box(BoundingBoxParameters()) + + assert first.data["size_mm"] == [40, 40, 10] + assert "already" in str(second.error) + + +@pytest.mark.asyncio +async def test_a_top_face_section() -> None: + adapter = await _part(1) + + result = await adapter.get_section_properties( + SectionPropertiesParameters(face_point=[0, 0, 10]) + ) + + assert result.data["area_mm2"] == 1600 + assert result.data["centroid_mm"] == [0, 0, 10] + assert result.data["ixx"] == pytest.approx(40**4 / 12, abs=0.01) + assert result.data["polar_moment_mm4"] == pytest.approx(40**4 / 6, abs=0.01) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("point", "words"), + [([0, 0], "face_point must be"), ([0, 0, 5], "No face at")], +) +async def test_a_bad_section_point(point: list[float], words: str) -> None: + adapter = await _part(1) + + result = await adapter.get_section_properties( + SectionPropertiesParameters(face_point=point) + ) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_no_body() -> None: + adapter = await _part(0) + + com = await adapter.create_center_of_mass_point() + box = await adapter.create_bounding_box(BoundingBoxParameters()) + cs = await adapter.create_coordinate_system( + CoordinateSystemParameters(origin=[0, 0]) + ) + + assert "no solid body" in str(com.error) + assert "no solid body" in str(box.error) + assert "origin must be" in str(cs.error) + + +@pytest.mark.asyncio +async def test_no_document() -> None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + + results = [ + await adapter.create_coordinate_system( + CoordinateSystemParameters(origin=[0, 0, 0]) + ), + await adapter.create_center_of_mass_point(), + await adapter.create_bounding_box(BoundingBoxParameters()), + await adapter.get_section_properties( + SectionPropertiesParameters(face_point=[0, 0, 0]) + ), + ] + + assert {r.error for r in results} == {"No active model"} + + +def test_a_side_face_section() -> None: + box = BodyState("B", 4000.0, (0, 0, 0), (20, 10, 20)) + + reply = rectangle_section(box, 0, 0) + + assert reply["area_mm2"] == 200 + assert reply["centroid_mm"] == [0, 5, 10] + assert reply["principal_moments_mm4"] == pytest.approx( + [200 * 10**2 / 12, 200 * 20**2 / 12], abs=0.01 + ) diff --git a/tests/solidworks_mcp/tools/test_appearance.py b/tests/solidworks_mcp/tools/test_appearance.py new file mode 100644 index 00000000..0b456e4c --- /dev/null +++ b/tests/solidworks_mcp/tools/test_appearance.py @@ -0,0 +1,85 @@ +"""The appearance tools on the mock adapter (queue item 36). Spec: tools/appearance.""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastmcp import FastMCP +from pydantic import ValidationError + +from solidworks_mcp.adapters.base import ExtrusionParameters +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.tools.appearance import ( + AppearanceTargetInput, + SetAppearanceInput, + register_appearance_tools, +) + + +async def _tools(adapter: Any) -> dict[str, Any]: + mcp = FastMCP("appearance") + assert await register_appearance_tools(mcp, adapter, {}) == 2 + return {t.name: t.fn for t in await mcp.list_tools()} + + +@pytest.fixture +async def block() -> MockSolidWorksAdapter: + """A mock 40 x 40 x 10 block.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + await adapter.add_rectangle(-20, -20, 20, 20) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=10)) + return adapter + + +@pytest.mark.asyncio +async def test_colour_a_face_then_reset_it(block: MockSolidWorksAdapter) -> None: + tools = await _tools(block) + + whole = await tools["set_appearance"]({"color": [200, 0, 0]}) + face = await tools["set_appearance"]( + SetAppearanceInput(face_point=[0, 0, 10], color="#1f77b4") + ) + reset = await tools["set_appearance"]({"face_point": [0, 0, 10], "reset": True}) + + assert whole["message"] == "Coloured: #c80000 on the part" + assert face["message"] == "Coloured: #1f77b4 on face [0.0, 0.0, 10.0]" + assert reset["message"] == "Removed the face's colour; #c80000 from the part shows" + + +@pytest.mark.asyncio +async def test_read_the_part_and_a_face(block: MockSolidWorksAdapter) -> None: + tools = await _tools(block) + + part = await tools["get_appearance"]() + face = await tools["get_appearance"](AppearanceTargetInput(face_point=[0, 0, 10])) + + assert part["message"] == "#e4e4e4 on the part, from the part" + assert face["appearance"]["level"] == "part" + + +@pytest.mark.asyncio +async def test_two_targets_are_an_error_reply(block: MockSolidWorksAdapter) -> None: + reply = await (await _tools(block))["set_appearance"]( + {"feature": "A", "body": "B", "color": "#000000"} + ) + + assert reply["status"] == "error" + assert reply["error_type"] == "invalid_input" + + +@pytest.mark.parametrize( + "values", + [ + {"color": "#000000", "transparency": 2}, + {"color": "#000000", "face_point": [1, 2]}, + {"feature": ""}, + ], +) +def test_inputs_are_strict(values: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + SetAppearanceInput(**values) diff --git a/tests/solidworks_mcp/tools/test_error_classifier.py b/tests/solidworks_mcp/tools/test_error_classifier.py index bf606466..aef3b88e 100644 --- a/tests/solidworks_mcp/tools/test_error_classifier.py +++ b/tests/solidworks_mcp/tools/test_error_classifier.py @@ -90,6 +90,24 @@ def classifier() -> ErrorClassifier: "feature_not_built", ), ("No body named 'Nope'. Bodies in the part: Block.", "invalid_input"), + ("Give one target, not feature and body: a feature", "invalid_input"), + ("No feature named 'X'; list_features names them.", "invalid_input"), + ("No face at [1, 2, 3] mm; give a point on the face's", "invalid_input"), + ("color '#12' is not '#rrggbb'.", "invalid_input"), + ("color [1, 2] must be [r, g, b], each 0 to 255.", "invalid_input"), + ("Give a color, [r, g, b] 0-255 or '#rrggbb'", "invalid_input"), + ("reset removes a feature's, body's or face's own colour", "invalid_input"), + ("transparency must be 0 (opaque) to 1 (clear), not 2.", "invalid_input"), + ("origin must be [x, y, z] in mm.", "invalid_input"), + ("The part has no solid body to box.", "invalid_input"), + ("The part has a bounding box already ('Bounding Box')", "invalid_input"), + ("SolidWorks couldn't take a section of that face (status 1)", "invalid_input"), + ("SolidWorks made no coordinate system.", "feature_not_built"), + ( + "SolidWorks drew no origin point for the coordinate system.", + "feature_not_built", + ), + ("SolidWorks did not keep the colour on the face.", "feature_not_built"), ("Give a translate or a rotate, not both", "invalid_input"), ("That would delete every body in the part", "invalid_input"), ("A scale of 1 on every axis does nothing.", "invalid_input"), diff --git a/tests/solidworks_mcp/tools/test_reference_extras.py b/tests/solidworks_mcp/tools/test_reference_extras.py new file mode 100644 index 00000000..f97183ab --- /dev/null +++ b/tests/solidworks_mcp/tools/test_reference_extras.py @@ -0,0 +1,85 @@ +"""The reference and analysis extras on the mock adapter (queue item 39). + +Spec: tools/reference-extras. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastmcp import FastMCP +from pydantic import ValidationError + +from solidworks_mcp.adapters.base import ExtrusionParameters +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.tools.reference_extras import ( + BoundingBoxInput, + CoordinateSystemInput, + SectionPropertiesInput, + register_reference_extras_tools, +) + + +async def _tools(adapter: Any) -> dict[str, Any]: + mcp = FastMCP("reference") + assert await register_reference_extras_tools(mcp, adapter, {}) == 4 + return {t.name: t.fn for t in await mcp.list_tools()} + + +@pytest.fixture +async def block() -> MockSolidWorksAdapter: + """A mock 40 x 40 x 10 block, its box from z 0 to 10.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + await adapter.add_rectangle(-20, -20, 20, 20) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=10)) + return adapter + + +@pytest.mark.asyncio +async def test_each_extra_on_a_block(block: MockSolidWorksAdapter) -> None: + tools = await _tools(block) + + frame = await tools["create_coordinate_system"]( + CoordinateSystemInput(origin=[20, 10, 20]) + ) + com = await tools["create_center_of_mass_point"]() + box = await tools["create_bounding_box"](BoundingBoxInput()) + default_box = await tools["create_bounding_box"]() + section = await tools["get_section_properties"]( + SectionPropertiesInput(face_point=[0, 0, 10]) + ) + + assert frame["message"] == "Coordinate System1 at (20, 10, 20) mm" + assert com["message"] == "Center of Mass at (0, 0, 5) mm" + assert box["message"] == "Bounding Box: 40 x 40 x 10 mm" + assert default_box["error_type"] == "invalid_input" + assert section["message"] == "Area 1,600.00 mm², centroid (0, 0, 10) mm" + + +@pytest.mark.asyncio +async def test_a_point_on_no_face_is_an_error_reply( + block: MockSolidWorksAdapter, +) -> None: + reply = await (await _tools(block))["get_section_properties"]( + {"face_point": [0, 0, 5]} + ) + + assert reply["status"] == "error" + assert reply["error_type"] == "invalid_input" + + +@pytest.mark.parametrize( + ("model", "values"), + [ + (CoordinateSystemInput, {"origin": [1, 2]}), + (SectionPropertiesInput, {"face_point": [1, 2, 3, 4]}), + ], +) +def test_inputs_are_strict(model: type, values: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + model(**values)