diff --git a/CHANGELOG.md b/CHANGELOG.md index a141c653..491b4cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Modelled threads** (queue item 43): `list_thread_sizes` lists the + sizes SolidWorks's own thread profiles hold, metric or inch (M1.2 to + M64, #0 to 4 in), each with coarse or fine pitch, the ISO 68-1 basic depth + and the ISO 3508 runout (normal 2.5P, short 1.25P; for inch the same rule + on 1/TPI, labelled a reasoned default). `create_thread` cuts an external + (die) or internal (tap) thread with SolidWorks's Thread feature at the + circular edge picked by a point, checks the cylinder's diameter against + the size first, and fails and undoes a thread that cuts nothing. Its + `runout` ends the thread as a machined one: `fade` sweeps the groove out + of the material (any thread: straight along the helix's tangent on a rod, + so the round rod tapers it to a point; along an arc over DIN 76-1's x1 + in a hole), and `undercut_a` / + `undercut_b` cut a DIN 76-1 Form A or B undercut (dg, g2, r from + DIN 76-1:2025-10 Table 1, a 30° flank) at the shoulder of an external + metric thread. Its `lead_in` chamfers the other end, the start, 45° to + just under the minor diameter (ISO 4753's chamfered end; M6: 4.7 mm), so + a bolt starts in a nut. Every thread starts two pitches outside the + part, so its groove runs out through the end face. `create_hole`'s description points to it for + fasteners. 173 tools in + all. Beta until the live demo; the live tests pass on SolidWorks 2026 + (an M6 rod, a 1/4-20 rod, an M6 tapped hole, a faded M6 and an M6 with + a Form A undercut at a collar). - **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; diff --git a/README.md b/README.md index c51ab390..845f1ad8 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 171 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 173 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 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). +All 173 tools cost about 73,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/modelled-threads/test_a_bolt_like_rod-motion.gif b/docs/assets/demos/modelled-threads/test_a_bolt_like_rod-motion.gif new file mode 100644 index 00000000..8d620e87 Binary files /dev/null and b/docs/assets/demos/modelled-threads/test_a_bolt_like_rod-motion.gif differ diff --git a/docs/assets/demos/modelled-threads/test_thread_runouts-motion.gif b/docs/assets/demos/modelled-threads/test_thread_runouts-motion.gif new file mode 100644 index 00000000..08a43525 Binary files /dev/null and b/docs/assets/demos/modelled-threads/test_thread_runouts-motion.gif differ diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index 7d7986a0..59f9d620 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,9 +1,9 @@ { "tools": { - "total": 171, + "total": 173, "by_level": { "stable": 149, - "beta": 14, + "beta": 16, "experimental": 0, "planned": 0, "deprecated": 8 @@ -485,6 +485,13 @@ "reason": "", "summary": "Place a model's three standard views (front, top and side) on the active drawing sheet in one call." }, + { + "name": "create_thread", + "family": "threads", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "Cut a modelled thread, external (a bolt) or internal (a tapped hole), at a standard size." + }, { "name": "delete_bodies", "family": "bodies", @@ -835,6 +842,13 @@ "reason": "", "summary": "List every document open in SolidWorks and say which one is active." }, + { + "name": "list_thread_sizes", + "family": "threads", + "level": "beta", + "reason": "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + "summary": "List the standard thread sizes SolidWorks holds, metric or inch, with coarse or fine pitch, depth and runout." + }, { "name": "load_assembly", "family": "file_management", @@ -1215,7 +1229,7 @@ "total": 2838 }, "api": { - "covered": 350, + "covered": 354, "total": 5985 }, "interfaces": [ diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index fd1d494e..2e19b9eb 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,12 +21,12 @@ -MCP tools: 163 +MCP tools: 165 100% work on SolidWorks today - - + + @@ -35,7 +35,7 @@ stable 149 -beta 14 +beta 16 experimental 0 @@ -51,5 +51,5 @@ -Whole API: 350 of 5,985 method names (5.8%), counted by a text scan of the adapters. +Whole API: 354 of 5,985 method names (5.9%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index fbdd0563..f61da110 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -70,6 +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. +create_threadthreadsbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.Cut a modelled thread, external (a bolt) or internal (a tapped hole), at a standard size. 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. @@ -120,6 +121,7 @@ list_hole_sizesmodelingstableList the Hole Wizard's hole types and sizes for a standard, or one size's dimensions. list_model_dimensionsengineering_datastableList every dimension in the active part or assembly with its full name and value. list_open_documentsfile_managementstableList every document open in SolidWorks and say which one is active. +list_thread_sizesthreadsbeta
new: checked on SolidWorks by a scratch run, not yet by a live demo.List the standard thread sizes SolidWorks holds, metric or inch, with coarse or fine pitch, depth and runout. load_assemblyfile_managementdeprecated
use `open_model`.Open an assembly (.sldasm) from disk and make it the active document. load_partfile_managementdeprecated
use `open_model`.Open a part (.sldprt) from disk and make it the active document. lookup_api_interfacedocs_discoverystableList every method and property of a SolidWorks COM interface. diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index d1721877..7185f483 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` | 171 | 279 KB | 71,512 | 100% | -| `core` | `list` | 130 | 202 KB | 51,608 | 72% | +| `all` | `list` | 173 | 284 KB | 72,744 | 100% | +| `core` | `list` | 132 | 206 KB | 52,841 | 73% | | `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 | 5% | -| `core,drawing` | `list` | 152 | 241 KB | 61,682 | 86% | +| `core,drawing` | `list` | 154 | 246 KB | 62,915 | 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 b75bef30..8f5d2051 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -1118,6 +1118,68 @@ be used instead. 4. `create_cut_sweep({"path": "Helix/Spiral1", "profile": "Helix/Spiral1"})`, refused on purpose 5. `create_cut_sweep({"path": "Helix/Spiral1", "profile": "Sketch3"})` +## Modelled threads {#threads} + +Source: [`tests/live/test_live_sw_threads.py`](https://github.com/andrewbartels1/SolidworksMCP-python/blob/main/tests/live/test_live_sw_threads.py). + +### A bolt-like rod {#bolt-like-rod} + +![The standard metric sizes read from SolidWorks, M10 refused on a 6 mm rod, an M6x1.0 thread cut 12 mm with its start chamfered 45 degrees, and a 1/4-20 inch thread, each seen side on](assets/demos/modelled-threads/test_a_bolt_like_rod-motion.gif) + +> *Example prompt:* Thread the end of this 6 mm rod M6 for 12 mm, chamfered +> so it starts in a nut. + +**What it shows.** `list_thread_sizes` reads the sizes from SolidWorks's +own die profile, and `create_thread` cuts one of them with SolidWorks's +Thread feature. The thread starts two pitches outside the rod, as a die +does, so its groove runs out through the end face; `lead_in` then chamfers +that end 45° to just under the minor diameter (ISO 4753's chamfered end): + +| Step | Tools | Expected | Measured | +| --- | --- | --- | --- | +| The metric sizes | `list_thread_sizes` | M3x0.5 first, ISO 68-1 depth, ISO 3508 runout | 69 sizes; M3x0.5: depth 0.2706 mm, runout 1.25 mm | +| M10 on a 6 mm rod | `create_thread` | refused, nothing built | `invalid_input`: "wants a rod of about 10 mm" | +| M6x1.0, 12 mm, `lead_in` | `create_thread` | full thread y 13 to 25; end 4.7 mm, 0.65 mm long | y 13 to 25; 4.7 mm, 0.65 mm | +| 1/4-20 on a 6.35 mm rod | `create_thread` | 1.27 mm pitch, 12.7 mm | 1.27 mm; y 12.3 to 25 | + +M10 is refused **on purpose**: the edge is 6 mm across. + +**Tool calls** + +1. `list_thread_sizes({"standard": "metric"})` +2. A 6 mm rod 25 mm long, then `create_thread({"size": "M10x1.5", "edge_point": [3, 25, 0], "length": 12})`, refused on purpose +3. `create_thread({"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "lead_in": true})` +4. A 6.35 mm rod, then `create_thread({"standard": "inch", "size": "1/4-20", "edge_point": [3.175, 25, 0], "length": 12.7})` + +### Runouts and a lead-in {#thread-runouts} + +![An M6 thread whose groove fades out along the helix's tangent, an M6 bolt to a collar ending in a DIN 76-1 Form A undercut with its free end chamfered, and an undercut in a tapped hole refused](assets/demos/modelled-threads/test_thread_runouts-motion.gif) + +> *Example prompt:* Thread this M6 bolt up to its collar with a DIN 76-1 +> undercut there, and chamfer its end. + +**What it shows.** How a thread ends at the shoulder. `fade` cuts the +groove's end straight along the helix's tangent, out past the rod: the +straight cut leaves the round rod, so the groove tapers to a point. +`undercut_a` cuts DIN 76-1's Form A groove at the collar instead. The other +end, where the bolt enters a nut, is chamfered by `lead_in`: + +| Step | Tools | Expected | Measured | +| --- | --- | --- | --- | +| M6x1.0, 12 mm, `fade` | `create_thread` | tangent; runs out over √(r² − (r − h)²) = 1.72 mm | tangent, 1.72 mm, −0.32 mm³ | +| M6x1.0 to a 10 mm collar, `undercut_a` | `create_thread` | DIN 76-1 Table 1: dg 4.4, g2 3.5, r 0.5, 30° flank | dg 4.4, g2 3.5, r 0.5, 30° | +| Its free end, `lead_in` | `create_thread` | 45° to 4.7 mm, 0.65 mm long | 4.7 mm, 0.65 mm, −1.38 mm³ | +| An undercut in a tapped hole | `create_thread` | refused, nothing built | `invalid_input`: "external metric threads only" | + +The undercut in a tapped hole is refused **on purpose**: DIN 76-1's table is +for external threads. + +**Tool calls** + +1. A 6 mm rod 25 mm long, then `create_thread({"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "runout": "fade"})` +2. A 6 mm rod 25 mm long on a 10 mm collar 6 mm long, then `create_thread({"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 25, "runout": "undercut_a", "lead_in": true})` +3. On the same part, `create_thread({"kind": "internal", "size": "M6x1.0", "edge_point": [2.5, 15, 0], "length": 10, "runout": "undercut_a"})`, refused on purpose + ## Several bodies {#bodies} Source: [`tests/live/test_live_sw_multi_body.py`](https://github.com/andrewbartels1/SolidworksMCP-python/blob/main/tests/live/test_live_sw_multi_body.py). diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 3348795d..c5311e6f 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, colours, reference geometry, sketching, files, measuring and checking, materials and properties, export, the circuit-breaker reset | +| `core` | Parts and assemblies: modelling, equations, multi-body tools, threads, 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 855acf76..d0cedad8 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. -🚀 **171 Tools** | 🤖 **Agent-Ready Workflows** | ⚡ **Automatic COM/VBA Routing** | 🧪 **Schema-Validated Prompt Runs** +🚀 **173 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 -- 171 tools across modeling, multi-body parts, colours, reference geometry, assemblies, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 173 tools across modeling, multi-body parts, modelled threads, 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 3263756b..b46ab7a8 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -36,10 +36,11 @@ ## Tool Catalog -- [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. +- [Tool Catalog — All 173 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **173 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. +- [Thread Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/threads/): Modelled threads at standard sizes: external (a bolt or rod) and internal (a tapped hole). - [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. diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index e3734757..46d24b0d 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,6 +1,6 @@ -# Tool Catalog — All 171 Tools +# Tool Catalog — All 173 Tools -This reference documents all **171 MCP tools** registered by the SolidWorks MCP server. +This reference documents all **173 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,7 @@ 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. | +| [Thread Tools](threads.md) | 2 | Modelled threads at standard sizes, external or internal, with coarse or fine pitch, the ISO 68-1 depth and the ISO 3508 runout. | | [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. | diff --git a/docs/user-guide/tool-catalog/threads.md b/docs/user-guide/tool-catalog/threads.md new file mode 100644 index 00000000..33a4459a --- /dev/null +++ b/docs/user-guide/tool-catalog/threads.md @@ -0,0 +1,104 @@ +# Thread Tools + +Modelled threads at standard sizes: external (a bolt or rod) and internal (a tapped hole). + +> **Prerequisite:** SolidWorks running (the sizes are read from its thread profiles); for `create_thread`, an open part with the rod or hole. + +**Total tools in this category: 2** + +The sizes are the ones SolidWorks's own thread profiles hold (Tools > Options > File Locations > Thread Profiles): Metric Die and Metric Tap, Inch Die and Inch Tap. Every size `list_thread_sizes` gives works in `create_thread`. + +For each size the tools give: + +- **Coarse or fine.** Metric coarse pitches come from SolidWorks's Hole Wizard library (its plain `M6` rows); elsewhere the coarsest pitch listed at a diameter is coarse and the others fine, and a diameter with one size is `only`. +- **The basic thread depth**, ISO 68-1: 0.541266 × pitch (5/8 of the 60° profile's fundamental triangle). Inch threads share the profile. +- **The runout**, the incomplete thread to leave before a shoulder: ISO 3508's normal 2.5 × pitch and short 1.25 × pitch. For inch threads the same rule is applied to the inch pitch (25.4 / TPI), a reasoned default rather than a standard; `runout_basis` says which. `create_thread`'s `runout` models it: a fade or a DIN 76-1 undercut (below). + +`add_cosmetic_thread` remains for a thread shown only in drawings; `create_hole` makes the tap drill for an internal thread. + +--- + +### `list_thread_sizes` + +List the standard thread sizes SolidWorks holds, metric or inch, with coarse or fine pitch, depth and runout. + +Each entry has `size` (the name `create_thread` takes), `diameter_mm`, `pitch_mm` (and `tpi` for inch), `pitch_class`, `basic_depth_mm` and `runout_mm` (`normal`, `short`). Inch sizes named in decimals (`0.2500-20`) also give their fractional name as `also` (`1/4-20`). + +**Prerequisite:** SolidWorks running. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `standard` | `str` | — | `"metric"` | 'metric' (ISO, e.g. M6x1.0) or 'inch' (UTS) | + +**Sample call:** + +```json +{"standard": "metric"} +``` + +--- + +### `create_thread` + +Cut a modelled thread, external (a bolt) or internal (a tapped hole), at a standard size. + +Pick the circular edge where the thread starts with `edge_point`: a rod's end, or a hole's opening. An external thread wants a rod of the nominal diameter (M6: 6 mm), an internal one a hole of about the tap drill (nominal minus one pitch, M6: 5 mm); a diameter more than one pitch off is refused before anything is built. Inch sizes may be given as fractions (`1/4-20`). A thread that cuts nothing is undone. + +**Prerequisite:** Active part with the rod or hole. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `kind` | `str` | — | `"external"` | 'external' (a bolt or rod, male) or 'internal' (a tapped hole, female) | +| `standard` | `str` | — | `"metric"` | 'metric' or 'inch' | +| `size` | `str` | ✅ | | A size as list_thread_sizes names it, e.g. 'M6x1.0'; inch also takes '1/4-20' | +| `edge_point` | `list[float]` | ✅ | | [x, y, z] in mm on the circular edge where the thread starts: a rod's end edge, or a hole's edge at its opening | +| `length` | `float` | ✅ | | Length of full thread in mm | +| `hand` | `str` | — | `"right"` | 'right' (the usual) or 'left' hand | +| `runout` | `str` | — | `"none"` | How the thread ends: 'none' (square), 'fade', 'undercut_a' or 'undercut_b' (see below) | +| `lead_in` | `bool` | — | `false` | Chamfer the thread's start 45° to just under the minor diameter, so the part starts in a nut (external threads; see below) | + +**Sample call:** + +```json +{"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12} +``` + +**The runout.** SolidWorks's Thread feature stops square. `runout` ends the thread the way a machined one does: + +| `runout` | What it models | Dimensions | For | +|---|---|---|---| +| `none` | The square end (the default) | | any thread | +| `fade` | The groove runs out of the material. External: its end face is swept as a cut straight along the helix's tangent, out past the rod, and the round rod makes the groove shallower until it ends in a point. Internal: swept along an arc tangent to the helix, turning towards the axis | External: where the groove's root leaves the rod, sqrt(r² − (r − h)²) (M6: 1.72 mm). Internal: DIN 76-1's normal runout x1 (2.5 mm for P 1), the arc rising 1.1 × the basic depth | any thread, external or internal, metric or inch | +| `undercut_a` | A DIN 76-1 Form A thread undercut, revolved at the thread's end | dg, g2 and r from DIN 76-1:2025-10 Table 1 (M6: dg 4.4, g2 3.5, r 0.5); a 30° flank on the thread side | external metric threads | +| `undercut_b` | The short Form B undercut (DIN 76-1 recommends it only where a short undercut is needed, as it needs special tools) | M6: dg 4.4, g2 2.5, r 0.5 | external metric threads | + +With an undercut, `length` reaches the shoulder: the undercut's square side is there and it reaches g2 back along the thread, so the full thread is `length` − g2 (`full_thread_mm`). It is sketched on the Front, Top or Right Plane, whichever holds the thread's axis. The reply's `runout` gives the dimensions, the sketch and cut it made and the volume it removed; if SolidWorks builds no runout, the thread is removed too. + +```json +{"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 25, "runout": "undercut_a"} +``` + +**The start.** Every thread starts two pitches outside the part, the way a +die or tap starts in the air, so the groove runs out through the end face +(or the hole's opening) rather than starting in a flat-ended pocket there. +`length` is still measured from the edge. + +**The lead-in.** The runout ends the thread at the shoulder, where the die +stops. The other end, the start, is where the part enters a nut: `lead_in` +chamfers it the way ISO 4753's chamfered end does, 45° down to just under +the minor diameter (d3 = d − 1.22687P from ISO 724, rounded down to 0.1 mm; +M6: 4.7 mm, 0.65 mm long). ISO 4753's table is not free, so the reply's +`lead_in.basis` calls this a reasoned default. It is a revolved cut on the +Front, Top or Right Plane, whichever holds the axis, made last; external +threads only (a tapped hole's lead-in is a countersink). The reply's +`lead_in` gives the end diameter, the length, the features and the volume +removed; if SolidWorks builds no lead-in, the thread and its runout are +removed too. + +```json +{"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 25, "runout": "undercut_a", "lead_in": true} +``` diff --git a/docs/user-guide/tools-overview.md b/docs/user-guide/tools-overview.md index 0ab80cac..43eac135 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -71,6 +71,14 @@ These read SolidWorks' installed files and never start it [**6 tools available** :octicons-arrow-right-24:](tool-catalog/bodies.md) +- :material-screw-machine-flat-top:{ .lg .middle } **Thread Tools** + + --- + + Modelled threads at standard sizes: external or internal, coarse or fine, with depth and runout. + + [**2 tools available** :octicons-arrow-right-24:](tool-catalog/threads.md) + - :material-palette:{ .lg .middle } **Appearance Tools** --- @@ -217,7 +225,7 @@ These read SolidWorks' installed files and never start it -**Total: 171 Tools** +**Total: 173 Tools** ## Deprecated tools diff --git a/mkdocs.yml b/mkdocs.yml index 8ffffcb8..6fcb9fe7 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -51,6 +51,7 @@ nav: - Modeling: user-guide/tool-catalog/modeling.md - Equations: user-guide/tool-catalog/equations.md - Bodies: user-guide/tool-catalog/bodies.md + - Threads: user-guide/tool-catalog/threads.md - Appearance: user-guide/tool-catalog/appearance.md - Reference Extras: user-guide/tool-catalog/reference-extras.md - Assembly: user-guide/tool-catalog/assembly.md diff --git a/openspec/changes/modelled-threads/.openspec.yaml b/openspec/changes/modelled-threads/.openspec.yaml new file mode 100644 index 00000000..d24126c0 --- /dev/null +++ b/openspec/changes/modelled-threads/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-28 diff --git a/openspec/changes/modelled-threads/design.md b/openspec/changes/modelled-threads/design.md new file mode 100644 index 00000000..6878e1c5 --- /dev/null +++ b/openspec/changes/modelled-threads/design.md @@ -0,0 +1,167 @@ +## Context + +Motivation: see proposal.md. Research and the user's decisions: +`openspec/research/modelled-threads.md` (decisions 1-7). + +**Probe (SolidWorks 2026 SP4, 2026-11-28; scratch parts, closed unsaved):** + +- The profiles are `.SLDLFP` files in the folder + `GetUserPreferenceStringValue(swFileLocationsThreadProfiles = 107)` names + (`C:\ProgramData\SOLIDWORKS\SOLIDWORKS 2026\Thread Profiles`): Metric Die, + Metric Tap (69 sizes each, `M1.2x0.25` ... ), Inch Die, Inch Tap (63, + `#0-80` ... ), SP4xx Bottle. Each size is a configuration, read without + opening the file by `ISldWorks.GetConfigurationNames(path)`. +- `IFeatureManager.CreateDefinition(swFmSweepThread = 87)` gives an + `IThreadFeatureData`; `InitializeThreadData()`; set `Edge` (the circular + edge picked with `SelectByID2(..., "EDGE", ...)` and read with + `GetSelectedObject6`), `Type` (the profile's name, e.g. "Metric Die"; + SolidWorks resolves the file), `Size` (a configuration name), + `ThreadMethod` 0 (cut), `EndCondition` 0 (blind), `BlindDepth` (m); + `CreateFeature(data)` gives "Thread1" (type `SweepThread`). +- A die M10x1.5 on a Ø10 rod, 20 mm: 2,356.2 -> 2,088.2 mm³. A tap M10x1.5 + in a Ø8.5 hole, 15 mm: 16,865.1 -> 16,712.5 mm³ (SolidWorks set the + diameter to 8.5 mm itself). Both pictures show the thread. +- The Hole Wizard library has no M1 or M1.4 coarse rows; the profiles have + `M1.2x0.25` and `M1.4x0.3` but no M1. Sizes come from the profiles: they + are what the feature accepts. + +## Goals / Non-Goals + +**Goals:** standard sizes read from SolidWorks; external and internal +threads; depth and runout reported by the agreed rules; checked before and +measured after. + +**Non-Goals:** +- DIN 76-1 Forms C and D (internal undercuts) and the short and long + runouts x2 and x3 as geometry; the fade uses x1. +- Extruded (added) threads, multiple starts, offsets, the Bottle profile. +- Other standards (DIN, JIS ...) and pipe threads. +- Threads in assemblies. + +## Decisions + +1. **Sizes from the profiles, not the Hole Wizard.** The profiles' sizes + are what the Thread feature accepts; listing anything else would offer + sizes that fail. +2. **Coarse or fine from the list itself.** At one diameter, the coarsest + pitch listed is `coarse`, the others `fine`, a lone one `only`. This is + true to the list without a separate table (`#0-80` is UNF only and is + reported `only`, not coarse). +3. **Diameters.** Metric: the number after M. Inch: a number size `#N` is + 0.060 + 0.013 N in (ASME B1.1 numbered sizes); a fraction is itself; + both in mm. +4. **Depth.** ISO 68-1 basic depth of engagement H1 = 5/8 H, H = √3/2 P, + so 0.541266 P. The same 60° profile serves inch threads. +5. **Runout.** ISO 3508: normal 2.5P (default), short 1.25P, rounded to + 0.01 mm. Inch: the same rule on P = 25.4/TPI, with `runout_basis` saying + it is a reasoned default (decision 6). +6. **Diameter check.** External: the edge's diameter within one pitch of + the nominal. Internal: within one pitch of nominal − P (about the tap + drill). Outside, refused before building, naming both diameters. +7. **Measured.** Through `_measured(direction=-1)`: no change or added + material deletes the feature and fails. + +## The runout, modelled (added after the user's review, 2026-11-28) + +The user asked for the runout as geometry, packaged as steps, after two +videos (a Thread feature's end swept out along a tangent arc; a swept thread +ended with a boundary to a point) and DIN 76-1 for the dimensions. + +**Probe (SolidWorks 2026 SP4, 2026-11-28; an M6x1.0 thread 12 mm on a 6 mm +rod):** the Thread feature has five faces; two are planar, one at each end +of the groove (0.304 mm², normal along the helix's tangent, out of the +material into the groove). A 3D sketch arc from the end face's centre, +tangent to the helix and rising out of the material, swept as a cut with +the end face as the profile (mark 1) and the sketch as the path (mark 4, +`InsertCutSwept5`) removed 0.26 mm³ and left the groove tapering to +nothing. A DIN 76-1 Form A profile (dg 4.4, g2 3.5, r 0.5, 30° flank) +sketched on the Front Plane and revolved as a cut (`FeatureRevolve2`, +IsCut) about a centreline on the axis removed 19.8 mm³. + +8. **Two runouts.** `fade` is the videos' method: it works on any thread + the Thread feature makes (external, internal, metric, inch). + `undercut_a` / `undercut_b` are DIN 76-1's external undercuts, so + external metric only. +9. **Dimensions from DIN 76-1:2025-10 Table 1.** The table is copied as + published (zencnc.com's transcription, checked against the rounding + note), not computed from the factors (g2 ≈ 3.5P / 2.5P, r ≈ 0.5P, + x1 ≈ 2.5P), which differ by rounding. +10. **The fade's arc.** Its length is x1; it rises 1.1 times the basic depth + so the cut leaves the material, so the radius is (x1² + h²) / 2h and + the arc turns asin(x1 / R). It starts at the end face's centre, + tangent to the helix (the face's inward normal tipped by the lead + angle), and rises away from the axis for an external thread, towards + it for an internal one. +11. **Where the undercut goes.** Its shoulder side is at the thread's end + (`length` from the start edge) and it reaches g2 back along the thread, + so the Thread feature's square end lies inside the groove; the full + thread is `length` − g2. `length` is therefore the distance to the + shoulder. +12. **The undercut's plane.** It is sketched on the Front, Top or Right + Plane, whichever holds the thread's axis; otherwise it is refused (a + plane through any axis is a later step). + +## The lead-in (added after the user's demo review, 2026-11-29) + +The user saw the runout at the collar and asked how the bolt would start +in a nut. The runout belongs at the shoulder (DIN 76-1); what starts a bolt +is the chamfered end of ISO 4753. Asked, the user chose a lead-in option +on `create_thread`. + +13. **The chamfer's size.** ISO 4753's table is paywalled; the usual reading + of its chamfered end is 45° to a diameter just under the minor + diameter. The end diameter is d3 = d − 1.22687P (ISO 724) rounded down + to 0.1 mm (M6: 4.7 mm, so 0.65 mm long); the reply calls it a reasoned + default on ISO 4753's form. +14. **How it is made.** A triangle on the main plane holding the axis, + revolved as a cut about the axis, like the undercut: robust where the + thread's groove has broken the end edge, which a Chamfer feature would + need whole. It runs 0.5 mm past the end face and the major diameter so + no skin is left. It is made last, after the runout (edge treatments go + last). +15. **External only.** An internal thread's lead-in is a countersink, which + `create_hole` already makes; `lead_in` on an internal thread is + refused. + +## The thread's start (added after the user's demo review, 2026-11-30) + +The user's screenshot showed the thread's groove starting at the end face +in a flat-ended pocket, a "box" no real bolt has. The user's reference +part (a countersunk M6x30 bolt) starts its Thread feature 2 mm outside the +bolt (`Offset` on, 2 mm, reversed), so the groove runs out through the end +face, then chamfers the tip 0.5 mm x 45° last. + +16. **Start two pitches outside.** Every thread is offset 2P out past its + edge (`Offset`, `OffsetDistance` 2P, `ReverseOffset`), the die or tap + starting in the air. Probed on SolidWorks 2026 (M6, 12 mm from y 25): + no offset ends the full thread at y 13; reversed offset with + `MaintainThreadLength` off ends it at y 15 (the 2 mm comes off the + threaded length); with it on, at y 13. So `MaintainThreadLength` is on + and `length` keeps its meaning, from the edge: the runout, undercut, + turns and lead-in are unchanged. `_end_face` already picks the far end + cap, which the offset leaves alone. + +## The fade, as the user's video makes it (added 2026-11-30) + +The user asked that `fade` be exactly the method of a video ("How to make +the end and start of this thread in Solidworks", Dr. Faust). Read frame by +frame: a Ø40 rod, chamfered 5 x 45° at its tip; a Thread feature M39x4 from +the chamfered edge, offset out past it, blind 50 mm; a 3D sketch of one +line from the thread's end face's outer corner, made tangent to the +thread's helical edge; a sketch on the end face converting its profile; +a Cut-Extrude of that profile with the line as its direction, blind +100 mm. The straight cut leaves the round rod, so the groove tapers to a +point. + +17. **The tangent fade.** On an external thread `fade` sweeps the end face + as a cut along a straight 3D-sketch line from the face's middle, along + the helix's tangent there (the direction the arc of decision 10 + started in), as long as the rod's diameter. Sweeping a planar profile + along a straight line is the video's extrusion along that line, and + reuses the swept cut probed for decision 10. The groove runs out where + the line's deepest point leaves the rod: sqrt(r² − (r − h)²), r the + edge's radius and h the basic depth (M6: 1.72 mm); the reply gives it + as `length_mm`, with `method` `tangent` and the path's length. +18. **Internal threads keep the arc.** In a hole a straight tangent runs + into the wall instead of leaving it, so an internal `fade` stays the + arc of decision 10, turning towards the axis over x1 (`method` `arc`). diff --git a/openspec/changes/modelled-threads/proposal.md b/openspec/changes/modelled-threads/proposal.md new file mode 100644 index 00000000..4b432b2d --- /dev/null +++ b/openspec/changes/modelled-threads/proposal.md @@ -0,0 +1,51 @@ +## Why + +The user's request (2026-11-26): modelled threads, external (male) and +internal (female), at the standard sizes with their coarse and fine pitches +and the right depths, read from tables rather than typed in, with a thread +runout. Today the server has only `add_cosmetic_thread`, a drawing +annotation with no geometry. M3 to M6 are the sizes most used. Queue item +43; research and the user's decisions: `openspec/research/modelled-threads.md`. + +## What Changes + +- **`list_thread_sizes`**: the sizes SolidWorks's own thread profiles hold + (the Die and Tap profiles in the Thread Profiles folder, read from the + installed SolidWorks), for `metric` or `inch`. Each size gives its + nominal diameter and pitch in mm (and threads per inch for inch), whether + its pitch is the coarse or a fine one for that diameter, the ISO 68-1 + basic thread depth, and the ISO 3508 runout (normal 2.5P, short 1.25P; + for inch the same rule on 1/TPI, labelled as a reasoned default). +- **`create_thread`**: a modelled thread with SolidWorks's Thread feature: + `kind` external (die) or internal (tap), `standard` metric or inch, + `size` (as `list_thread_sizes` names it), started at the circular edge + picked by `edge_point`, `length` mm long, right or left hand. The + cylinder's diameter is checked against the size before anything is + built. The thread is measured: a thread that removes no material is + undone and fails. The reply gives the thread's depth and runout. +- **`create_hole`**: its description points to `create_thread` and + `list_thread_sizes` for a modelled thread when fasteners are involved; it + still models none by default (the user's decision 4). +- Two new tools, beta until the live demo. + +## Capabilities + +### New Capabilities + +- `tools/threads`: `list_thread_sizes` and `create_thread`. + +### Modified Capabilities + +None (the `create_hole` change is a description only). + +## Impact + +- `adapters/thread_rules.py` (pure: size parsing, coarse or fine, depth, + runout, the diameter check); `adapters/solidworks/threads.py` (COM); + `adapters/mock_threads.py`; base, circuit breaker and connection pool + wrappers. +- `tools/threads.py`, registered; core toolset; support levels (beta); + hints; classifier rules. +- Docs: a tool-catalog page, counts, the skill's thread workflow. +- Tests mirroring src; a live test with an M6 bolt-like rod and an M6 + tapped hole, one refusal each. diff --git a/openspec/changes/modelled-threads/specs/tools/threads/spec.md b/openspec/changes/modelled-threads/specs/tools/threads/spec.md new file mode 100644 index 00000000..8ca0ee17 --- /dev/null +++ b/openspec/changes/modelled-threads/specs/tools/threads/spec.md @@ -0,0 +1,133 @@ +## ADDED Requirements + +### Requirement: The standard sizes SolidWorks holds +`list_thread_sizes` SHALL take `standard` (`metric` or `inch`) and list the +sizes of SolidWorks's own Die thread profile for it, read from the Thread +Profiles folder SolidWorks names. Each entry SHALL give `size` (the name +`create_thread` takes, e.g. `M6x1.0` or `1/4-20`), `diameter_mm`, +`pitch_mm` (and `tpi` for inch), `pitch_class` (`coarse` for the coarsest +pitch listed at that diameter when there are several, `fine` for the +others, `only` when there is one), `basic_depth_mm` (ISO 68-1: 5/8 of the +fundamental triangle, 0.541266 × P) and `runout_mm` with its normal (2.5P) +and short (1.25P) values (ISO 3508). The reply SHALL say where the runout +rule comes from (`runout_basis`): ISO 3508 for metric, the ISO 3508 rule on +the inch pitch (1/TPI) for inch. + +#### Scenario: Metric sizes +- **WHEN** it is called with `standard` `metric` +- **THEN** `M6x1.0` is listed with `pitch_mm` 1.0, `pitch_class` `coarse` + and `runout_mm` normal 2.5 and short 1.25, and `M10x1.25` with + `pitch_class` `fine` + +### Requirement: A modelled thread +`create_thread` SHALL take `kind` (`external` or `internal`), `standard`, +`size`, `edge_point` (`[x, y, z]` mm on the circular edge where the thread +starts), `length` (mm) and `hand` (`right`, the default, or `left`), and +SHALL make SolidWorks's Thread feature with the Die profile for an external +thread or the Tap profile for an internal one, cutting the thread. The +reply SHALL give the feature's `name`, the size, its pitch and depth, the +runout, and the volume before, after and removed. + +The thread SHALL start two pitches outside the part, the way a die or tap +starts in the air, so its groove runs out through the end face (or the +hole's opening) instead of starting in a flat-ended pocket there; `length` +SHALL still be the full thread's length measured from the edge. + +#### Scenario: An M6 external thread +- **WHEN** a 6 mm rod's top edge is picked and `create_thread` is called + with `kind` external, `size` `M6x1.0` and `length` 12 +- **THEN** a Thread feature is made, the part loses volume, and the reply + gives `pitch_mm` 1.0 and `runout_mm` 2.5 + +#### Scenario: The groove runs out through the end face +- **WHEN** an M6x1.0 thread is cut 12 mm from a rod's top edge +- **THEN** the Thread feature is offset 2 mm (two pitches) out past the + edge, with its length kept, so the full thread still ends 12 mm from + the end face + +### Requirement: Refused before anything is built +`create_thread` SHALL fail with `invalid_input`, changing nothing, when the +size isn't one the profile holds (the message names the nearest sizes), +the point is on no edge or on one that isn't circular, or the edge's +diameter doesn't suit the size: an external thread's cylinder within one +pitch of the nominal diameter, an internal thread's hole within one pitch +of the tap drill (nominal minus one pitch). + +#### Scenario: The wrong size for the rod +- **WHEN** `M10x1.5` is asked for on a 6 mm rod +- **THEN** it fails with `invalid_input`, saying the edge is 6 mm and the + size wants about 10 mm + +### Requirement: A thread that cuts nothing is undone +A Thread feature that leaves the volume unchanged, or adds material, SHALL +be deleted and the call SHALL fail with `feature_not_built`. + +#### Scenario: Nothing cut +- **WHEN** SolidWorks makes the feature but the volume is unchanged +- **THEN** the feature is deleted and the call fails + +### Requirement: The thread's runout, modelled +`create_thread` SHALL take `runout`: `none` (the default), `fade`, +`undercut_a` or `undercut_b`. With `fade` on an external thread the +Thread feature's end face SHALL be swept as a cut straight along the +helix's tangent at the thread's end, out past the rod: the line leaves the +round rod, so the groove gets shallower until it runs out, over +sqrt(r² − (r − h)²) for the rod's radius r and the basic depth h (M6: +1.72 mm). On an internal thread a straight line would run into the hole's +wall, so its end face SHALL be swept along an arc tangent to the helix +that turns towards the axis and leaves the material over DIN 76-1's +normal runout x1 (2.5P where the table has no row). With `undercut_a` or `undercut_b` an external +metric thread SHALL end in a DIN 76-1 Form A or Form B undercut: a revolved +groove at the thread's end, of diameter dg, width g2, a 30° flank on the +thread side and the radius r at the shoulder, from DIN 76-1 Table 1 for the +pitch. The reply SHALL give `runout` with the style, its dimensions, the +feature it made and the volume it removed. An undercut on an internal or an +inch thread, a pitch the table has no row for, an undercut wider than the +thread, or an axis that no main plane holds SHALL fail with `invalid_input` +before anything is built. + +#### Scenario: A faded M6 thread +- **WHEN** `create_thread` cuts M6x1.0 12 mm on a 6 mm rod with `runout` + `fade` +- **THEN** the end face is swept straight along the helix's tangent, the + groove fades out over 1.72 mm, and the reply gives `method` `tangent`, + the fade's length and the volume it removed + +#### Scenario: A faded tapped hole +- **WHEN** `create_thread` cuts an internal M6x1.0 with `runout` `fade` +- **THEN** the end face is swept along an arc towards the axis over 2.5 mm + and the reply gives `method` `arc` + +#### Scenario: A DIN 76-1 Form A undercut +- **WHEN** `create_thread` cuts M6x1.0 12 mm with `runout` `undercut_a` +- **THEN** the thread ends in a groove of diameter 4.4 mm and width 3.5 mm + with r 0.5 mm, and the reply gives those dimensions + +#### Scenario: An undercut on a tapped hole +- **WHEN** `create_thread` is asked for an internal thread with `runout` + `undercut_a` +- **THEN** it fails with `invalid_input` and nothing is built + +### Requirement: A lead-in at the thread's start +`create_thread` SHALL take `lead_in` (default false). With it, an external +thread's start SHALL be chamfered the way ISO 4753's chamfered end is: 45° +from the end face down to an end diameter just under the minor diameter +(d3 = d − 1.22687P, ISO 724, rounded down to 0.1 mm), revolved as a cut +after the thread and its runout, so the chamfer is the last feature. The +reply SHALL give `lead_in` with the basis, the end diameter, the chamfer's +length, the features it made and the volume it removed. The runout stays +at the other end, at the shoulder. A lead-in on an internal thread, or on +an axis no main plane holds, SHALL fail with `invalid_input` before +anything is built; if SolidWorks builds no lead-in, the thread and its +runout SHALL be removed too. + +#### Scenario: An M6 bolt that starts in a nut +- **WHEN** `create_thread` cuts M6x1.0 to a collar with `runout` + `undercut_a` and `lead_in` true +- **THEN** the free end is chamfered 45° to 4.7 mm (0.65 mm long) and the + undercut stays at the collar + +#### Scenario: A lead-in in a tapped hole +- **WHEN** `create_thread` is asked for an internal thread with `lead_in` +- **THEN** it fails with `invalid_input` and nothing is built + diff --git a/openspec/changes/modelled-threads/tasks.md b/openspec/changes/modelled-threads/tasks.md new file mode 100644 index 00000000..f1463bd5 --- /dev/null +++ b/openspec/changes/modelled-threads/tasks.md @@ -0,0 +1,74 @@ +## 1. Probe + +- [x] 1.1 Probe the Thread feature (die and tap, M10x1.5), the profile + folder and the profiles' sizes on SolidWorks 2026 (answers in + design.md) + +## 2. Adapter + +- [x] 2.1 `adapters/thread_rules.py`: size parsing (metric, inch), coarse or + fine, depth, runout, the diameter check +- [x] 2.2 `base.py` parameter models and methods; wrappers in + `circuit_breaker.py` and `connection_pool.py` +- [x] 2.3 `adapters/solidworks/threads.py`: list the profiles' sizes; make + the thread, measured +- [x] 2.4 `adapters/mock_threads.py` + +## 3. Tools + +- [x] 3.1 `tools/threads.py`: `list_thread_sizes`, `create_thread` +- [x] 3.2 Register; toolset family; support levels (beta); hints; + classifier rules; `create_hole`'s description points to them + +## 4. Tests + +- [x] 4.1 Unit tests mirroring src, 100% coverage +- [x] 4.2 Live test `tests/live/test_live_sw_threads.py`: an M6 rod + threaded 12 mm, an M6 tapped hole; one refusal each; look at the + images (passed 2026-11-28: M6 63.8 mm³ over 12 turns, 1/4-20 + 89.3 mm³, the internal M6 40.3 mm³ in a 5.0 mm hole) + +## 5. Docs + +- [x] 5.1 Tool-catalog page, counts, skill workflow, CHANGELOG, queue +- [x] 5.2 A demo section and GIF once the user has seen it + +## 6. The runout, modelled (after the user's review) + +- [x] 6.1 Probe the fade and a DIN 76-1 undercut on SolidWorks 2026 + (design.md) +- [x] 6.2 `adapters/runout_rules.py`: DIN 76-1 Table 1, the fade's arc, the + undercut's profile; input checks +- [x] 6.3 `adapters/solidworks/thread_runout.py`; `create_thread` takes + `runout`; the mock +- [x] 6.4 Unit tests, 100% coverage; live test: fade and Form A on M6, an + internal undercut refused; look at the images +- [x] 6.5 Catalog page, skill workflow, CHANGELOG + +## 7. The lead-in (after the user's demo review) + +- [x] 7.1 `runout_rules`: the lead-in's size and outline; refuse it on an + internal thread +- [x] 7.2 `thread_runout`: the revolved cut shared with the undercut; + `create_thread` takes `lead_in`, made last; the mock; the tool field +- [x] 7.3 Unit tests, 100% coverage; live: the M6 rod and the undercut rod + with a lead-in, the thread's ends seen side on (Left view) +- [x] 7.4 Catalog page, skill workflow, CHANGELOG + +## 8. The thread's start (after the user's demo review) + +- [x] 8.1 Probe the Thread feature's offset on SolidWorks 2026 (design.md 16) +- [x] 8.2 `create_thread` starts every thread 2P outside, its length kept; + unit tests +- [x] 8.3 Catalog page, CHANGELOG +- [x] 8.4 Live: the rods' free ends, side on, show the groove running out + through the chamfer + +## 9. The fade, as the user's video makes it + +- [x] 9.1 Read the video frame by frame (design.md 17, 18) +- [x] 9.2 `runout_rules.fade_tangent`; an external fade swept along the + helix's tangent, an internal one along the arc; the mock; unit tests +- [x] 9.3 Catalog page, skill workflow, tool description, CHANGELOG +- [x] 9.4 Live: the faded M6 seen side on, the groove tapering to a point + diff --git a/openspec/queue.md b/openspec/queue.md index 75a33984..440155c4 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -53,7 +53,7 @@ Last updated 2026-11-25. | 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 | -| 43 | Modelled threads (the user's request 2026-11-26): external (male) and internal (female) threads through SolidWorks' Thread feature (`IThreadFeatureData`, the installed die and tap profiles), at standard sizes with coarse and fine pitches read from the installed Hole Wizard tables (`

_DATA_HW_TappedHole`), the thread depth reported from the ISO 68-1 profile, and a thread runout (DIN 76 / ISO 4755). Research notes: `openspec/research/modelled-threads.md` | none | not yet written | Researched 2026-11-26; spec next (four open questions) | +| 43 | Modelled threads (the user's request 2026-11-26): external (male) and internal (female) threads through SolidWorks' Thread feature (`IThreadFeatureData`, the installed die and tap profiles), at standard sizes with coarse and fine pitches read from the installed Hole Wizard tables (`

_DATA_HW_TappedHole`), the thread depth reported from the ISO 68-1 profile, and a thread runout (DIN 76 / ISO 4755). Research notes: `openspec/research/modelled-threads.md` | none | `modelled-threads` | Built 2026-11-28: `list_thread_sizes`, `create_thread` (die and tap profiles, coarse or fine, ISO 68-1 depth, ISO 3508 runout reported); live tests pass; beta until the user's demo. Runout as geometry and M1/M1.4 are open questions | ## Removed tools (item 10, release 2.1.0) diff --git a/openspec/research/modelled-threads.md b/openspec/research/modelled-threads.md index 759780ce..a31d7d87 100644 --- a/openspec/research/modelled-threads.md +++ b/openspec/research/modelled-threads.md @@ -211,3 +211,29 @@ overrides it. This needs the user's decision. `list_thread_sizes(standard)` reading the tables above. 4. Whether `create_hole` with a tapped hole should be able to model the thread as well, not only show a cosmetic one. + +## 8. The runout as geometry (the user, 2026-11-28) + +The user asked for the runout modelled, packaged as steps, after two +videos and DIN 76-1: + +- *Thread termination* (youtube.com/watch?v=SoXCvN25WVo): a helix-swept + thread, its start rounded by a partial revolve and its end lofted + (Boundary) to a point on the rod: a vanishing thread. +- *Thread finishing* (youtube.com/watch?v=9AL_n3N9a9Y): SolidWorks's Thread + feature, then its end face swept along a 3D-sketch arc tangent to the + thread (radius 3.5 mm for M10x1) into the core; for a tapped hole a + swept cut the other way. +- DIN 76-1:2025-10 Table 1 (external threads), read from zencnc.com's + transcription (zencnc.com/fachwissen/gewindefreistich/), checked against + dswerk.de's notes: per pitch, dg = d − (0.3 ... 8.3), g1 min and g2 max + for Form A (normal) and Form B (short, special tools), r, and the + runouts x1 (normal), x2 (short), x3 (long, rolled). Factors ≈ g2 3.5P / + 2.5P, r 0.5P, x1 2.5P, but the table differs by rounding (P 1.5: r 0.8, + g2 A 5.3), so the table is used. The flank on the thread side is at + least 30°. The 2016-08 edition differs in a few rows (M10 A g2 5.2, + M6 r 0.6). + +Built (design.md decisions 8 to 12): `runout` on `create_thread`, `fade` +after the second video, sized by x1, and `undercut_a` / `undercut_b` from +the table. diff --git a/src/solidworks_mcp/adapters/base.py b/src/solidworks_mcp/adapters/base.py index f7628ea4..ee45da30 100644 --- a/src/solidworks_mcp/adapters/base.py +++ b/src/solidworks_mcp/adapters/base.py @@ -455,6 +455,32 @@ class SectionPropertiesParameters(BaseModel): face_point: list[float] +class ThreadParameters(BaseModel): + """A modelled thread with SolidWorks's Thread feature. + + Attributes: + kind (str): ``external`` (die) or ``internal`` (tap). + standard (str): ``metric`` or ``inch``. + size (str): A profile size, e.g. ``M6x1.0`` or ``1/4-20``. + edge_point (list[float]): ``[x, y, z]`` mm on the circular edge where + the thread starts. + length (float): The thread's length, mm; with an undercut, to the + shoulder. + hand (str): ``right`` or ``left``. + runout (str): ``none``, ``fade``, ``undercut_a`` or ``undercut_b``. + lead_in (bool): Chamfer the thread's start 45° (ISO 4753), last. + """ + + kind: str = "external" + standard: str = "metric" + size: str + edge_point: list[float] + length: float + hand: str = "right" + runout: str = "none" + lead_in: bool = False + + class LoftParameters(BaseModel): """Parameters for loft operations. @@ -984,6 +1010,36 @@ async def scale_body( error="scale_body is not implemented by this adapter", ) + async def list_thread_sizes(self, standard: str) -> AdapterResult[dict[str, Any]]: + """The sizes SolidWorks's thread profiles hold for a standard. + + Args: + standard: ``metric`` or ``inch``. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="list_thread_sizes is not implemented by this adapter", + ) + + async def create_thread( + self, params: ThreadParameters + ) -> AdapterResult[dict[str, Any]]: + """A modelled thread, external or internal, measured. + + Args: + params: The kind, standard, size, edge, length and hand. + + Returns: + AdapterResult[dict[str, Any]]: Error unless the adapter implements it. + """ + return AdapterResult( + status=AdapterResultStatus.ERROR, + error="create_thread is not implemented by this adapter", + ) + async def set_appearance( self, params: AppearanceParameters ) -> AdapterResult[dict[str, Any]]: diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index 8d3a0e41..1bfd7cd4 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -36,6 +36,7 @@ SolidWorksModel, SplitBodyParameters, SweepParameters, + ThreadParameters, ) T = TypeVar("T") @@ -1358,6 +1359,24 @@ async def scale_body( input_dict=_to_input_dict(params), ) + async def list_thread_sizes(self, standard: str) -> AdapterResult[dict[str, Any]]: + """The thread profiles' sizes. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "list_thread_sizes", + lambda: self.adapter.list_thread_sizes(standard), + input_dict={"standard": standard}, + ) + + async def create_thread( + self, params: ThreadParameters + ) -> AdapterResult[dict[str, Any]]: + """A modelled thread. Through the circuit breaker.""" + return await self._execute_with_circuit_breaker( + "create_thread", + lambda: self.adapter.create_thread(params), + input_dict=_to_input_dict(params), + ) + async def set_appearance( self, params: AppearanceParameters ) -> AdapterResult[dict[str, Any]]: diff --git a/src/solidworks_mcp/adapters/connection_pool.py b/src/solidworks_mcp/adapters/connection_pool.py index 5a3143e7..fa686fb3 100644 --- a/src/solidworks_mcp/adapters/connection_pool.py +++ b/src/solidworks_mcp/adapters/connection_pool.py @@ -35,6 +35,7 @@ SolidWorksModel, SplitBodyParameters, SweepParameters, + ThreadParameters, ) T = TypeVar("T") @@ -1225,6 +1226,20 @@ async def get_section_properties( lambda adapter: adapter.get_section_properties(params), ) + async def list_thread_sizes(self, standard: str) -> AdapterResult[dict[str, Any]]: + """The thread profiles' sizes. Using the pool.""" + return await self._execute_with_pool( + "list_thread_sizes", lambda adapter: adapter.list_thread_sizes(standard) + ) + + async def create_thread( + self, params: ThreadParameters + ) -> AdapterResult[dict[str, Any]]: + """A modelled thread. Using the pool.""" + return await self._execute_with_pool( + "create_thread", lambda adapter: adapter.create_thread(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 d278aefd..cff53b7e 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -37,6 +37,7 @@ from .mock_sheet_metal import MockSheetMetalMixin from .mock_swept import MockSweptMixin from .mock_templates import MockTemplatesMixin +from .mock_threads import MockThreadsMixin from .solidworks.documentation import MATERIAL_PROPERTIES from .solidworks.drawing_standard import gtol_problem from .solidworks.features import _AXIS_PLANE_PAIRS @@ -147,6 +148,7 @@ def __bool__(self) -> bool: class MockSolidWorksAdapter( + MockThreadsMixin, MockAppearanceMixin, MockReferenceExtrasMixin, MockBodiesMixin, diff --git a/src/solidworks_mcp/adapters/mock_threads.py b/src/solidworks_mcp/adapters/mock_threads.py new file mode 100644 index 00000000..e2cfff7d --- /dev/null +++ b/src/solidworks_mcp/adapters/mock_threads.py @@ -0,0 +1,194 @@ +"""The mock adapter's modelled threads (queue item 43). + +The mock has no thread profiles; it serves a few sizes of each standard, as +SolidWorks 2026's Die profiles name them, and the coarse pitches its Hole +Wizard library gives. A thread needs an open part with a body; the edge's +diameter is taken to be the one the size wants (the mock has no edges), and +the volume removed is the thread's groove: the basic depth over half the +circumference, times the length. A runout is sized by :mod:`runout_rules` +and removes, roughly, a third of the groove over the fade's length, or the +undercut's ring. Refusals use :mod:`thread_rules` and :mod:`runout_rules`. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from typing import Any + +from ..exceptions import InputRefused +from . import runout_rules +from . import thread_rules as rules +from .base import AdapterResult, AdapterResultStatus, ThreadParameters +from .body_rules import BodyState + +#: Sizes the mock's profiles hold. +MOCK_SIZES: dict[str, list[str]] = { + "metric": [ + "M3x0.5", + "M4x0.7", + "M5x0.8", + "M6x1.0", + "M8x1.25", + "M8x1.0", + "M10x1.5", + "M10x1.25", + ], + "inch": ["#4-40", "#10-24", "#10-32", "0.2500-20", "0.2500-28"], +} +#: Coarse pitches by diameter, as the Hole Wizard's plain rows give them. +MOCK_COARSE = {3.0: 0.5, 4.0: 0.7, 5.0: 0.8, 6.0: 1.0, 8.0: 1.25, 10.0: 1.5} + + +def _error(message: str) -> AdapterResult[Any]: + """An error result.""" + return AdapterResult(status=AdapterResultStatus.ERROR, error=message) + + +class MockThreadsMixin: + """``list_thread_sizes`` and ``create_thread``, in memory.""" + + _current_model: Any + #: From :class:`MockBodiesMixin`: the active part's box bodies. + _bodies: Callable[[], list[BodyState]] + + async def list_thread_sizes(self, standard: str) -> AdapterResult[dict[str, Any]]: + """Mock: the sizes the mock's profiles hold. + + Args: + standard: ``metric`` or ``inch``. + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if standard not in rules.STANDARDS: + return _error(f"standard must be one of {', '.join(rules.STANDARDS)}.") + coarse = MOCK_COARSE if standard == "metric" else {} + sizes = rules.size_table(MOCK_SIZES[standard], coarse) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={ + "standard": standard, + "profile": rules.PROFILES[(standard, "external")], + "sizes": sizes, + "count": len(sizes), + "runout_basis": rules.RUNOUT_BASIS[standard], + }, + ) + + async def create_thread( + self, params: ThreadParameters + ) -> AdapterResult[dict[str, Any]]: + """Mock: a modelled thread, its groove's volume removed. + + Args: + params: The kind, standard, size, edge, length and hand. + + Returns: + AdapterResult[dict[str, Any]]: As the real adapter's. + """ + if not self._current_model: + return _error("No active model") + try: + rules.check_inputs(params) + runout_rules.check_runout(params) + size = rules.match_size(MOCK_SIZES[params.standard], params.size) + if not self._bodies(): + raise InputRefused( + f"No edge at {list(params.edge_point)} mm; the part has no body." + ) + runout = _mock_runout(params, size) + lead = _mock_lead_in(params, size) + except InputRefused as refused: + return _error(str(refused)) + diameter = rules.expected_diameter(size, params.kind) + entry = rules.size_entry(size, "") + depth = entry["basic_depth_mm"] + removed = math.pi * diameter * depth / 2 * params.length + removed -= runout["volume_change"] if runout else 0.0 + removed -= lead["volume_change"] if lead else 0.0 + before = sum(body.volume for body in self._bodies()) + return AdapterResult( + status=AdapterResultStatus.SUCCESS, + data={ + "runout": runout, + "lead_in": lead, + "name": "Thread1", + "kind": params.kind, + "standard": params.standard, + "profile": rules.PROFILES[(params.standard, params.kind)], + "size": size.size, + "pitch_mm": size.pitch_mm, + "basic_depth_mm": depth, + "runout_mm": entry["runout_mm"], + "runout_basis": rules.RUNOUT_BASIS[params.standard], + "length_mm": params.length, + "hand": params.hand, + "edge_diameter_mm": diameter, + "turns": round(params.length / size.pitch_mm, 2), + "volume_before": before, + "volume_after": before - removed, + "volume_change": -removed, + }, + ) + + +def _mock_lead_in( + params: ThreadParameters, size: rules.ThreadSize +) -> dict[str, Any] | None: + """The lead-in the mock reports, or None without one. + + Its volume is the revolved triangle's: 2 pi times its centroid's radius + times its area. + """ + if not params.lead_in: + return None + lead = runout_rules.lead_in(size.pitch_mm, size.diameter_mm) + side = lead.length_mm + centroid = size.diameter_mm / 2 - side / 3 + return { + **runout_rules.lead_in_reply(lead), + "plane": "Front", + "features": ["Sketch3", "Cut-Revolve2"], + "volume_change": -round(2 * math.pi * centroid * side * side / 2, 4), + } + + +def _mock_runout( + params: ThreadParameters, size: rules.ThreadSize +) -> dict[str, Any] | None: + """The runout the mock reports, or None for ``none``. + + Raises: + InputRefused: An undercut the table has no row for, or one wider than + the thread. + """ + if params.runout == "none": + return None + depth = rules.BASIC_DEPTH * size.pitch_mm + if params.runout == "fade": + shape: dict[str, Any] + if params.kind == "external": + shape = runout_rules.fade_tangent(size.pitch_mm, size.diameter_mm) + basis = runout_rules.TANGENT_BASIS + else: + shape = {"method": "arc", **runout_rules.fade_arc(size.pitch_mm)} + basis = f"{runout_rules.BASIS} (x1)" + groove = depth * size.pitch_mm / 2 + return { + "style": "fade", + "basis": basis, + **shape, + "features": ["3DSketch1", "Cut-Sweep1"], + "volume_change": -round(groove * float(shape["length_mm"]) / 3, 4), + } + cut = runout_rules.undercut(size.pitch_mm, size.diameter_mm, params.runout) + runout_rules.check_width(cut, params.length) + ring = math.pi * ((size.diameter_mm / 2) ** 2 - (cut.diameter_mm / 2) ** 2) + return { + **runout_rules.undercut_reply(cut), + "plane": "Front", + "full_thread_mm": round(params.length - cut.width_mm, 4), + "features": ["Sketch2", "Cut-Revolve1"], + "volume_change": -round(ring * cut.bottom_mm, 4), + } diff --git a/src/solidworks_mcp/adapters/pywin32_adapter.py b/src/solidworks_mcp/adapters/pywin32_adapter.py index 55067365..21dfc656 100644 --- a/src/solidworks_mcp/adapters/pywin32_adapter.py +++ b/src/solidworks_mcp/adapters/pywin32_adapter.py @@ -42,6 +42,7 @@ SolidWorksSketchMixin, SolidWorksSweptMixin, SolidWorksTemplatesMixin, + SolidWorksThreadsMixin, bitmap, default_entities, ) @@ -1726,6 +1727,7 @@ def _is_feature_suppressed(self, feature: Any) -> bool: class PyWin32Adapter( + SolidWorksThreadsMixin, SolidWorksAppearanceMixin, SolidWorksReferenceExtrasMixin, SolidWorksAssemblyMixin, diff --git a/src/solidworks_mcp/adapters/runout_rules.py b/src/solidworks_mcp/adapters/runout_rules.py new file mode 100644 index 00000000..b0743e7b --- /dev/null +++ b/src/solidworks_mcp/adapters/runout_rules.py @@ -0,0 +1,368 @@ +"""The rules for a modelled thread runout, shared by the adapter and the mock. + +Two runouts end a thread the way a machined part does, instead of the +Thread feature's square end: + +- ``fade``: the groove runs out over DIN 76-1's normal runout x1, its end + face swept along an arc tangent to the helix that leaves the material; +- ``undercut_a`` / ``undercut_b``: DIN 76-1's external thread undercut, + Form A (normal) or Form B (short), a revolved groove at the thread's end. + +The other end, where the thread starts, can take a lead-in: ISO 4753's +chamfered end, 45° to just under the minor diameter, so the part starts in +a nut. + +Pure functions: + +- :func:`check_runout` refuses a style that can't be built, before anything + is; +- :func:`fade_arc` gives the fade's length, rise, radius and turn; +- :func:`undercut` gives a Form A or B undercut's dimensions for a pitch; +- :func:`undercut_profile` gives its outline in the axial half-plane; +- :func:`lead_in` and :func:`lead_in_profile` give the lead-in's size and + outline. + +Source: DIN 76-1:2025-10 Table 1 (external threads), as transcribed by +zencnc.com (research note ``openspec/research/modelled-threads.md``). The +table's values are used, not the factors (g2 ≈ 3.5P / 2.5P, r ≈ 0.5P, +x1 ≈ 2.5P), which differ from it by rounding. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from ..exceptions import InputRefused +from .base import ThreadParameters +from .thread_rules import BASIC_DEPTH + +#: The runout styles ``create_thread`` takes. +STYLES = ("none", "fade", "undercut_a", "undercut_b") +#: DIN 76-1 Table 1, external threads: +#: pitch -> (d - dg, g1 min A, g1 min B, g2 max A, g2 max B, r, x1). +DIN_76_1: dict[float, tuple[float, float, float, float, float, float, float]] = { + 0.2: (0.3, 0.45, 0.25, 0.7, 0.5, 0.1, 0.5), + 0.25: (0.4, 0.55, 0.25, 0.9, 0.6, 0.1, 0.6), + 0.3: (0.5, 0.6, 0.3, 1.1, 0.8, 0.2, 0.8), + 0.35: (0.6, 0.7, 0.4, 1.2, 0.9, 0.2, 0.9), + 0.4: (0.7, 0.8, 0.5, 1.4, 1.0, 0.2, 1.0), + 0.45: (0.7, 1.0, 0.5, 1.6, 1.1, 0.2, 1.1), + 0.5: (0.8, 1.1, 0.5, 1.8, 1.3, 0.3, 1.3), + 0.6: (1.0, 1.2, 0.6, 2.1, 1.5, 0.3, 1.5), + 0.7: (1.1, 1.5, 0.8, 2.5, 1.8, 0.4, 1.8), + 0.75: (1.2, 1.6, 0.9, 2.6, 1.9, 0.4, 1.9), + 0.8: (1.3, 1.7, 0.9, 2.8, 2.0, 0.4, 2.0), + 1.0: (1.6, 2.1, 1.1, 3.5, 2.5, 0.5, 2.5), + 1.25: (2.0, 2.7, 1.5, 4.4, 3.1, 0.6, 3.1), + 1.5: (2.3, 3.2, 1.8, 5.3, 3.8, 0.8, 3.8), + 1.75: (2.6, 3.9, 2.1, 6.1, 4.4, 0.9, 4.4), + 2.0: (3.0, 4.5, 2.5, 7.0, 5.0, 1.0, 5.0), + 2.5: (3.6, 5.6, 3.2, 8.8, 6.3, 1.3, 6.3), + 3.0: (4.4, 6.7, 3.7, 10.5, 7.5, 1.5, 7.5), + 3.5: (5.0, 7.7, 4.7, 12.3, 9.0, 1.8, 8.8), + 4.0: (5.7, 9.0, 5.0, 14.0, 10.0, 2.0, 10.0), + 4.5: (6.4, 10.5, 5.5, 15.8, 11.3, 2.3, 11.3), + 5.0: (7.0, 11.5, 6.5, 17.5, 12.5, 2.5, 12.5), + 5.5: (7.7, 12.5, 7.5, 19.3, 13.8, 2.8, 13.8), + 6.0: (8.3, 14.0, 8.0, 21.0, 15.0, 3.0, 15.0), +} +#: Where the dimensions come from. +BASIS = "DIN 76-1:2025-10 Table 1" +#: The undercut's flank on the thread side, to the axis. +FLANK_DEG = 30.0 +#: Where an external thread's fade comes from (design.md 17). +TANGENT_BASIS = ( + "the thread's end face swept straight along the helix's tangent, out " + "past the rod, so the groove runs out of the round rod by itself" +) +#: How far the fade rises, over the basic depth, so the cut leaves the material. +FADE_RISE = 1.1 +#: How far the undercut's outline reaches past the major diameter, mm. +OVERSHOOT_MM = 0.5 +#: ISO 724: an external thread's minor diameter is d3 = d - 1.22687P. +MINOR_FACTOR = 1.22687 +#: The lead-in's chamfer angle, to the axis. +LEAD_IN_DEG = 45.0 +#: Where the lead-in comes from. +LEAD_IN_BASIS = ( + "ISO 4753 chamfered end: 45° to just under the minor diameter (d3 = d - " + "1.22687P, ISO 724, rounded down to 0.1 mm); a reasoned default, as the " + "standard's table is not free" +) + + +@dataclass(frozen=True) +class Undercut: + """A DIN 76-1 external thread undercut. + + Attributes: + form: ``A`` or ``B``. + diameter_mm: The groove's diameter dg. + width_mm: Its width g2 at the major diameter. + bottom_mm: Its flat bottom, g2 less the flank, at least g1. + g1_mm: The table's least bottom length g1. + radius_mm: The radius r at the shoulder. + depth_mm: (d - dg) / 2. + """ + + form: str + diameter_mm: float + width_mm: float + bottom_mm: float + g1_mm: float + radius_mm: float + depth_mm: float + + +@dataclass(frozen=True) +class LeadIn: + """A 45° lead-in chamfer at a thread's start. + + Attributes: + end_diameter_mm: The diameter at the end face, just under d3. + length_mm: The chamfer's length along the axis (and its depth). + """ + + end_diameter_mm: float + length_mm: float + + +def _row(pitch_mm: float) -> tuple[float, ...] | None: + """The table's row for a pitch, matched to 0.001 mm.""" + for pitch, row in DIN_76_1.items(): + if abs(pitch - pitch_mm) < 1e-3: + return row + return None + + +def fade_length(pitch_mm: float) -> float: + """DIN 76-1's normal runout x1 for a pitch; 2.5P where it has no row.""" + row = _row(pitch_mm) + return row[6] if row else round(2.5 * pitch_mm, 2) + + +def fade_tangent(pitch_mm: float, diameter_mm: float) -> dict[str, float | str]: + """An external thread's fade: straight along the helix's tangent. + + The groove's deepest point, at r - h from the axis, leaves the rod of + radius r after sqrt(r² - (r - h)²); the path runs the rod's diameter, + well past that. + + Args: + pitch_mm: The thread's pitch. + diameter_mm: The start edge's diameter. + + Returns: + dict: ``method`` (``tangent``), ``length_mm`` (where the groove runs + out) and ``path_mm``. + """ + radius = diameter_mm / 2 + depth = BASIC_DEPTH * pitch_mm + return { + "method": "tangent", + "length_mm": round(math.sqrt(radius**2 - (radius - depth) ** 2), 2), + "path_mm": diameter_mm, + } + + +def fade_arc(pitch_mm: float) -> dict[str, float]: + """The fade's arc: its length (x1), rise, radius and turn. + + The arc is tangent to the helix at the thread's end and rises + ``FADE_RISE`` times the basic depth over x1, so the cut leaves the + material: R = (x1² + h²) / 2h, turned asin(x1 / R). + + Args: + pitch_mm: The thread's pitch. + + Returns: + dict[str, float]: ``length_mm``, ``rise_mm``, ``radius_mm`` and + ``turn_deg``. + """ + length = fade_length(pitch_mm) + rise = FADE_RISE * BASIC_DEPTH * pitch_mm + radius = (length**2 + rise**2) / (2 * rise) + return { + "length_mm": length, + "rise_mm": round(rise, 4), + "radius_mm": round(radius, 4), + "turn_deg": round(math.degrees(math.asin(length / radius)), 3), + } + + +def undercut(pitch_mm: float, diameter_mm: float, style: str) -> Undercut: + """A Form A or B undercut's dimensions for a pitch and diameter. + + Args: + pitch_mm: The thread's pitch. + diameter_mm: Its major (nominal) diameter. + style: ``undercut_a`` or ``undercut_b``. + + Returns: + Undercut: The groove's dimensions. + + Raises: + InputRefused: The table has no row for the pitch. + """ + row = _row(pitch_mm) + if row is None: + pitches = ", ".join(f"{p:g}" for p in DIN_76_1) + raise InputRefused( + f"{BASIS} has no undercut for a {pitch_mm:g} mm pitch; it covers " + f"{pitches} mm. Use runout 'fade' instead." + ) + offset, g1a, g1b, g2a, g2b, radius, _ = row + form = "A" if style == "undercut_a" else "B" + g1, g2 = (g1a, g2a) if form == "A" else (g1b, g2b) + depth = offset / 2 + flank = depth / math.tan(math.radians(FLANK_DEG)) + return Undercut( + form=form, + diameter_mm=round(diameter_mm - offset, 4), + width_mm=g2, + bottom_mm=round(max(g2 - flank, g1), 4), + g1_mm=g1, + radius_mm=radius, + depth_mm=depth, + ) + + +def undercut_profile( + cut: Undercut, diameter_mm: float +) -> tuple[list[tuple[float, float]], tuple[float, float]]: + """The undercut's closed outline in the axial half-plane. + + Each point is ``(radius, along)`` in mm: ``along`` is measured from the + shoulder side (the thread's end) back towards the thread's start. The + flank runs out past the major diameter by ``OVERSHOOT_MM`` so the cut + leaves no skin. + + Args: + cut: The undercut. + diameter_mm: The thread's major diameter. + + Returns: + tuple: The six corner points in order (the arc runs from the second + to the third) and the arc's centre. + """ + outer = diameter_mm / 2 + bottom = cut.diameter_mm / 2 + r = cut.radius_mm + slope = math.tan(math.radians(FLANK_DEG)) + flank_start = cut.width_mm - cut.depth_mm / slope + # The shoulder side stops at the major diameter: past it the outline + # would lie on a collar's face and split it. + points = [ + (outer, 0.0), + (bottom + r, 0.0), + (bottom, r), + (bottom, flank_start), + (outer, cut.width_mm), + (outer + OVERSHOOT_MM, cut.width_mm + OVERSHOOT_MM / slope), + ] + return points, (bottom + r, r) + + +def lead_in(pitch_mm: float, diameter_mm: float) -> LeadIn: + """The lead-in for a thread: 45° down to d3 rounded down to 0.1 mm. + + Args: + pitch_mm: The thread's pitch. + diameter_mm: Its major diameter. + + Returns: + LeadIn: The end diameter and the chamfer's length. + """ + minor = diameter_mm - MINOR_FACTOR * pitch_mm + end = math.floor(round(minor * 10, 6)) / 10 + return LeadIn( + end_diameter_mm=round(end, 4), length_mm=round((diameter_mm - end) / 2, 4) + ) + + +def lead_in_profile(lead: LeadIn, diameter_mm: float) -> list[tuple[float, float]]: + """The lead-in's closed outline in the axial half-plane. + + Each point is ``(radius, along)`` in mm: ``along`` is measured from the + end face into the part. The triangle's 45° side passes through the end + diameter at the face and the major diameter ``length_mm`` in, and runs + ``OVERSHOOT_MM`` past both so the cut leaves no skin. + + Args: + lead: The lead-in. + diameter_mm: The thread's major diameter. + + Returns: + list[tuple[float, float]]: The triangle's three corners. + """ + over = OVERSHOOT_MM + outer = diameter_mm / 2 + over + return [ + (lead.end_diameter_mm / 2 - over, -over), + (outer, -over), + (outer, lead.length_mm + over), + ] + + +def lead_in_reply(lead: LeadIn) -> dict[str, float | str]: + """A lead-in's dimensions as the reply gives them.""" + return { + "basis": LEAD_IN_BASIS, + "angle_deg": LEAD_IN_DEG, + "end_diameter_mm": lead.end_diameter_mm, + "length_mm": lead.length_mm, + } + + +def check_runout(params: ThreadParameters) -> None: + """Refuse a runout or lead-in that can't be built, before anything is. + + Args: + params: The thread, with its ``runout`` and ``lead_in``. + + Raises: + InputRefused: An unknown style, an undercut on an internal or an + inch thread, or a lead-in on an internal thread. + """ + if params.runout not in STYLES: + raise InputRefused(f"runout must be one of {', '.join(STYLES)}.") + if params.lead_in and params.kind != "external": + raise InputRefused( + "A lead-in chamfers an external thread's free end (ISO 4753); a " + "tapped hole's lead-in is a countersink at its opening." + ) + if not params.runout.startswith("undercut"): + return + if params.kind != "external" or params.standard != "metric": + raise InputRefused( + f"{BASIS} gives undercuts for external metric threads only; use " + "runout 'fade' for an internal or an inch thread." + ) + + +def check_width(cut: Undercut, length_mm: float) -> None: + """Refuse an undercut as wide as the thread or wider. + + Raises: + InputRefused: g2 is not shorter than the thread. + """ + if cut.width_mm >= length_mm: + raise InputRefused( + f"The Form {cut.form} undercut is {cut.width_mm:g} mm wide, as long as " + f"the {length_mm:g} mm thread or longer; make the thread longer." + ) + + +def undercut_reply(cut: Undercut) -> dict[str, float | str]: + """An undercut's dimensions as the reply gives them.""" + return { + "style": f"undercut_{cut.form.lower()}", + "form": cut.form, + "basis": BASIS, + "diameter_mm": cut.diameter_mm, + "width_mm": cut.width_mm, + "bottom_mm": cut.bottom_mm, + "radius_mm": cut.radius_mm, + "flank_deg": FLANK_DEG, + } diff --git a/src/solidworks_mcp/adapters/solidworks/__init__.py b/src/solidworks_mcp/adapters/solidworks/__init__.py index 85c03529..22f01037 100644 --- a/src/solidworks_mcp/adapters/solidworks/__init__.py +++ b/src/solidworks_mcp/adapters/solidworks/__init__.py @@ -17,6 +17,7 @@ from .sketch import SolidWorksSketchMixin from .swept import SolidWorksSweptMixin from .templates import SolidWorksTemplatesMixin +from .threads import SolidWorksThreadsMixin __all__ = [ "SolidWorksAppearanceMixin", @@ -36,4 +37,5 @@ "SolidWorksSketchMixin", "SolidWorksSweptMixin", "SolidWorksTemplatesMixin", + "SolidWorksThreadsMixin", ] diff --git a/src/solidworks_mcp/adapters/solidworks/thread_runout.py b/src/solidworks_mcp/adapters/solidworks/thread_runout.py new file mode 100644 index 00000000..af6bc7ce --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/thread_runout.py @@ -0,0 +1,423 @@ +"""A modelled thread runout on SolidWorks: a fade or a DIN 76-1 undercut. + +Measured on SolidWorks 2026 (design.md of the ``modelled-threads`` change, +decisions 8 to 12): + +- the Thread feature has two planar faces, one at each end of its groove; + the one farther along the axis from the start edge is the thread's end; +- the fade: a 3D sketch from that face's centre, swept as a cut with the + face as the profile (mark 1) and the sketch as the path (mark 4) by + ``InsertCutSwept5``; on an external thread the sketch is a straight line + along the helix's tangent (the user's video, decision 17), on an + internal one an arc tangent to the helix turning towards the axis; +- the undercut: its outline sketched on the main plane that holds the + thread's axis, with a centreline on the axis, revolved as a cut by + ``FeatureRevolve2``; +- the lead-in (decisions 13 to 15): a 45° triangle at the thread's start, + revolved as a cut the same way, after the runout. + +Every step runs inside ``create_thread``'s build, on the COM thread. +""" + +from __future__ import annotations + +import math +from typing import Any + +from ...exceptions import InputRefused +from .. import runout_rules, sw_type_info +from .com_utils import as_list, double_array +from .default_entities import entity_name +from .features import _null_callout + +#: Selection marks ``InsertCutSwept5`` reads: the profile, then the path. +_MARK_PROFILE = 1 +_MARK_PATH = 4 +#: Tolerance for an axis lying in a main plane, metres. +_IN_PLANE = 1e-7 + +Vector = list[float] + + +def _unit(v: Vector) -> Vector: + length = math.sqrt(sum(c * c for c in v)) + return [c / length for c in v] + + +def _dot(a: Vector, b: Vector) -> float: + return sum(x * y for x, y in zip(a, b, strict=True)) + + +def _along(p: Vector, a: Vector, k: float) -> Vector: + return [pc + ac * k for pc, ac in zip(p, a, strict=True)] + + +def main_plane(centre: Vector, axis: Vector) -> tuple[str, Vector]: + """The main plane holding an axis line, and the radial direction in it. + + Args: + centre: A point on the axis, metres. + axis: The axis direction, a unit vector. + + Returns: + tuple: ``Front``, ``Top`` or ``Right``, and a unit vector in that + plane square to the axis. + + Raises: + InputRefused: No main plane holds the axis. + """ + x, y, z = axis + planes = ( + ("Front", 2, [-y, x, 0.0]), + ("Top", 1, [-z, 0.0, x]), + ("Right", 0, [0.0, -z, y]), + ) + for name, index, radial in planes: + if abs(axis[index]) < _IN_PLANE and abs(centre[index]) < _IN_PLANE: + return name, _unit(radial) + raise InputRefused( + "An undercut or a lead-in is sketched on the Front, Top or Right Plane, " + "and none of them holds this thread's axis; use runout 'fade' and no " + "lead-in, or model the part with the thread's axis on a main plane." + ) + + +class SolidWorksThreadRunoutMixin: + """The fade and the undercut that end a ``create_thread`` thread.""" + + def _thread_axis(self, edge: Any) -> tuple[Vector, Vector]: + """The start edge's centre (m) and its circle's axis (unit).""" + adapter: Any = self + curve = sw_type_info.flagged( + adapter._attempt(lambda: edge.GetCurve()), "ICurve" + ) + circle = [float(v) for v in adapter._attempt(lambda: curve.CircleParams)] + return circle[:3], _unit(circle[3:6]) + + def _volume_now(self) -> float | None: + """The part's volume in mm³ now, or None unread.""" + adapter: Any = self + extension = sw_type_info.flagged( + adapter.currentModel.Extension, "IModelDocExtension" + ) + mass = adapter._attempt(lambda: extension.CreateMassProperty(), default=None) + volume = adapter._attempt(lambda: mass.Volume, default=None) + return float(volume) * 1e9 if volume is not None else None + + def _end_face( + self, thread: Any, centre: Vector, axis: Vector + ) -> tuple[Any, Vector]: + """The thread's end face, and the axis turned to point at it. + + Raises: + RuntimeError: The thread has no planar end face. + """ + adapter: Any = self + feature = sw_type_info.flagged(thread, "IFeature") + best: tuple[float, Any] | None = None + for raw in as_list(adapter._attempt(lambda: feature.GetFaces(), default=[])): + face = sw_type_info.flagged(raw, "IFace2") + surface = sw_type_info.flagged(face.GetSurface(), "ISurface") + if not surface.IsPlane(): + continue + box = [float(v) for v in face.GetBox()] + middle = [(box[i] + box[i + 3]) / 2 for i in range(3)] + reach = _dot([m - c for m, c in zip(middle, centre, strict=True)], axis) + if best is None or abs(reach) > abs(best[0]): + best = (reach, face) + if best is None: + raise RuntimeError("The thread has no planar end face to run out from.") + return best[1], axis if best[0] > 0 else [-c for c in axis] + + def _last_feature_name(self) -> str: + adapter: Any = self + last = adapter.currentModel.FeatureByPositionReverse(0) + return str(sw_type_info.flagged(last, "IFeature").Name) + + def _fade( + self, + thread: Any, + start_axis: tuple[Vector, Vector], + pitch_mm: float, + kind: str, + diameter_mm: float, + ) -> dict[str, Any]: + """Sweep the thread's end face out of the material. + + External: straight along the helix's tangent, the groove running + out of the round rod. Internal: along an arc turning towards the + axis over x1. + + Args: + thread: The Thread feature. + start_axis: Its start edge's centre (m) and axis, read before the + thread replaced the edge. + pitch_mm: The pitch. + kind: ``external`` or ``internal``. + diameter_mm: The start edge's diameter. + + Returns: + dict[str, Any]: The fade's style, method, dimensions and the + features it made. + + On failure the dict has ``error`` and the sketch it made, for the + caller to remove with the thread. + """ + adapter: Any = self + model = adapter.currentModel + centre, axis = start_axis + face, axis = self._end_face(thread, centre, axis) + box = [float(v) for v in face.GetBox()] + start = [(box[i] + box[i + 3]) / 2 for i in range(3)] + normal = [float(v) for v in face.Normal] + lead = math.atan(pitch_mm / (math.pi * diameter_mm)) + tangent = _unit( + [ + -n * math.cos(lead) + a * math.sin(lead) + for n, a in zip(normal, axis, strict=True) + ] + ) + offset = [s - c for s, c in zip(start, centre, strict=True)] + radial = _unit(_along(offset, axis, -_dot(offset, axis))) + out = radial if kind == "external" else [-c for c in radial] + sketches = model.SketchManager + sketches.Insert3DSketch(True) + sketches.AddToDB = True + if kind == "external": + shape: dict[str, Any] = runout_rules.fade_tangent(pitch_mm, diameter_mm) + basis = runout_rules.TANGENT_BASIS + end = _along(start, tangent, float(shape["path_mm"]) / 1000.0) + sketches.CreateLine(*start, *end) + else: + shape = {"method": "arc", **runout_rules.fade_arc(pitch_mm)} + basis = f"{runout_rules.BASIS} (x1)" + self._fade_arc(sketches, start, tangent, out, shape) + sketches.AddToDB = False + sketches.Insert3DSketch(True) + path = self._last_feature_name() + + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + selection = sw_type_info.flagged(model.SelectionManager, "ISelectionMgr") + data = selection.CreateSelectData() + data.Mark = _MARK_PROFILE + sw_type_info.flagged(face, "IEntity").Select4(False, data) + extension = sw_type_info.flagged(model.Extension, "IModelDocExtension") + extension.SelectByID2( + path, "SKETCH", 0.0, 0.0, 0.0, True, _MARK_PATH, _null_callout(), 0 + ) + sweep = model.FeatureManager.InsertCutSwept5( + False, False, 0, False, False, 0, 0, False, 0.0, 0.0, 0, 0, + True, True, 0.0, True, False, False, False, False, 0.0, 0, + ) # fmt: skip + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + if sweep is None: + return { + "error": f"SolidWorks made no fade: the swept cut along {path} " + "from the thread's end face failed.", + "features": [path], + } + return { + "style": "fade", + "basis": basis, + **shape, + "features": [path, str(sw_type_info.flagged(sweep, "IFeature").Name)], + } + + @staticmethod + def _fade_arc( + sketches: Any, + start: Vector, + tangent: Vector, + out: Vector, + arc: dict[str, Any], + ) -> None: + """Draw the internal fade's arc: tangent at ``start``, turning ``out``.""" + radius = float(arc["radius_mm"]) / 1000.0 + + def at(turn: float) -> Vector: + ahead = radius * math.sin(turn) + up = radius * (1 - math.cos(turn)) + return [ + s + ahead * t + up * o + for s, t, o in zip(start, tangent, out, strict=True) + ] + + turn = math.radians(float(arc["turn_deg"])) + sketches.Create3PointArc(*start, *at(turn), *at(turn / 2)) + + def _revolved_cut( + self, + plane: str, + corners: list[Vector], + arcs: dict[int, Vector], + centre: Vector, + axis: Vector, + what: str, + ) -> dict[str, Any]: + """Sketch a closed outline on a main plane and revolve it as a cut. + + Args: + plane: ``Front``, ``Top`` or ``Right``; it holds the axis. + corners: The outline's corners in model space, metres, in order. + arcs: For a side from corner i to i + 1 that is an arc, i -> a + point it passes through (model space, metres). + centre: A point on the axis, metres. + axis: The axis direction, a unit vector. + what: The cut's name in a failure message. + + Returns: + dict[str, Any]: ``features`` (the sketch and the cut), or + ``error`` and the sketch alone when SolidWorks made no cut. + """ + adapter: Any = self + model = adapter.currentModel + extension = sw_type_info.flagged(model.Extension, "IModelDocExtension") + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + extension.SelectByID2( + entity_name(adapter, plane), "PLANE", 0.0, 0.0, 0.0, False, 0, + _null_callout(), 0, + ) # fmt: skip + sketches = model.SketchManager + sketches.InsertSketch(True) + sketch = sw_type_info.flagged(sketches.ActiveSketch, "ISketch") + app = sw_type_info.flagged(adapter.swApp, "ISldWorks") + maths = sw_type_info.flagged(app.GetMathUtility(), "IMathUtility") + to_sketch = sketch.ModelToSketchTransform + + def flat(p: Vector) -> Vector: + point = sw_type_info.flagged( + maths.CreatePoint(double_array(p)), "IMathPoint" + ) + moved = sw_type_info.flagged( + point.MultiplyTransform(to_sketch), "IMathPoint" + ) + return [float(v) for v in as_list(moved.ArrayData)[:3]] + + flats = [flat(p) for p in corners] + sketches.AddToDB = True + for index, start in enumerate(flats): + end = flats[(index + 1) % len(flats)] + if index in arcs: + sketches.Create3PointArc(*start, *end, *flat(arcs[index])) + else: + sketches.CreateLine(*start, *end) + sketches.CreateCenterLine(*flat(centre), *flat(_along(centre, axis, 0.01))) + sketches.AddToDB = False + sketches.InsertSketch(True) + name = self._last_feature_name() + + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + extension.SelectByID2( + name, "SKETCH", 0.0, 0.0, 0.0, False, 0, _null_callout(), 0 + ) + revolve = model.FeatureManager.FeatureRevolve2( + True, True, False, True, False, False, 0, 0, 2 * math.pi, 0.0, + False, False, 0.0, 0.0, 0, 0.0, 0.0, True, False, True, + ) # fmt: skip + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + if revolve is None: + return { + "error": f"SolidWorks made no {what}: the revolved cut of {name} " + "failed.", + "features": [name], + } + cut = str(sw_type_info.flagged(revolve, "IFeature").Name) + return {"features": [name, cut]} + + def _undercut( + self, + thread: Any, + start_axis: tuple[Vector, Vector], + cut: runout_rules.Undercut, + diameter_mm: float, + length_mm: float, + ) -> dict[str, Any]: + """Revolve a DIN 76-1 undercut at the thread's end. + + Args: + thread: The Thread feature. + start_axis: Its start edge's centre (m) and axis. + cut: The undercut's dimensions. + diameter_mm: The thread's major diameter. + length_mm: The thread's length: the shoulder side is this far + from the start edge. + + Returns: + dict[str, Any]: The undercut's dimensions and the features it made. + + On failure the dict has ``error`` and the sketch it made, for the + caller to remove with the thread. + + Raises: + InputRefused: No main plane holds the axis. + """ + centre, axis = start_axis + plane, radial = main_plane(centre, axis) + # The axis from the start edge towards the thread's end face. + _, axis = self._end_face(thread, centre, axis) + shoulder = _along(centre, axis, length_mm / 1000.0) + points, middle = runout_rules.undercut_profile(cut, diameter_mm) + + def model_point(radius_mm: float, back_mm: float) -> Vector: + p = _along(shoulder, axis, -back_mm / 1000.0) + return _along(p, radial, radius_mm / 1000.0) + + r = cut.radius_mm + bend = model_point(middle[0] - r / math.sqrt(2), middle[1] - r / math.sqrt(2)) + made = self._revolved_cut( + plane, + [model_point(r_mm, b_mm) for r_mm, b_mm in points], + {1: bend}, + centre, + axis, + "undercut", + ) + if "error" in made: + return made + return { + **runout_rules.undercut_reply(cut), + "plane": plane, + "full_thread_mm": round(length_mm - cut.width_mm, 4), + **made, + } + + def _lead_in( + self, + start_axis: tuple[Vector, Vector], + lead: runout_rules.LeadIn, + diameter_mm: float, + ) -> dict[str, Any]: + """Revolve the 45° lead-in at the thread's start. + + Args: + start_axis: The start edge's centre (m) and the axis pointing + into the thread, from the start edge towards its end. + lead: The lead-in's size. + diameter_mm: The thread's major diameter. + + Returns: + dict[str, Any]: The lead-in's dimensions and the features it made, + or ``error`` and the sketch it made. + + Raises: + InputRefused: No main plane holds the axis. + """ + centre, axis = start_axis + plane, radial = main_plane(centre, axis) + + def model_point(radius_mm: float, along_mm: float) -> Vector: + p = _along(centre, axis, along_mm / 1000.0) + return _along(p, radial, radius_mm / 1000.0) + + outline = runout_rules.lead_in_profile(lead, diameter_mm) + made = self._revolved_cut( + plane, + [model_point(r_mm, a_mm) for r_mm, a_mm in outline], + {}, + centre, + axis, + "lead-in", + ) + if "error" in made: + return made + return {**runout_rules.lead_in_reply(lead), "plane": plane, **made} diff --git a/src/solidworks_mcp/adapters/solidworks/threads.py b/src/solidworks_mcp/adapters/solidworks/threads.py new file mode 100644 index 00000000..10433ccd --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/threads.py @@ -0,0 +1,330 @@ +"""Modelled threads on SolidWorks (queue item 43): the Thread feature. + +Measured on SolidWorks 2026 (design.md of the ``modelled-threads`` change): + +- the profiles are ``.SLDLFP`` files in the folder + ``GetUserPreferenceStringValue(swFileLocationsThreadProfiles)`` names; + each size is a configuration, read by ``ISldWorks.GetConfigurationNames`` + without opening the file; +- ``IFeatureManager.CreateDefinition(swFmSweepThread)`` gives an + ``IThreadFeatureData``; after ``InitializeThreadData`` it takes the + circular ``Edge``, the profile's name as ``Type`` (SolidWorks finds the + file), a configuration as ``Size``, ``ThreadMethod`` 0 (cut), + ``EndCondition`` 0 (blind) and ``BlindDepth`` in metres; + ``CreateFeature`` makes "Thread1". + +The thread is judged by the volume (``_measured``, direction -1): one that +cuts nothing is deleted and fails. +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +from ...exceptions import InputRefused +from .. import runout_rules, sw_type_info +from .. import thread_rules as rules +from ..base import AdapterResult, AdapterResultStatus, ThreadParameters +from . import hole_library +from .features import _null_callout +from .thread_runout import SolidWorksThreadRunoutMixin, main_plane + +#: ``swUserPreferenceStringValue_e.swFileLocationsThreadProfiles``. +_THREAD_PROFILES_FOLDER = 107 +#: ``swFeatureNameID_e.swFmSweepThread``. +_SWEEP_THREAD = 87 +#: ``swThreadMethod_e.swThreadMethod_Cut``. +_CUT = 0 +#: ``swThreadEndCondition_e.swThreadEndCondition_Blind``. +_BLIND = 0 +_PROFILE_SUFFIX = ".sldlfp" + + +class SolidWorksThreadsMixin(SolidWorksThreadRunoutMixin): + """``list_thread_sizes`` and ``create_thread`` on SolidWorks.""" + + def _profile_path(self, profile: str) -> Path: + """The profile's file, in the folder SolidWorks names for them. + + Raises: + RuntimeError: SolidWorks names no folder holding the profile. + """ + adapter: Any = self + setting = adapter._attempt( + lambda: adapter.swApp.GetUserPreferenceStringValue(_THREAD_PROFILES_FOLDER), + default="", + ) + for folder in str(setting or "").split(";"): + if not folder.strip(): + continue + for candidate in Path(folder.strip()).glob("*"): + if candidate.name.lower() == profile.lower() + _PROFILE_SUFFIX: + return candidate + raise RuntimeError( + f"SolidWorks names no thread profile '{profile}' (Tools > Options > " + f"File Locations > Thread Profiles: '{setting}')." + ) + + def _profile_sizes(self, standard: str, kind: str) -> list[str]: + """The sizes (configurations) of a standard's die or tap profile.""" + adapter: Any = self + path = self._profile_path(rules.PROFILES[(standard, kind)]) + names = adapter._attempt(lambda: adapter.swApp.GetConfigurationNames(str(path))) + if not isinstance(names, (list, tuple)) or not names: + raise RuntimeError(f"SolidWorks read no sizes from {path}.") + return [str(name) for name in names] + + def _coarse_pitches(self, standard: str) -> dict[float, float]: + """Metric coarse pitches from the installed Hole Wizard library. + + Empty for inch, or when the library can't be read; the size list + then decides coarse and fine by itself. + """ + adapter: Any = self + if standard != "metric": + return {} + rows = adapter._attempt( + lambda: hole_library.find_library().size_rows("iso", "DATA_HW_TappedHole"), + default=[], + ) + return rules.coarse_from_hole_rows(rows or []) + + def _circular_edge_at(self, point: list[float]) -> tuple[Any, float]: + """The circular edge at ``point`` (mm) and its diameter (mm). + + Raises: + InputRefused: No edge at the point, or one that isn't a circle. + """ + adapter: Any = self + model = adapter.currentModel + # New edges 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( + "", "EDGE", x, y, z, False, 0, _null_callout(), 0 + ), + default=False, + ) + manager = sw_type_info.flagged(model.SelectionManager, "ISelectionMgr") + edge = adapter._attempt(lambda: manager.GetSelectedObject6(1, -1)) + adapter._attempt(lambda: model.ClearSelection2(True)) + if not picked or edge is None: + raise InputRefused( + f"No edge at {list(point)} mm; give a point on the circular " + "edge where the thread starts." + ) + edge = sw_type_info.flagged(edge, "IEdge") + curve = sw_type_info.flagged( + adapter._attempt(lambda: edge.GetCurve()), "ICurve" + ) + circle = adapter._attempt(lambda: curve.CircleParams) + if not adapter._attempt(lambda: curve.IsCircle(), default=False) or not ( + isinstance(circle, (list, tuple)) and len(circle) >= 7 + ): + raise InputRefused( + f"The edge at {list(point)} mm is not a circle; a thread starts " + "at a cylinder's circular edge." + ) + return edge, round(float(circle[6]) * 2000.0, 4) + + async def list_thread_sizes(self, standard: str) -> AdapterResult[dict[str, Any]]: + """The sizes SolidWorks's die profile holds for a standard. + + Args: + standard: ``metric`` or ``inch``. + + Returns: + AdapterResult[dict[str, Any]]: ``standard``, ``profile``, + ``sizes`` (see :func:`..thread_rules.size_table`), ``count`` and + ``runout_basis``. + """ + adapter: Any = self + + def read() -> dict[str, Any]: + if standard not in rules.STANDARDS: + raise InputRefused( + f"standard must be one of {', '.join(rules.STANDARDS)}." + ) + sizes = rules.size_table( + self._profile_sizes(standard, "external"), + self._coarse_pitches(standard), + ) + return { + "standard": standard, + "profile": rules.PROFILES[(standard, "external")], + "sizes": sizes, + "count": len(sizes), + "runout_basis": rules.RUNOUT_BASIS[standard], + } + + return cast( + AdapterResult[dict[str, Any]], + adapter._handle_com_operation("list_thread_sizes", read), + ) + + async def create_thread( + self, params: ThreadParameters + ) -> AdapterResult[dict[str, Any]]: + """A modelled thread, cut by SolidWorks's Thread feature, measured. + + Args: + params: The kind, standard, size, edge, length and hand. + + Returns: + AdapterResult[dict[str, Any]]: ``name``, the size, pitch, depth, + runout and edge diameter, plus the volume before, after and its + change (``_measured``). + """ + adapter: Any = self + if not adapter.currentModel: + return AdapterResult( + status=AdapterResultStatus.ERROR, error="No active model" + ) + + def build() -> dict[str, Any]: + rules.check_inputs(params) + runout_rules.check_runout(params) + profile = rules.PROFILES[(params.standard, params.kind)] + size = rules.match_size( + self._profile_sizes(params.standard, params.kind), params.size + ) + edge, diameter = self._circular_edge_at(params.edge_point) + rules.check_diameter(size, params.kind, diameter) + # The edge is replaced by the thread's cut, so its axis is read now. + start_axis = self._thread_axis(edge) + cut = None + if params.runout.startswith("undercut"): + cut = runout_rules.undercut( + size.pitch_mm, size.diameter_mm, params.runout + ) + runout_rules.check_width(cut, params.length) + if cut is not None or params.lead_in: + main_plane(*start_axis) + model = adapter.currentModel + manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager") + data = sw_type_info.flagged( + manager.CreateDefinition(_SWEEP_THREAD), "IThreadFeatureData" + ) + data.InitializeThreadData() + data.Edge = edge + data.Type = profile + data.Size = size.size + data.ThreadMethod = _CUT + data.EndCondition = _BLIND + data.BlindDepth = params.length / 1000.0 + data.RightHanded = params.hand == "right" + # Start outside the part, the groove running out through the end + # face; the length is kept from the edge (design.md 16). + data.Offset = True + data.OffsetDistance = rules.START_OUTSIDE_PITCHES * size.pitch_mm / 1000.0 + data.ReverseOffset = True + data.MaintainThreadLength = True + feature = manager.CreateFeature(data) + if feature is None: + raise RuntimeError( + f"SolidWorks made no thread ({profile} {size.size} on the " + f"{diameter:g} mm edge)." + ) + entry = rules.size_entry(size, "") + # Into the thread from its start, read while its end face is whole. + inward = ( + (start_axis[0], self._end_face(feature, *start_axis)[1]) + if params.lead_in + else start_axis + ) + runout = self._runout(feature, start_axis, size, params, diameter, cut) + lead = None + if params.lead_in and not (runout or {}).get("error"): + lead = self._step( + lambda: self._lead_in( + inward, + runout_rules.lead_in(size.pitch_mm, size.diameter_mm), + size.diameter_mm, + ) + ) + return { + "runout": runout, + "lead_in": lead, + "name": str(sw_type_info.flagged(feature, "IFeature").Name), + "kind": params.kind, + "standard": params.standard, + "profile": profile, + "size": size.size, + "pitch_mm": size.pitch_mm, + "basic_depth_mm": entry["basic_depth_mm"], + "runout_mm": entry["runout_mm"], + "runout_basis": rules.RUNOUT_BASIS[params.standard], + "length_mm": params.length, + "hand": params.hand, + "edge_diameter_mm": diameter, + "turns": round(params.length / size.pitch_mm, 2), + } + + result = cast( + AdapterResult[dict[str, Any]], + await adapter._measured("create_thread", build, direction=-1), + ) + data = result.data or {} + ends = [data.get("runout") or {}, data.get("lead_in") or {}] + failed = [end["error"] for end in ends if end.get("error")] + if not failed: + return result + # A runout or lead-in failed: the thread goes too, so nothing + # half-made stays. + made = [name for end in ends for name in end.get("features", [])] + for name in [*reversed(made), data["name"]]: + await adapter.delete_feature(name) + return AdapterResult( + status=AdapterResultStatus.ERROR, + error=f"{failed[0]} The thread was removed again.", + ) + + def _runout( + self, + feature: Any, + start_axis: tuple[list[float], list[float]], + size: rules.ThreadSize, + params: ThreadParameters, + diameter: float, + cut: runout_rules.Undercut | None, + ) -> dict[str, Any] | None: + """End the thread as ``params.runout`` asks, measured on its own. + + Returns: + dict[str, Any] | None: None for ``none``; else the runout's + dimensions, the features it made and ``volume_change`` (mm³), or + ``error`` when SolidWorks built nothing. + """ + if params.runout == "none": + return None + if cut is None: + return self._step( + lambda: self._fade( + feature, start_axis, size.pitch_mm, params.kind, diameter + ) + ) + return self._step( + lambda: self._undercut( + feature, start_axis, cut, size.diameter_mm, params.length + ) + ) + + def _step(self, make: Callable[[], dict[str, Any]]) -> dict[str, Any]: + """Make one end of the thread, measured on its own. + + Returns: + dict[str, Any]: What ``make`` returned, with ``volume_change`` + (mm³) when the volume could be read before and after. + """ + before = self._volume_now() + made = make() + after = self._volume_now() + if before is not None and after is not None: + made["volume_change"] = round(after - before, 4) + return made diff --git a/src/solidworks_mcp/adapters/thread_rules.py b/src/solidworks_mcp/adapters/thread_rules.py new file mode 100644 index 00000000..922315b8 --- /dev/null +++ b/src/solidworks_mcp/adapters/thread_rules.py @@ -0,0 +1,315 @@ +"""The rules for modelled threads (queue item 43), shared by the adapter and the mock. + +Pure functions: + +- :func:`parse_size` reads a profile size (``M6x1.0``, ``1/4-20``, + ``#10-32``) into its nominal diameter and pitch in mm; +- :func:`size_table` lists sizes with coarse or fine, the ISO 68-1 basic + depth and the ISO 3508 runout; +- :func:`check_diameter` refuses a cylinder whose diameter doesn't suit the + size; +- :func:`match_size` finds a size by name, ignoring case, or refuses with the + nearest names. + +Sources (research note ``openspec/research/modelled-threads.md``): + +- ISO 68-1: H = √3/2 P; the basic depth of engagement H1 = 5/8 H. +- ISO 3508 (read in IS 1369 Part 1): runout x, normal ≈ 2.5P, short + ≈ 1.25P. For inch threads the same rule on P = 25.4/TPI is a reasoned + default, not a standard (the user's decision 6). +- Numbered inch sizes: #N is 0.060 + 0.013 N inch (ASME B1.1). +""" + +from __future__ import annotations + +import math +import re +from collections.abc import Sequence +from dataclasses import dataclass +from fractions import Fraction +from typing import Any + +from ..exceptions import InputRefused +from .base import ThreadParameters + +#: The standards and their profile names. +STANDARDS = ("metric", "inch") +#: ``(standard, kind) -> profile`` in the Thread Profiles folder. +PROFILES = { + ("metric", "external"): "Metric Die", + ("metric", "internal"): "Metric Tap", + ("inch", "external"): "Inch Die", + ("inch", "internal"): "Inch Tap", +} +#: ISO 68-1: the basic depth of engagement over the pitch, 5/8 × √3/2. +BASIC_DEPTH = 5 / 8 * math.sqrt(3) / 2 +#: Pitches the thread starts outside the part, as a die or tap starts in +#: the air, so its groove runs out through the end face. +START_OUTSIDE_PITCHES = 2.0 +#: ISO 3508 runout over the pitch. +RUNOUT = {"normal": 2.5, "short": 1.25} +#: Where each standard's runout rule comes from. +RUNOUT_BASIS = { + "metric": "ISO 3508 (normal 2.5P, short 1.25P)", + "inch": ( + "the ISO 3508 rule on the inch pitch (P = 25.4/TPI): a reasoned " + "default, as no free inch standard gives a runout length" + ), +} +MM_PER_INCH = 25.4 +_METRIC = re.compile(r"^M(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)$", re.IGNORECASE) +_INCH = re.compile(r"^(#\d+|\d+-\d+/\d+|\d+/\d+|\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$") +_NEAREST = 6 + + +@dataclass(frozen=True) +class ThreadSize: + """One thread size. + + Attributes: + size: The profile's name for it, e.g. ``M6x1.0``. + diameter_mm: The nominal (major) diameter. + pitch_mm: The pitch. + tpi: Threads per inch (inch sizes), else None. + """ + + size: str + diameter_mm: float + pitch_mm: float + tpi: float | None = None + + +def _inch_diameter(text: str) -> float: + """A nominal inch size in inches: ``#10``, ``1/4``, ``1-1/2`` or ``0.2500``.""" + if text.startswith("#"): + return 0.060 + 0.013 * int(text[1:]) + if "/" not in text: + return float(text) + whole, _, fraction = text.rpartition("-") + numerator, denominator = fraction.split("/") + return (float(whole) if whole else 0.0) + int(numerator) / int(denominator) + + +def inch_label(diameter_in: float, tpi: float) -> str | None: + """A fractional name, e.g. ``1/4-20``, for a size in 64ths of an inch. + + Args: + diameter_in: The nominal diameter, inches. + tpi: Threads per inch. + + Returns: + str | None: ``1/4-20`` or ``1-1/2-6``; None when the diameter isn't + a whole number of 64ths. + """ + sixty_fourths = diameter_in * 64 + if abs(sixty_fourths - round(sixty_fourths)) > 1e-6: + return None + whole, part = divmod(round(sixty_fourths), 64) + turns = f"{tpi:g}" + if part == 0: + return f"{whole}-{turns}" + fraction = Fraction(part, 64) + text = f"{fraction.numerator}/{fraction.denominator}" + return f"{whole}-{text}-{turns}" if whole else f"{text}-{turns}" + + +def parse_size(size: str) -> ThreadSize | None: + """A profile size read as diameter and pitch, or None if it isn't one. + + Args: + size: ``M6x1.0``, ``1/4-20``, ``#10-32`` or ``1-1/2-6``. + + Returns: + ThreadSize | None: The size, or None for a name in another form. + + Example: + >>> parse_size("1/4-20").pitch_mm + 1.27 + """ + text = size.strip() + metric = _METRIC.match(text) + if metric: + return ThreadSize(text, float(metric.group(1)), float(metric.group(2))) + inch = _INCH.match(text) + if inch: + tpi = float(inch.group(2)) + return ThreadSize( + text, + round(_inch_diameter(inch.group(1)) * MM_PER_INCH, 4), + round(MM_PER_INCH / tpi, 4), + tpi, + ) + return None + + +def runout(pitch_mm: float) -> dict[str, float]: + """The ISO 3508 runout for a pitch: normal and short, mm.""" + return {name: round(factor * pitch_mm, 2) for name, factor in RUNOUT.items()} + + +def size_entry(size: ThreadSize, pitch_class: str) -> dict[str, Any]: + """One size as ``list_thread_sizes`` lists it.""" + entry: dict[str, Any] = { + "size": size.size, + "diameter_mm": size.diameter_mm, + "pitch_mm": size.pitch_mm, + "pitch_class": pitch_class, + "basic_depth_mm": round(BASIC_DEPTH * size.pitch_mm, 4), + "runout_mm": runout(size.pitch_mm), + } + if size.tpi is not None: + entry["tpi"] = size.tpi + # Decimal names ("0.2500-20") also go by their fraction ("1/4-20"); + # numbered sizes ("#5-40") keep their own name. + label = inch_label(size.diameter_mm / MM_PER_INCH, size.tpi) + if label and not size.size.startswith("#") and label != size.size: + entry["also"] = label + return entry + + +def size_table( + names: Sequence[str], coarse: dict[float, float] | None = None +) -> list[dict[str, Any]]: + """Sizes by diameter then pitch, each classed coarse, fine or only. + + With ``coarse`` (nominal diameter -> coarse pitch, e.g. from the Hole + Wizard's plain ``M6`` rows), a size at a known diameter is ``coarse`` + when its pitch is that one and ``fine`` otherwise. Elsewhere the list + decides: at one diameter the coarsest pitch is ``coarse`` and the others + ``fine``, and a diameter with one size is ``only``. Names that aren't + sizes are left out. + + Args: + names: The profile's configuration names. + coarse: Known coarse pitches by diameter, mm. + + Returns: + list[dict[str, Any]]: :func:`size_entry` for each size. + """ + known = coarse or {} + sizes = [parsed for name in names if (parsed := parse_size(str(name)))] + by_diameter: dict[float, list[ThreadSize]] = {} + for size in sizes: + by_diameter.setdefault(size.diameter_mm, []).append(size) + table = [] + for diameter in sorted(by_diameter): + group = sorted(by_diameter[diameter], key=lambda s: -s.pitch_mm) + for index, size in enumerate(group): + if diameter in known: + same = abs(size.pitch_mm - known[diameter]) < 1e-6 + pitch_class = "coarse" if same else "fine" + elif len(group) == 1: + pitch_class = "only" + else: + pitch_class = "coarse" if index == 0 else "fine" + table.append(size_entry(size, pitch_class)) + return table + + +def match_size(names: Sequence[str], wanted: str) -> ThreadSize: + """The size ``wanted`` names, ignoring case, as the profile spells it. + + Args: + names: The profile's sizes. + wanted: The size asked for. + + Returns: + ThreadSize: The size. + + Raises: + InputRefused: No such size; the message names the nearest ones. + """ + folded = wanted.strip().lower().replace(" ", "") + for name in names: + if str(name).lower() == folded: + parsed = parse_size(str(name)) + if parsed: + return parsed + asked = parse_size(wanted) + sizes = [parsed for name in names if (parsed := parse_size(str(name)))] + for size in sizes: + if ( + asked + and abs(size.diameter_mm - asked.diameter_mm) < 1e-3 + and abs(size.pitch_mm - asked.pitch_mm) < 1e-3 + ): + return size + if asked: + sizes.sort( + key=lambda s: ( + abs(s.diameter_mm - asked.diameter_mm), + abs(s.pitch_mm - asked.pitch_mm), + ) + ) + nearest = ", ".join(s.size for s in sizes[:_NEAREST]) or "none" + raise InputRefused( + f"No thread size '{wanted}' in the profile; nearest: {nearest}. " + "list_thread_sizes names them all." + ) + + +def expected_diameter(size: ThreadSize, kind: str) -> float: + """The cylinder diameter a thread wants: nominal, or about the tap drill.""" + if kind == "internal": + return round(size.diameter_mm - size.pitch_mm, 4) + return size.diameter_mm + + +def check_diameter(size: ThreadSize, kind: str, edge_diameter_mm: float) -> None: + """Refuse an edge whose diameter doesn't suit the size, within one pitch. + + Args: + size: The thread size. + kind: ``external`` or ``internal``. + edge_diameter_mm: The picked edge's diameter. + + Raises: + InputRefused: The diameter is more than one pitch off. + """ + want = expected_diameter(size, kind) + if abs(edge_diameter_mm - want) > size.pitch_mm: + what = "rod" if kind == "external" else "hole (about the tap drill)" + raise InputRefused( + f"The edge is {edge_diameter_mm:g} mm across but {size.size} " + f"{kind} wants a {what} of about {want:g} mm. Pick the right " + "edge or size (list_thread_sizes)." + ) + + +_PLAIN_METRIC = re.compile(r"^M(\d+(?:\.\d+)?)$", re.IGNORECASE) + + +def coarse_from_hole_rows(rows: Sequence[dict[str, Any]]) -> dict[float, float]: + """Coarse pitches by diameter from the Hole Wizard's ISO tapped-hole rows. + + The library names the coarse series plainly (``M6``) and the fine ones + with their pitch (``M8x1.0``); the plain rows give each diameter's + coarse pitch. + + Args: + rows: :meth:`HoleLibrary.size_rows` rows (``size``, ``dimensions``). + + Returns: + dict[float, float]: Nominal diameter -> coarse pitch, mm. + """ + coarse: dict[float, float] = {} + for row in rows: + match = _PLAIN_METRIC.match(str(row.get("size") or "")) + pitch = (row.get("dimensions") or {}).get("pitch") + if match and isinstance(pitch, (int, float)): + coarse[float(match.group(1))] = float(pitch) + return coarse + + +def check_inputs(params: ThreadParameters) -> None: + """Refuse a kind, standard, hand, point or length that can't work.""" + if params.standard not in STANDARDS: + raise InputRefused(f"standard must be one of {', '.join(STANDARDS)}.") + if params.kind not in ("external", "internal"): + raise InputRefused("kind must be 'external' or 'internal'.") + if params.hand not in ("right", "left"): + raise InputRefused("hand must be 'right' or 'left'.") + if len(params.edge_point) != 3: + raise InputRefused("edge_point must be [x, y, z] in mm.") + if params.length <= 0: + raise InputRefused("length must be greater than 0 mm.") diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md index c6a01113..4577b2ec 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md @@ -109,7 +109,30 @@ A cut or a `create_hole` hole that already exists can be repeated instead: 5. `set_flat_pattern` with `flat: true` gives the blank's size; check it, `export_flat_pattern` for the DXF, then `flat: false` to fold it back. -## A spring or a modelled thread (a helix and a sweep) +## A standard thread (a bolt, a tapped hole) + +1. `list_thread_sizes` (`metric` or `inch`) names the sizes SolidWorks + holds, with coarse or fine, the basic depth and the runout. M3 to M6 + are the common bolt sizes. +2. External: extrude a rod of the nominal diameter (M6: 6 mm), then + `create_thread` with `size`, `length` and `edge_point` on the rod's end + edge. Internal: `create_hole` with `hole_type` tapped makes the tap + drill; then `create_thread` with `kind` internal and `edge_point` on the + hole's edge at its opening. +3. End it as a machined thread with `runout`: `fade` (any thread: the + groove is swept straight along the helix's tangent out of a rod, or + along an arc over DIN 76-1's x1 in a hole) or, on an external metric thread + up to a shoulder or head, "undercut_a" (DIN 76-1 Form A; "undercut_b" + is the short form). With an undercut, give `length` up to the + shoulder. Without a runout, leave the reply's `runout_mm` (normal) + between the thread's end and a shoulder. A thread that cuts nothing + fails and is removed. +4. For a bolt, give `lead_in` too: the free end is chamfered 45° so it + starts in a nut (ISO 4753). The runout stays at the shoulder. +4. When the user mentions fasteners and a hole is tapped, ask whether to + model its thread; `add_cosmetic_thread` only marks one for drawings. + +## A spring or a custom thread (a helix and a sweep) 1. `create_part`, `create_sketch` on "Top", one `add_circle` (the helix's diameter; its centre is on the axis), `exit_sketch`. diff --git a/src/solidworks_mcp/tools/__init__.py b/src/solidworks_mcp/tools/__init__.py index d7c8539e..c8a22808 100644 --- a/src/solidworks_mcp/tools/__init__.py +++ b/src/solidworks_mcp/tools/__init__.py @@ -27,6 +27,7 @@ from .server_admin import register_server_admin_tools from .sketching import register_sketching_tools from .template_management import register_template_management_tools +from .threads import register_thread_tools from .vba_generation import register_vba_generation_tools @@ -47,6 +48,7 @@ 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_thread_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) diff --git a/src/solidworks_mcp/tools/error_classifier.py b/src/solidworks_mcp/tools/error_classifier.py index 2047d7a9..b8f2754c 100644 --- a/src/solidworks_mcp/tools/error_classifier.py +++ b/src/solidworks_mcp/tools/error_classifier.py @@ -296,6 +296,55 @@ def matches(self, message: str, hresult: int | None) -> bool: r"SolidWorks did not keep the colour", ), ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "Use a size from list_thread_sizes, and pick the circular edge where " + "the thread starts: a rod of the nominal diameter (external) or a " + "hole of about the tap drill (internal)." + ), + patterns=( + r"No thread size '", + r"No edge at \[", + r"is not a circle; a thread starts", + r"wants a (rod|hole \(about the tap drill\)) of about", + r"(standard|kind|hand) must be", + r"length must be greater than 0", + ), + ), + ErrorRule( + error_type=INVALID_INPUT, + hint=( + "A DIN 76-1 undercut needs an external metric thread longer than the " + "undercut, and a lead-in an external thread, each with its axis on " + "the Front, Top or Right Plane; otherwise use runout 'fade' and no " + "lead-in." + ), + patterns=( + r"runout must be one of", + r"gives undercuts for external metric threads only", + r"has no undercut for a [\d.]+ mm pitch", + r"undercut is [\d.]+ mm wide", + r"none of them holds this thread's axis", + r"A lead-in chamfers an external thread", + ), + ), + ErrorRule( + error_type="feature_not_built", + hint=( + "SolidWorks made no thread. Check the edge is a cylinder's end and " + "the size suits it, then retry." + ), + patterns=(r"SolidWorks made no thread",), + ), + ErrorRule( + error_type="feature_not_built", + hint=( + "SolidWorks made the thread but not its runout or lead-in, so all of " + "it was removed. Retry with runout 'none' or lead_in off." + ), + patterns=(r"SolidWorks made no (fade|undercut|lead-in)",), + ), ErrorRule( error_type=INVALID_INPUT, hint=( diff --git a/src/solidworks_mcp/tools/modeling.py b/src/solidworks_mcp/tools/modeling.py index a667389d..c9646985 100644 --- a/src/solidworks_mcp/tools/modeling.py +++ b/src/solidworks_mcp/tools/modeling.py @@ -3388,8 +3388,10 @@ async def create_hole(input_data: CreateHoleInput) -> dict[str, Any]: Hole Wizard library (`list_hole_sizes`): an unknown size is refused, with the nearest ones, before anything is made. A simple hole can't be through all in SolidWorks, so it is made blind through the part (`end_condition_used`, with - a warning). It fails when the volume doesn't change. Needs: an open part with - a flat face at `face_point`. Changes: adds a hole feature. Returns: `hole` + a warning). It fails when the volume doesn't change. A tapped hole's thread + is not modelled; when fasteners matter, ask whether to add one with + `create_thread` (`kind` internal, sizes from `list_thread_sizes`) at the + hole's edge. Needs: an open part with a flat face at `face_point`. Changes: adds a hole feature. Returns: `hole` with `name`, `hole_count`, `hole_type`, `standard`, `fastener` (the hole type used), `size`, `end_condition`, `end_condition_used`, and `volume_before`, `volume_after` and `volume_change` (mm³). diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index ae7f33a7..ec4de662 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -352,6 +352,15 @@ def _deprecated(replacement: str | None) -> Support: SupportLevel.BETA, "new: checked on SolidWorks by a scratch run, not yet by a live demo.", ), + # Queue item 43: beta until the threads live demo. + "create_thread": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), + "list_thread_sizes": Support( + SupportLevel.BETA, + "new: checked on SolidWorks by a scratch run, not yet by a live demo.", + ), "delete_feature": _STABLE, "get_dimension": _STABLE, "insert_component": _STABLE, diff --git a/src/solidworks_mcp/tools/threads.py b/src/solidworks_mcp/tools/threads.py new file mode 100644 index 00000000..a02dfae6 --- /dev/null +++ b/src/solidworks_mcp/tools/threads.py @@ -0,0 +1,212 @@ +"""Modelled threads: the standard sizes, and external or internal threads (queue item 43). + +``list_thread_sizes`` reads the sizes SolidWorks's own thread profiles hold, +with coarse or fine, the ISO 68-1 basic depth and the ISO 3508 runout; +``create_thread`` cuts a thread with SolidWorks's Thread feature, checked +before and measured after. ``add_cosmetic_thread`` remains for a thread +shown only in drawings. +""" + +from __future__ import annotations + +from typing import Any, Literal + +from fastmcp import FastMCP +from pydantic import Field + +from ..adapters.base import SolidWorksAdapter, ThreadParameters +from .input_compat import CompatInput +from .tool_boundary import ( + normalize_input, + require_capability, + require_success, + with_tool_boundary, +) + + +class ThreadSizesInput(CompatInput): + """Input schema for listing thread sizes. + + Attributes: + standard (str): ``metric`` or ``inch``. + """ + + standard: Literal["metric", "inch"] = Field( + default="metric", description="'metric' (ISO, e.g. M6x1.0) or 'inch' (UTS)" + ) + + +class CreateThreadInput(CompatInput): + """Input schema for a modelled thread. + + Attributes: + kind (str): ``external`` or ``internal``. + standard (str): ``metric`` or ``inch``. + size (str): A size from ``list_thread_sizes``. + edge_point (list[float]): ``[x, y, z]`` mm on the circular edge. + length (float): mm. + hand (str): ``right`` or ``left``. + runout (str): ``none``, ``fade``, ``undercut_a`` or ``undercut_b``. + lead_in (bool): Chamfer the thread's start 45° (ISO 4753). + """ + + kind: Literal["external", "internal"] = Field( + default="external", + description="'external' (a bolt or rod, male) or 'internal' (a tapped " + "hole, female)", + ) + standard: Literal["metric", "inch"] = Field( + default="metric", description="'metric' or 'inch'" + ) + size: str = Field( + min_length=1, + description="A size as list_thread_sizes names it, e.g. 'M6x1.0'; inch " + "also takes '1/4-20'", + ) + edge_point: list[float] = Field( + min_length=3, + max_length=3, + description="[x, y, z] in mm on the circular edge where the thread " + "starts: a rod's end edge, or a hole's edge at its opening", + ) + length: float = Field(gt=0, description="Length of full thread in mm") + hand: Literal["right", "left"] = Field( + default="right", description="'right' (the usual) or 'left' hand" + ) + runout: Literal["none", "fade", "undercut_a", "undercut_b"] = Field( + default="none", + description="How the thread ends: 'none' (square), 'fade' (the groove " + "runs out: swept straight along the helix's tangent on a rod, along an " + "arc over DIN 76-1's x1 in a hole), 'undercut_a' or 'undercut_b' (a DIN 76-1 " + "Form A or short Form B groove at the end; external metric only, and " + "`length` then reaches the shoulder)", + ) + lead_in: bool = Field( + default=False, + description="Chamfer the thread's start 45° to just under the minor " + "diameter (ISO 4753's chamfered end), so the part starts in a nut; made " + "last; external threads only", + ) + + +def _lead_in_words(lead: dict[str, Any] | None) -> str: + """The message's words for a lead-in, or nothing without one.""" + if not lead: + return "" + return ( + f", its start chamfered {lead['angle_deg']:g}° to " + f"{lead['end_diameter_mm']:g} mm" + ) + + +def _runout_words(runout: dict[str, Any] | None) -> str: + """The message's words for a runout, or nothing for none.""" + if not runout: + return "" + if runout["style"] == "fade": + return f", fading out over {runout['length_mm']:g} mm" + return ( + f", ending in a DIN 76-1 Form {runout['form']} undercut " + f"(dg {runout['diameter_mm']:g} x {runout['width_mm']:g} mm)" + ) + + +async def register_thread_tools( + mcp: FastMCP, adapter: SolidWorksAdapter, config: Any +) -> int: + """Register the thread 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 list_thread_sizes( + input_data: ThreadSizesInput | None = None, + ) -> dict[str, Any]: + """List the standard thread sizes SolidWorks holds, metric or inch, with coarse or fine pitch, depth and runout. + + Read from SolidWorks's own thread profiles, so every size works in + `create_thread`. Each size gives `diameter_mm`, `pitch_mm` (`tpi` for + inch), `pitch_class` (coarse, fine, or only), `basic_depth_mm` (ISO + 68-1) and `runout_mm` (normal and short, ISO 3508; for inch the same + rule on 1/TPI, as `runout_basis` says). M3 to M6 are the common bolt + sizes. Needs: SolidWorks running. Read-only. Returns: `sizes`, + `count`, `profile` and `runout_basis`. + + Args: + input_data: Optional `standard`, metric by default. + + Returns: + dict[str, Any]: The sizes. + """ + input_data = normalize_input(input_data or {}, ThreadSizesInput) + require_capability( + adapter, "list_thread_sizes", "Active adapter can't read thread sizes" + ) + result = await adapter.list_thread_sizes(input_data.standard) + require_success(result, "Failed to read the thread sizes") + data = result.data or {} + return { + "status": "success", + "message": f"{data.get('count', 0)} {input_data.standard} thread sizes", + **data, + "execution_time": result.execution_time, + } + + @mcp.tool() + async def create_thread(input_data: CreateThreadInput) -> dict[str, Any]: + """Cut a modelled thread, external (a bolt) or internal (a tapped hole), at a standard size. + + `edge_point` is on the circular edge where it starts: a rod's end (rod + at the nominal diameter, M6: 6 mm) or a hole's opening (about the tap + drill, M6: 5 mm). Fails, changing nothing, for a size not in + `list_thread_sizes`, no circular edge there, or a diameter that + doesn't suit; a thread that cuts nothing is undone. `runout` ends it at + the shoulder end: `fade` sweeps the groove straight along the helix's + tangent out of a rod (in a hole: an arc over x1); + `undercut_a`/`undercut_b` cut a DIN 76-1 Form A or B groove whose + shoulder side is `length` from the start (external metric). + `lead_in` chamfers the start 45° to just under the minor diameter, so + a bolt starts in a nut (external; made last). Undercut and lead-in + need the axis on the Front, Top or Right Plane. Needs: an open part + with the cylinder or hole. Changes: adds a Thread feature, and each + end's sketch and cut. Returns: `thread` with `name`, `size`, + `pitch_mm`, `runout_mm`, `turns`, `volume_change`, `runout` and + `lead_in` (dimensions, features, volume). + + Args: + input_data: `size`, `edge_point` and `length`; `kind`, `standard`, + `hand`, `runout` and `lead_in` optional. + + Returns: + dict[str, Any]: The thread and its measured change. + """ + input_data = normalize_input(input_data, CreateThreadInput) + require_capability( + adapter, "create_thread", "Active adapter can't model threads" + ) + result = await adapter.create_thread( + ThreadParameters(**input_data.model_dump()) + ) + require_success(result, "Failed to create the thread") + data = result.data or {} + return { + "status": "success", + "message": ( + f"{data.get('name')}: {data.get('size')} {input_data.kind}, " + f"{input_data.length:g} mm, {float(data.get('volume_change') or 0):,.1f} mm³" + + _runout_words(data.get("runout")) + + _lead_in_words(data.get("lead_in")) + ), + "thread": data, + "execution_time": result.execution_time, + } + + return 2 diff --git a/src/solidworks_mcp/tools/tool_hints.py b/src/solidworks_mcp/tools/tool_hints.py index 80a52c91..04c17335 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -208,6 +208,8 @@ def _discards(title: str) -> ToolHints: "move_copy_body": _adds("Move/Copy Body"), "delete_bodies": _discards("Delete/Keep Bodies"), "scale_body": _adds("Scale Body"), + "list_thread_sizes": _reads("List Thread Sizes"), + "create_thread": _adds("Create Thread"), "set_appearance": _sets("Set Appearance"), "get_appearance": _reads("Get Appearance"), "create_coordinate_system": _adds("Create Coordinate System"), diff --git a/src/solidworks_mcp/tools/toolsets.py b/src/solidworks_mcp/tools/toolsets.py index f068a3f5..9e4c166a 100644 --- a/src/solidworks_mcp/tools/toolsets.py +++ b/src/solidworks_mcp/tools/toolsets.py @@ -20,6 +20,7 @@ "modeling", "equations", "bodies", + "threads", "appearance", "reference_extras", "assembly", diff --git a/tests/integration/test_skill_content.py b/tests/integration/test_skill_content.py index e8866c9b..cedc97aa 100644 --- a/tests/integration/test_skill_content.py +++ b/tests/integration/test_skill_content.py @@ -41,6 +41,7 @@ "length_m", "length_mm", "measured_change", + "runout_mm", "size_mm", "start_point_mm", "system_value", diff --git a/tests/integration/test_tool_descriptions.py b/tests/integration/test_tool_descriptions.py index 86f8f764..0dcd0a0a 100644 --- a/tests/integration/test_tool_descriptions.py +++ b/tests/integration/test_tool_descriptions.py @@ -37,6 +37,7 @@ "server_admin", "sketching", "template_management", + "threads", "vba_generation", ] diff --git a/tests/live/test_live_sw_threads.py b/tests/live/test_live_sw_threads.py new file mode 100644 index 00000000..0875fe7c --- /dev/null +++ b/tests/live/test_live_sw_threads.py @@ -0,0 +1,269 @@ +"""Modelled threads (queue item 43), checked on real SolidWorks. + +1. A bolt-like rod: the metric sizes listed (M3 to M6 coarse); a 6 mm rod + 25 mm long; on purpose, M10x1.5 on it is refused (the rod is 6 mm); then + M6x1.0 cut 12 mm from its end with a lead-in: material removed, 12 + turns, runout 2.5 mm, the start chamfered 45° to 4.7 mm. And a 1/4-20 + inch thread on a 6.35 mm rod. Each thread is then seen side on (the Left + view), both its ends in frame. +2. A tapped hole: a 20 x 20 x 15 mm block, an M6 tapped hole from + ``create_hole`` (its 5 mm tap drill), and an internal M6x1.0 thread 10 mm + into it. +3. Runouts: a faded M6; an M6 to a 10 mm collar ending in a DIN 76-1 Form A + undercut there, its free end chamfered by a lead-in; on purpose, an + undercut in a tapped hole is refused. + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_threads.py::test_a_bolt_like_rod + +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 + +_ISO_VIEW = 7 # swStandardViews_e.swIsometricView +_LEFT_VIEW = 3 # swStandardViews_e.swLeftView + + +async def _tools(adapter: Any) -> dict[str, Any]: + """The modelling tools plus the thread tools.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.threads import register_thread_tools + + tools = await _base_tools(adapter) + mcp = FastMCP("threads-live") + await register_thread_tools(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 _rod(tools: dict[str, Any], name: str, radius: float, length: float) -> None: + """A rod on the Top Plane, its end edge at y = length.""" + await _ok(await tools["create_part"]({"name": name})) + await _ok(await tools["create_sketch"]({"plane": "Top"})) + await _ok( + await tools["add_circle"]({"center_x": 0, "center_y": 0, "radius": radius}) + ) + await _ok(await tools["exit_sketch"]()) + await _ok(await tools["create_extrusion"]({"depth": length})) + + +def _both_ends( + adapter: Any, label: str, radius: float, top: float, length: float +) -> None: + """Side-on close-up of a rod's thread, its start and its end in frame.""" + _close_up( + adapter, + [-radius - 2, top - length - 3, -radius, radius + 2, top + 1, radius], + view=_LEFT_VIEW, + ) + evidence( + f"{label}: the thread's start and end, side on", + {"from_y_mm": top - length, "to_y_mm": top}, + ) + + +async def test_a_bolt_like_rod(scratch: Any) -> None: + """Metric sizes, a refused size, an M6 thread and a 1/4-20 thread.""" + adapter = scratch.adapter + tools = await _tools(adapter) + + listed = await _ok(await tools["list_thread_sizes"]({"standard": "metric"})) + common = [ + s for s in listed["sizes"] if s["diameter_mm"] in (3.0, 4.0, 5.0, 6.0, 8.0) + ] + evidence( + "metric sizes M3 to M8 from SolidWorks's profile", + {"count": listed["count"], "sizes": common, "runout": listed["runout_basis"]}, + call='list_thread_sizes({"standard": "metric"})', + ) + by_size = {s["size"]: s for s in listed["sizes"]} + assert by_size["M6x1.0"]["pitch_class"] == "coarse" + assert by_size["M8x1.0"]["pitch_class"] == "fine" + + await _rod(tools, "m6-rod", 3, 25) + _iso(adapter) + + # On purpose: a size the rod can't take. + refused = await tools["create_thread"]( + {"size": "M10x1.5", "edge_point": [3, 25, 0], "length": 12} + ) + evidence("M10 on a 6 mm rod is refused", refused) + assert refused["status"] == "error" and refused["error_type"] == "invalid_input" + + call = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "lead_in": True} + made = await _ok(await tools["create_thread"](call)) + _iso(adapter) + evidence( + "M6x1.0 cut 12 mm from the rod's end, its start chamfered to 4.7 mm", + made["thread"], + call=f"create_thread({call})", + ) + thread = made["thread"] + assert thread["volume_change"] < 0 + assert thread["turns"] == pytest.approx(12) + assert thread["runout_mm"]["normal"] == pytest.approx(2.5) + assert thread["lead_in"]["end_diameter_mm"] == pytest.approx(4.7) + assert thread["lead_in"]["volume_change"] < 0 + _both_ends(adapter, "M6x1.0", 3, 25, 12) + + await _rod(tools, "quarter-twenty", 3.175, 25) + call = { + "standard": "inch", + "size": "1/4-20", + "edge_point": [3.175, 25, 0], + "length": 12.7, + } + inch = await _ok(await tools["create_thread"](call)) + _iso(adapter) + evidence( + "1/4-20 on a 6.35 mm rod (runout by the ISO rule on 1/20 in)", + inch["thread"], + call=f"create_thread({call})", + ) + assert inch["thread"]["size"] == "0.2500-20" + assert inch["thread"]["volume_change"] < 0 + _both_ends(adapter, "1/4-20", 3.175, 25, 12.7) + + +async def test_a_tapped_hole(scratch: Any) -> None: + """create_hole's M6 tapped hole, then an internal M6x1.0 thread in it.""" + adapter = scratch.adapter + tools = await _tools(adapter) + await _ok(await tools["create_part"]({"name": "tapped-block"})) + await _ok(await tools["create_sketch"]({"plane": "Top"})) + await _ok(await tools["add_rectangle"]({"x1": -10, "y1": -10, "x2": 10, "y2": 10})) + await _ok(await tools["exit_sketch"]()) + await _ok(await tools["create_extrusion"]({"depth": 15})) + hole = await _ok( + await tools["create_hole"]( + {"face_point": [0, 15, 0], "hole_type": "tapped", "size": "M6"} + ) + ) + _iso(adapter) + evidence("an M6 tapped hole (its 5 mm tap drill)", hole["hole"]) + + call = { + "kind": "internal", + "size": "M6x1.0", + "edge_point": [2.5, 15, 0], + "length": 10, + } + made = await _ok(await tools["create_thread"](call)) + _iso(adapter) + evidence( + "an internal M6x1.0 thread 10 mm into the hole", + made["thread"], + call=f"create_thread({call})", + ) + assert made["thread"]["profile"] == "Metric Tap" + assert made["thread"]["edge_diameter_mm"] == pytest.approx(5.0, abs=0.2) + assert made["thread"]["volume_change"] < 0 + + +def _close_up(adapter: Any, box_mm: list[float], view: int = _ISO_VIEW) -> None: + """Zoom the camera onto a box of the part (staging, not a tool call).""" + model = adapter.currentModel + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + adapter._attempt(lambda: model.ShowNamedView2("", view), default=None) + adapter._attempt( + lambda: model.ViewZoomTo2(*(v / 1000 for v in box_mm)), default=None + ) + + +async def test_thread_runouts(scratch: Any) -> None: + """A faded M6 runout; at a collar, a Form A undercut and a lead-in; a refusal. + + The runout is at the shoulder, where the die stops (DIN 76-1); the + lead-in chamfers the free end, where the bolt starts in a nut (ISO 4753). + """ + adapter = scratch.adapter + tools = await _tools(adapter) + + await _rod(tools, "faded-m6", 3, 25) + call = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "runout": "fade"} + faded = await _ok(await tools["create_thread"](call)) + _close_up(adapter, [-4, 10, -4, 4, 16, 4]) + evidence( + "M6x1.0 whose groove fades out", faded["thread"], call=f"create_thread({call})" + ) + fade = faded["thread"]["runout"] + # The video's method: straight along the helix's tangent, tapering out. + assert (fade["style"], fade["method"]) == ("fade", "tangent") + assert fade["length_mm"] == pytest.approx(1.72) + assert fade["volume_change"] < 0 + + # A 6 mm rod on a 10 mm collar: the shoulder is at y = 0. + await _rod(tools, "undercut-m6", 3, 25) + await _ok(await tools["create_sketch"]({"plane": "Top"})) + await _ok(await tools["add_circle"]({"center_x": 0, "center_y": 0, "radius": 5})) + await _ok(await tools["exit_sketch"]()) + await _ok(await tools["create_extrusion"]({"depth": 6, "reverse_direction": True})) + call = { + "size": "M6x1.0", + "edge_point": [3, 25, 0], + "length": 25, + "runout": "undercut_a", + "lead_in": True, + } + cut = await _ok(await tools["create_thread"](call)) + _close_up(adapter, [-6, -3, -6, 6, 8, 6]) + evidence( + "M6x1.0 to the collar, ending in a DIN 76-1 Form A undercut there", + cut["thread"], + call=f"create_thread({call})", + ) + undercut = cut["thread"]["runout"] + assert undercut["diameter_mm"] == pytest.approx(4.4) + assert undercut["width_mm"] == pytest.approx(3.5) + assert undercut["radius_mm"] == pytest.approx(0.5) + assert undercut["volume_change"] < 0 + lead = cut["thread"]["lead_in"] + assert lead["end_diameter_mm"] == pytest.approx(4.7) + assert lead["length_mm"] == pytest.approx(0.65) + assert lead["volume_change"] < 0 + _close_up(adapter, [-5, 19, -5, 5, 26, 5]) + evidence( + "its free end: the 45° lead-in that starts it in a nut", + lead, + call="(the same create_thread call: lead_in)", + ) + _both_ends(adapter, "the bolt", 5, 25, 26) + + # On purpose: an undercut is for external threads. + refused = await tools["create_thread"]( + { + "kind": "internal", + "size": "M6x1.0", + "edge_point": [2.5, 15, 0], + "length": 10, + "runout": "undercut_a", + } + ) + evidence("an undercut in a tapped hole is refused", refused) + assert refused["status"] == "error" and refused["error_type"] == "invalid_input" diff --git a/tests/solidworks_mcp/adapters/solidworks/runout_fakes.py b/tests/solidworks_mcp/adapters/solidworks/runout_fakes.py new file mode 100644 index 00000000..f1a8fb72 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/runout_fakes.py @@ -0,0 +1,119 @@ +"""Fake COM objects for a thread runout, shaped like SolidWorks 2026's. + +The probe of 2026-11-28 (design.md of the modelled-threads change): an M6 +thread 12 mm down a 6 mm rod whose end edge is at y = 25 mm; the Thread +feature's planar faces are its start (y 24.1 to 25) and its end (y 12.1 to +13), each 0.3 mm² with its normal along z. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + + +class Face: + """A face of the Thread feature.""" + + def __init__(self, box_mm: list[float], plane: bool = True) -> None: + self.box = [v / 1000 for v in box_mm] + self.plane = plane + self.Normal = (0.0, 0.0, 1.0) + self.selected_with: Any = None + + def GetSurface(self) -> Any: + return SimpleNamespace(IsPlane=lambda: self.plane) + + def GetBox(self) -> list[float]: + return self.box + + def Select4(self, append: bool, data: Any) -> bool: + self.selected_with = data.Mark + return True + + +#: The probe's faces: the helical one, the start, the end. +START = Face([-3.0, 24.125, 0.0, -2.459, 25.0, 0.0]) +END = Face([-3.0, 12.125, 0.0, -2.459, 13.0, 0.0]) + + +def thread(faces: list[Face] | None = None) -> Any: + """A Thread feature with the probe's faces.""" + if faces is None: + faces = [Face([-3, 12, -3, 3, 25, 3], plane=False), START, END] + return SimpleNamespace(Name="Thread1", GetFaces=lambda: faces) + + +class Sketches: + """``ISketchManager``: records what is drawn.""" + + def __init__(self) -> None: + self.calls: list[tuple[str, tuple[float, ...]]] = [] + self.AddToDB = False + self.ActiveSketch = SimpleNamespace(ModelToSketchTransform="model-to-sketch") + + def _record(self, name: str) -> Any: + def call(*args: Any) -> bool: + self.calls.append((name, args)) + return True + + return call + + def __getattr__(self, name: str) -> Any: + if name.startswith(("Insert", "Create")): + return self._record(name) + raise AttributeError(name) + + +class Model: + """A part with a threaded rod; the runout's feature is made or not.""" + + def __init__(self, made: bool = True, volumes: list[float] | None = None) -> None: + self.made = made + self.volumes = [100.0, 99.0] if volumes is None else list(volumes) + self.SketchManager = Sketches() + self.picked: list[tuple[str, str, int]] = [] + self.SelectionManager = SimpleNamespace( + CreateSelectData=lambda: SimpleNamespace(Mark=0) + ) + self.Extension = SimpleNamespace( + SelectByID2=self._select, CreateMassProperty=self._mass + ) + self.FeatureManager = SimpleNamespace( + InsertCutSwept5=lambda *a: ( + SimpleNamespace(Name="Cut-Sweep1") if self.made else None + ), + FeatureRevolve2=lambda *a: ( + SimpleNamespace(Name="Cut-Revolve1") if self.made else None + ), + ) + + def _select(self, name: str, kind: str, *rest: Any) -> bool: + self.picked.append((name, kind, rest[4])) + return True + + def _mass(self) -> Any: + return SimpleNamespace(Volume=self.volumes.pop(0) / 1e9) + + def FeatureByPositionReverse(self, index: int) -> Any: + return SimpleNamespace(Name="Sketch9") + + def ClearSelection2(self, everything: bool) -> None: + return None + + +def math_app() -> Any: + """``ISldWorks`` whose sketch transform leaves points where they are.""" + + def point(array: Any) -> Any: + values = list(getattr(array, "value", array)) + return SimpleNamespace( + MultiplyTransform=lambda xf: SimpleNamespace(ArrayData=values) + ) + + return SimpleNamespace(GetMathUtility=lambda: SimpleNamespace(CreatePoint=point)) + + +#: The rod's end edge: centre at y = 25 mm, axis along -y (as SolidWorks +#: may give it), radius 3 mm. +START_AXIS = ([0.0, 0.025, 0.0], [0.0, -1.0, 0.0]) diff --git a/tests/solidworks_mcp/adapters/solidworks/test_thread_runout.py b/tests/solidworks_mcp/adapters/solidworks/test_thread_runout.py new file mode 100644 index 00000000..db530e87 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_thread_runout.py @@ -0,0 +1,187 @@ +"""A thread's runout on fake COM objects shaped like SolidWorks 2026's. + +Spec: tools/threads, "The thread's runout, modelled". The calls are the ones +the probe of 2026-11-28 measured (design.md of the modelled-threads change). +""" + +from __future__ import annotations + +import math +from types import SimpleNamespace +from typing import Any + +import pytest + +from solidworks_mcp.adapters import runout_rules, sw_type_info +from solidworks_mcp.adapters.solidworks import thread_runout +from solidworks_mcp.exceptions import InputRefused +from tests.solidworks_mcp.adapters.solidworks import runout_fakes as fakes + + +class _Harness(thread_runout.SolidWorksThreadRunoutMixin): + def __init__(self, model: Any) -> None: + self.currentModel = model + self.swApp = fakes.math_app() + + def _attempt(self, operation: Any, default: Any = None) -> Any: + try: + return operation() + except Exception: + return default + + +@pytest.fixture(autouse=True) +def _no_flagging(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sw_type_info, "flagged", lambda obj, *_: obj) + monkeypatch.setattr(thread_runout, "entity_name", lambda adapter, name: name) + + +@pytest.mark.parametrize( + ("centre", "axis", "plane"), + [ + ([0, 0.025, 0], [0, -1, 0], "Front"), + ([0, 0, 0.01], [1, 0, 0], "Top"), + ([0, 0.01, 0.02], [0, 0, 1], "Right"), + ], +) +def test_the_main_plane_that_holds_the_axis( + centre: list[float], axis: list[float], plane: str +) -> None: + name, radial = thread_runout.main_plane(centre, axis) + + assert name == plane + assert sum(r * a for r, a in zip(radial, axis, strict=True)) == pytest.approx(0) + + +def test_an_axis_no_main_plane_holds_is_refused() -> None: + with pytest.raises(InputRefused, match="none of them holds"): + thread_runout.main_plane([0.01, 0.01, 0.01], [0, 1, 0]) + + +def test_the_start_edge_gives_the_axis() -> None: + curve = SimpleNamespace(CircleParams=(0, 0.025, 0, 0, -2, 0, 0.003)) + edge = SimpleNamespace(GetCurve=lambda: curve) + + centre, axis = _Harness(fakes.Model())._thread_axis(edge) + + assert centre == [0, 0.025, 0] and axis == [0, -1, 0] + + +@pytest.mark.parametrize("sign", [1, -1]) +def test_the_end_face_is_the_one_farthest_along(sign: int) -> None: + centre, axis = fakes.START_AXIS + + face, toward = _Harness(fakes.Model())._end_face( + fakes.thread(), centre, [sign * c for c in axis] + ) + + assert face is fakes.END + assert toward == [0.0, -1.0, 0.0] + + +def test_a_thread_without_a_flat_end_is_refused() -> None: + with pytest.raises(RuntimeError, match="no planar end face"): + _Harness(fakes.Model())._end_face(fakes.thread([]), *fakes.START_AXIS) + + +def test_the_volume_now_unread_is_none() -> None: + model = fakes.Model(volumes=[]) + + assert _Harness(model)._volume_now() is None + + +def test_an_external_fade_sweeps_straight_along_the_helix_tangent() -> None: + model = fakes.Model() + + made = _Harness(model)._fade(fakes.thread(), fakes.START_AXIS, 1.0, "external", 6.0) + + assert (made["style"], made["method"]) == ("fade", "tangent") + assert made["length_mm"] == 1.72 and made["path_mm"] == 6.0 + assert made["basis"] == runout_rules.TANGENT_BASIS + assert made["features"] == ["Sketch9", "Cut-Sweep1"] + assert fakes.END.selected_with == 1 + assert ("Sketch9", "SKETCH", 4) in model.picked + drawn = [name for name, _ in model.SketchManager.calls] + assert "Create3PointArc" not in drawn + line = next( + args for name, args in model.SketchManager.calls if name == "CreateLine" + ) + start, end = line[:3], line[3:6] + # From the end face's middle, the rod's diameter down the groove (-z): + # a straight line, no turn away from the axis. + assert start[0] == pytest.approx(-0.0027295) + assert math.dist(start, end) == pytest.approx(0.006) + assert end[2] < start[2] + + +def test_an_internal_fade_turns_along_an_arc_towards_the_axis() -> None: + model = fakes.Model() + + made = _Harness(model)._fade(fakes.thread(), fakes.START_AXIS, 1.0, "internal", 6.0) + + assert (made["method"], made["length_mm"]) == ("arc", 2.5) + arc = next( + args for name, args in model.SketchManager.calls if name == "Create3PointArc" + ) + start, end = arc[:3], arc[3:6] + assert start[0] == pytest.approx(-0.0027295) + assert end[2] < start[2] + assert end[0] > start[0] # towards the axis (+x from this face) + + +def test_a_fade_solidworks_does_not_build_is_reported() -> None: + made = _Harness(fakes.Model(made=False))._fade( + fakes.thread(), fakes.START_AXIS, 1.0, "external", 6.0 + ) + + assert "made no fade" in made["error"] and made["features"] == ["Sketch9"] + + +def test_an_undercut_revolves_din_76_1_form_a() -> None: + model = fakes.Model() + cut = runout_rules.undercut(1.0, 6.0, "undercut_a") + + made = _Harness(model)._undercut(fakes.thread(), fakes.START_AXIS, cut, 6.0, 12) + + assert made["plane"] == "Front" and made["full_thread_mm"] == 8.5 + assert made["features"] == ["Sketch9", "Cut-Revolve1"] + assert ("Front", "PLANE", 0) in model.picked + drawn = [name for name, _ in model.SketchManager.calls] + assert drawn.count("CreateLine") == 5 + assert drawn.count("Create3PointArc") == 1 + assert drawn.count("CreateCenterLine") == 1 + # The shoulder side is 12 mm from the edge at y = 25: y = 13 mm. + first = next( + args for name, args in model.SketchManager.calls if name == "CreateLine" + ) + assert first[1] == pytest.approx(0.013) + + +def test_an_undercut_solidworks_does_not_build_is_reported() -> None: + cut = runout_rules.undercut(1.0, 6.0, "undercut_b") + + made = _Harness(fakes.Model(made=False))._undercut( + fakes.thread(), fakes.START_AXIS, cut, 6.0, 12 + ) + + assert "made no undercut" in made["error"] + + +def test_a_lead_in_revolves_a_45_degree_triangle_at_the_start() -> None: + model = fakes.Model() + lead = runout_rules.lead_in(1.0, 6.0) + + made = _Harness(model)._lead_in(fakes.START_AXIS, lead, 6.0) + + assert made["plane"] == "Front" and made["end_diameter_mm"] == 4.7 + assert made["features"] == ["Sketch9", "Cut-Revolve1"] + drawn = [name for name, _ in model.SketchManager.calls] + assert drawn.count("CreateLine") == 3 and "Create3PointArc" not in drawn + + +def test_a_lead_in_solidworks_does_not_build_is_reported() -> None: + lead = runout_rules.lead_in(1.0, 6.0) + + made = _Harness(fakes.Model(made=False))._lead_in(fakes.START_AXIS, lead, 6.0) + + assert "made no lead-in" in made["error"] and made["features"] == ["Sketch9"] diff --git a/tests/solidworks_mcp/adapters/solidworks/test_threads.py b/tests/solidworks_mcp/adapters/solidworks/test_threads.py new file mode 100644 index 00000000..f6d6171e --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_threads.py @@ -0,0 +1,374 @@ +"""Modelled threads on fake COM objects shaped like SolidWorks 2026's (queue item 43). + +Spec: tools/threads. The calls are the ones the probe of 2026-11-28 measured +(design.md of the modelled-threads change). +""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from solidworks_mcp.adapters import sw_type_info +from solidworks_mcp.adapters.base import ( + AdapterResult, + AdapterResultStatus, + ThreadParameters, +) +from solidworks_mcp.adapters.solidworks import threads + +METRIC = ["M6x1.0", "M8x1.25", "M8x1.0"] + + +class _Curve: + def __init__(self, radius_m: float | None) -> None: + self.radius = radius_m + + def IsCircle(self) -> bool: + return self.radius is not None + + @property + def CircleParams(self) -> Any: + return (0, 0, 0, 0, 1, 0, self.radius) if self.radius else None + + +class _Model: + def __init__(self, radius_m: float | None = 0.003, made: bool = True) -> None: + self.edge = SimpleNamespace(GetCurve=lambda: _Curve(radius_m)) + self.selected: Any = None + self.data = SimpleNamespace(InitializeThreadData=lambda: None) + self.made = made + self.Extension = SimpleNamespace(SelectByID2=self._select) + self.SelectionManager = SimpleNamespace( + GetSelectedObject6=lambda index, mark: self.selected + ) + self.FeatureManager = SimpleNamespace( + CreateDefinition=lambda kind: self.data, + CreateFeature=lambda data: ( + SimpleNamespace(Name="Thread1") if self.made else None + ), + ) + + def _select( + self, name: str, kind: str, x: float, y: float, z: float, *rest: Any + ) -> bool: + self.selected = ( + self.edge if (round(x, 6), round(y, 6)) == (0.003, 0.025) else None + ) + return self.selected is not None + + def ForceRebuild3(self, top_only: bool) -> bool: + return True + + def ClearSelection2(self, everything: bool) -> None: + return None + + +class _Harness(threads.SolidWorksThreadsMixin): + def __init__(self, model: Any, folder: str, names: Any = METRIC) -> None: + self.currentModel = model + self.swApp = SimpleNamespace( + GetUserPreferenceStringValue=lambda pref: folder, + GetConfigurationNames=lambda path: names, + ) + + def _attempt(self, operation: Any, default: Any = None) -> Any: + try: + return operation() + except Exception: + return default + + 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) + + async def _measured(self, operation: str, build: Any, direction: int = 0) -> Any: + assert direction == -1 + return self._handle_com_operation(operation, build) + + +@pytest.fixture +def folder(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> str: + """A profile folder holding the four profiles; no flagging; an ISO library.""" + for name in ("Metric Die", "Metric Tap", "Inch Die", "Inch Tap"): + (tmp_path / f"{name}.SLDLFP").write_text("") + monkeypatch.setattr(sw_type_info, "flagged", lambda obj, *_: obj) + library = SimpleNamespace( + size_rows=lambda standard, table: [ + {"size": "M6", "dimensions": {"pitch": 1.0}}, + {"size": "M8", "dimensions": {"pitch": 1.25}}, + ] + ) + monkeypatch.setattr(threads.hole_library, "find_library", lambda: library) + return f";{tmp_path}" + + +def _params(**change: Any) -> ThreadParameters: + values: dict[str, Any] = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12} + values.update(change) + return ThreadParameters(**values) + + +@pytest.mark.asyncio +async def test_metric_sizes_take_the_library_coarse_pitches(folder: str) -> None: + result = await _Harness(_Model(), folder).list_thread_sizes("metric") + + assert result.data["profile"] == "Metric Die" + assert [e["pitch_class"] for e in result.data["sizes"]] == [ + "coarse", + "coarse", + "fine", + ] + + +@pytest.mark.asyncio +async def test_inch_sizes_go_by_the_list(folder: str) -> None: + result = await _Harness(_Model(), folder, ["0.2500-20"]).list_thread_sizes("inch") + + assert result.data["sizes"][0]["pitch_class"] == "only" + assert "25.4/TPI" in result.data["runout_basis"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("standard", "setting", "names", "words"), + [ + ("din", None, METRIC, "standard must be"), + ("metric", "", METRIC, "names no thread profile 'Metric Die'"), + ("metric", None, None, "read no sizes"), + ], +) +async def test_size_failures( + folder: str, standard: str, setting: str | None, names: Any, words: str +) -> None: + harness = _Harness(_Model(), folder if setting is None else setting, names) + + result = await harness.list_thread_sizes(standard) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_an_external_thread(folder: str) -> None: + model = _Model() + + result = await _Harness(model, folder).create_thread(_params(hand="left")) + + assert result.data["name"] == "Thread1" + assert result.data["edge_diameter_mm"] == 6.0 + assert result.data["turns"] == 12 + data = model.data + assert (data.Type, data.Size, data.ThreadMethod, data.EndCondition) == ( + "Metric Die", + "M6x1.0", + 0, + 0, + ) + assert data.BlindDepth == pytest.approx(0.012) + assert data.RightHanded is False + # Two pitches outside the rod's end, the length still from the edge. + assert (data.Offset, data.ReverseOffset, data.MaintainThreadLength) == ( + True, + True, + True, + ) + assert data.OffsetDistance == pytest.approx(0.002) + assert data.Edge is model.edge + + +@pytest.mark.asyncio +async def test_an_internal_thread_uses_the_tap(folder: str) -> None: + model = _Model(radius_m=0.0025) + model.Extension = SimpleNamespace( + SelectByID2=lambda *args: setattr(model, "selected", model.edge) or True + ) + + result = await _Harness(model, folder).create_thread(_params(kind="internal")) + + assert result.data["profile"] == "Metric Tap" + assert model.data.Type == "Metric Tap" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("model", "params", "words"), + [ + (_Model(), {"size": "M7x1.0"}, "No thread size"), + (_Model(), {"edge_point": [9, 9, 9]}, "No edge at"), + (_Model(radius_m=None), {}, "is not a circle"), + (_Model(radius_m=0.005), {}, "wants a rod of about 6 mm"), + (_Model(made=False), {}, "SolidWorks made no thread"), + (_Model(), {"length": -1}, "length must be greater than 0"), + ], +) +async def test_thread_failures( + folder: str, model: Any, params: dict[str, Any], words: str +) -> None: + result = await _Harness(model, folder).create_thread(_params(**params)) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_no_document(folder: str) -> None: + result = await _Harness(None, folder).create_thread(_params()) + + assert result.error == "No active model" + + +class _RunoutHarness(_Harness): + """``create_thread`` with the runout's COM steps stubbed and recorded.""" + + def __init__(self, model: Any, folder: str, made: bool = True) -> None: + super().__init__(model, folder) + self.made = made + self.lead_made = True + self.volumes: list[float | None] = [100.0, 98.5, 98.5, 98.0] + self.calls: list[tuple[Any, ...]] = [] + self.deleted: list[str] = [] + + def _volume_now(self) -> float | None: + return self.volumes.pop(0) + + def _fade(self, *args: Any) -> dict[str, Any]: + self.calls.append(("fade", *args[1:])) + if not self.made: + return {"error": "SolidWorks made no fade: x.", "features": ["3DSketch1"]} + return {"style": "fade", "features": ["3DSketch1", "Cut-Sweep1"]} + + def _undercut(self, *args: Any) -> dict[str, Any]: + self.calls.append(("undercut", *args[1:])) + return {"style": "undercut_a", "features": ["Sketch2", "Cut-Revolve1"]} + + def _end_face(self, thread: Any, centre: Any, axis: Any) -> tuple[Any, Any]: + return None, [0, -1, 0] + + def _lead_in(self, *args: Any) -> dict[str, Any]: + self.calls.append(("lead_in", *args)) + if not self.lead_made: + return {"error": "SolidWorks made no lead-in: x.", "features": ["Sketch3"]} + return {"end_diameter_mm": 4.7, "features": ["Sketch3", "Cut-Revolve2"]} + + async def delete_feature(self, name: str) -> None: + self.deleted.append(name) + + +@pytest.mark.asyncio +async def test_a_faded_thread_reports_its_runout(folder: str) -> None: + harness = _RunoutHarness(_Model(), folder) + + result = await harness.create_thread(_params(runout="fade")) + + assert result.data["runout"]["volume_change"] == pytest.approx(-1.5) + kind, start_axis, pitch, *_ = harness.calls[0] + assert (kind, start_axis, pitch) == ("fade", ([0, 0, 0], [0, 1, 0]), 1.0) + + +@pytest.mark.asyncio +async def test_an_undercut_thread_gets_din_76_1_dimensions(folder: str) -> None: + harness = _RunoutHarness(_Model(), folder) + harness.volumes = [None, None] + + result = await harness.create_thread(_params(runout="undercut_a")) + + assert "volume_change" not in result.data["runout"] + cut = harness.calls[0][2] + assert (cut.diameter_mm, cut.width_mm, cut.radius_mm) == (4.4, 3.5, 0.5) + + +@pytest.mark.asyncio +async def test_a_runout_solidworks_does_not_build_removes_the_thread( + folder: str, +) -> None: + harness = _RunoutHarness(_Model(), folder, made=False) + + result = await harness.create_thread(_params(runout="fade")) + + assert harness.deleted == ["3DSketch1", "Thread1"] + assert result.error == "SolidWorks made no fade: x. The thread was removed again." + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("params", "axis", "words"), + [ + ({"runout": "undercut_a", "length": 3}, None, "3.5 mm wide"), + ( + {"runout": "undercut_b"}, + ([0.01, 0.01, 0.01], [0, 1, 0]), + "none of them holds", + ), + ({"runout": "undercut_a", "kind": "internal"}, None, "external metric"), + ({"runout": "taper"}, None, "runout must be one of"), + ], +) +async def test_an_undercut_that_cannot_be_built_builds_nothing( + folder: str, params: dict[str, Any], axis: Any, words: str +) -> None: + model = _Model() + harness = _RunoutHarness(model, folder) + if axis is not None: + harness._thread_axis = lambda edge: axis # type: ignore[method-assign] + + result = await harness.create_thread(_params(**params)) + + assert words in str(result.error) + assert not hasattr(model.data, "Edge") + + +@pytest.mark.asyncio +async def test_a_lead_in_is_made_last_pointing_into_the_thread(folder: str) -> None: + harness = _RunoutHarness(_Model(), folder) + + result = await harness.create_thread(_params(runout="undercut_a", lead_in=True)) + + assert [call[0] for call in harness.calls] == ["undercut", "lead_in"] + _, inward, lead, diameter = harness.calls[1] + assert inward == ([0, 0, 0], [0, -1, 0]) + assert (lead.end_diameter_mm, diameter) == (4.7, 6.0) + assert result.data["lead_in"]["volume_change"] == pytest.approx(-0.5) + + +@pytest.mark.asyncio +async def test_a_lead_in_solidworks_does_not_build_removes_everything( + folder: str, +) -> None: + harness = _RunoutHarness(_Model(), folder) + harness.lead_made = False + + result = await harness.create_thread(_params(runout="undercut_a", lead_in=True)) + + assert harness.deleted == ["Sketch3", "Cut-Revolve1", "Sketch2", "Thread1"] + assert result.error == ( + "SolidWorks made no lead-in: x. The thread was removed again." + ) + + +@pytest.mark.asyncio +async def test_no_lead_in_after_a_failed_runout(folder: str) -> None: + harness = _RunoutHarness(_Model(), folder, made=False) + + await harness.create_thread(_params(runout="fade", lead_in=True)) + + assert [call[0] for call in harness.calls] == ["fade"] + assert harness.deleted == ["3DSketch1", "Thread1"] + + +@pytest.mark.asyncio +async def test_a_lead_in_alone_needs_a_main_plane(folder: str) -> None: + model = _Model() + harness = _RunoutHarness(model, folder) + harness._thread_axis = lambda edge: ([0.01, 0.01, 0.01], [0, 1, 0]) # type: ignore[method-assign] + + result = await harness.create_thread(_params(lead_in=True)) + + assert "none of them holds" in str(result.error) + assert not hasattr(model.data, "Edge") diff --git a/tests/solidworks_mcp/adapters/test_base_threads.py b/tests/solidworks_mcp/adapters/test_base_threads.py new file mode 100644 index 00000000..172bdc77 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_base_threads.py @@ -0,0 +1,20 @@ +"""The thread methods (queue item 43) on the base adapter: none is implemented there.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from .test_base_part_features import _bare +from .thread_calls import CALLS, IDS + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_thread_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_threads.py b/tests/solidworks_mcp/adapters/test_circuit_breaker_threads.py new file mode 100644 index 00000000..ac560839 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_circuit_breaker_threads.py @@ -0,0 +1,25 @@ +"""The thread methods (queue item 43) 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 .thread_calls import CALLS, IDS, recorder + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_thread_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_threads.py b/tests/solidworks_mcp/adapters/test_connection_pool_threads.py new file mode 100644 index 00000000..e06cf813 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_connection_pool_threads.py @@ -0,0 +1,28 @@ +"""The thread methods (queue item 43) 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 .thread_calls import CALLS, IDS, recorder + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("name", "args", "kwargs"), CALLS, ids=IDS) +async def test_each_thread_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_threads.py b/tests/solidworks_mcp/adapters/test_mock_threads.py new file mode 100644 index 00000000..e1e0d8f1 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_mock_threads.py @@ -0,0 +1,166 @@ +"""The mock adapter's modelled threads (queue item 43). Spec: tools/threads.""" + +from __future__ import annotations + +import math + +import pytest + +from solidworks_mcp.adapters.base import ExtrusionParameters, ThreadParameters +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter + + +async def _part(rod: bool) -> MockSolidWorksAdapter: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + if rod: + await adapter.create_sketch("Top") + await adapter.add_circle(0, 0, 3) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=25)) + return adapter + + +@pytest.mark.asyncio +async def test_sizes() -> None: + adapter = await _part(False) + + metric = await adapter.list_thread_sizes("metric") + inch = await adapter.list_thread_sizes("inch") + other = await adapter.list_thread_sizes("din") + + assert {e["size"]: e["pitch_class"] for e in metric.data["sizes"]}[ + "M8x1.0" + ] == "fine" + assert inch.data["profile"] == "Inch Die" + assert "standard must be" in str(other.error) + + +@pytest.mark.asyncio +async def test_a_thread_removes_its_groove() -> None: + adapter = await _part(True) + + result = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12) + ) + + groove = math.pi * 6 * 0.5413 / 2 * 12 + assert result.data["volume_change"] == pytest.approx(-groove) + assert result.data["turns"] == 12 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("rod", "params", "words"), + [ + (True, {"size": "M7x1.0"}, "No thread size"), + (True, {"hand": "both"}, "hand must be"), + (False, {}, "the part has no body"), + ], +) +async def test_refusals(rod: bool, params: dict, words: str) -> None: + adapter = await _part(rod) + values = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, **params} + + result = await adapter.create_thread(ThreadParameters(**values)) + + assert words in str(result.error) + + +@pytest.mark.asyncio +async def test_no_document() -> None: + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + + result = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12) + ) + + assert result.error == "No active model" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("runout", "style", "key"), + [("fade", "fade", "path_mm"), ("undercut_b", "undercut_b", "width_mm")], +) +async def test_a_runout_is_reported_and_removes_more( + runout: str, style: str, key: str +) -> None: + adapter = await _part(True) + plain = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12) + ) + + ended = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12, runout=runout) + ) + + assert plain.data["runout"] is None + assert ended.data["runout"]["style"] == style and key in ended.data["runout"] + assert ended.data["volume_change"] < plain.data["volume_change"] + + +@pytest.mark.asyncio +async def test_an_undercut_wider_than_the_thread_is_refused() -> None: + adapter = await _part(True) + + result = await adapter.create_thread( + ThreadParameters( + size="M6x1.0", edge_point=[3, 25, 0], length=2, runout="undercut_a" + ) + ) + + assert "3.5 mm wide" in str(result.error) + + +@pytest.mark.asyncio +async def test_a_lead_in_is_reported_and_removes_more() -> None: + adapter = await _part(True) + plain = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12) + ) + + led = await adapter.create_thread( + ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12, lead_in=True) + ) + + assert plain.data["lead_in"] is None + assert led.data["lead_in"]["end_diameter_mm"] == 4.7 + assert led.data["volume_change"] < plain.data["volume_change"] + + +@pytest.mark.asyncio +async def test_a_lead_in_in_a_tapped_hole_is_refused() -> None: + adapter = await _part(True) + + result = await adapter.create_thread( + ThreadParameters( + kind="internal", + size="M6x1.0", + edge_point=[2.5, 15, 0], + length=10, + lead_in=True, + ) + ) + + assert "a countersink" in str(result.error) + + +@pytest.mark.asyncio +async def test_a_faded_tapped_hole_reports_the_arc() -> None: + adapter = await _part(True) + + result = await adapter.create_thread( + ThreadParameters( + kind="internal", + size="M6x1.0", + edge_point=[2.5, 15, 0], + length=10, + runout="fade", + ) + ) + + assert result.data["runout"]["method"] == "arc" + assert result.data["runout"]["length_mm"] == 2.5 diff --git a/tests/solidworks_mcp/adapters/test_runout_rules.py b/tests/solidworks_mcp/adapters/test_runout_rules.py new file mode 100644 index 00000000..cdf2c3ae --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_runout_rules.py @@ -0,0 +1,145 @@ +"""The rules for a modelled thread runout. Spec: tools/threads.""" + +from __future__ import annotations + +import math +from typing import Any + +import pytest + +from solidworks_mcp.adapters import runout_rules as rules +from solidworks_mcp.adapters.base import ThreadParameters +from solidworks_mcp.exceptions import InputRefused + + +def test_the_table_is_din_76_1_for_m6_and_m10() -> None: + m6 = rules.undercut(1.0, 6.0, "undercut_a") + m10 = rules.undercut(1.5, 10.0, "undercut_b") + + assert (m6.diameter_mm, m6.width_mm, m6.g1_mm, m6.radius_mm) == (4.4, 3.5, 2.1, 0.5) + assert (m10.diameter_mm, m10.width_mm, m10.g1_mm) == (7.7, 3.8, 1.8) + + +def test_the_bottom_is_the_width_less_the_30_degree_flank() -> None: + cut = rules.undercut(1.0, 6.0, "undercut_a") + + assert cut.bottom_mm == pytest.approx(3.5 - 0.8 * math.sqrt(3), abs=1e-4) + + +def test_the_bottom_is_never_shorter_than_g1() -> None: + cut = rules.undercut(0.2, 1.0, "undercut_b") + + assert cut.bottom_mm == cut.g1_mm + + +def test_a_pitch_the_table_lacks_is_refused() -> None: + with pytest.raises(InputRefused, match="no undercut for a 1.27 mm pitch"): + rules.undercut(1.27, 6.35, "undercut_a") + + +@pytest.mark.parametrize(("pitch", "length"), [(1.0, 2.5), (1.27, 3.17)]) +def test_the_fade_runs_over_x1_or_2_5p(pitch: float, length: float) -> None: + arc = rules.fade_arc(pitch) + + assert arc["length_mm"] == length + rise, radius = arc["rise_mm"], arc["radius_mm"] + assert radius - math.sqrt(radius**2 - length**2) == pytest.approx(rise, abs=1e-3) + + +def test_the_profile_closes_from_the_shoulder_to_past_the_flank() -> None: + cut = rules.undercut(1.0, 6.0, "undercut_a") + + points, centre = rules.undercut_profile(cut, 6.0) + + assert points[0] == (3.0, 0.0) + assert points[2] == (2.2, 0.5) and centre == (2.7, 0.5) + assert points[4] == (3.0, 3.5) + assert points[5][0] == 3.0 + rules.OVERSHOOT_MM + + +def _params(**change: Any) -> ThreadParameters: + values: dict[str, Any] = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12} + values.update(change) + return ThreadParameters(**values) + + +@pytest.mark.parametrize( + ("change", "words"), + [ + ({"runout": "taper"}, "runout must be one of"), + ({"runout": "undercut_a", "kind": "internal"}, "external metric"), + ({"runout": "undercut_b", "standard": "inch"}, "external metric"), + ({"lead_in": True, "kind": "internal"}, "a countersink"), + ], +) +def test_runouts_that_cannot_be_built(change: dict[str, Any], words: str) -> None: + with pytest.raises(InputRefused, match=words): + rules.check_runout(_params(**change)) + + +@pytest.mark.parametrize("runout", ["none", "fade", "undercut_a"]) +def test_runouts_that_can(runout: str) -> None: + rules.check_runout(_params(runout=runout)) + + +def test_an_undercut_as_wide_as_the_thread_is_refused() -> None: + cut = rules.undercut(1.0, 6.0, "undercut_a") + + rules.check_width(cut, 3.6) + with pytest.raises(InputRefused, match="3.5 mm wide"): + rules.check_width(cut, 3.5) + + +def test_the_reply_names_the_form_and_its_basis() -> None: + reply = rules.undercut_reply(rules.undercut(1.0, 6.0, "undercut_b")) + + assert reply["style"] == "undercut_b" and reply["basis"] == rules.BASIS + assert reply["flank_deg"] == 30.0 + + +@pytest.mark.parametrize( + ("pitch", "diameter", "end", "length"), + [(1.0, 6.0, 4.7, 0.65), (1.27, 6.35, 4.7, 0.825), (1.25, 8.0, 6.4, 0.8)], +) +def test_the_lead_in_ends_just_under_the_minor_diameter( + pitch: float, diameter: float, end: float, length: float +) -> None: + lead = rules.lead_in(pitch, diameter) + + assert (lead.end_diameter_mm, lead.length_mm) == (end, length) + assert lead.end_diameter_mm <= diameter - rules.MINOR_FACTOR * pitch + + +def test_the_lead_in_outline_is_45_degrees_through_both_diameters() -> None: + lead = rules.lead_in(1.0, 6.0) + + (r0, a0), (r1, a1), (r2, a2) = rules.lead_in_profile(lead, 6.0) + + assert r1 == r2 == 3.5 and a0 == a1 == -0.5 + assert (a2 - a0) == pytest.approx(r2 - r0) # 45 degrees + # The slope passes through the end diameter at the face (along 0). + assert r0 + 0.5 == pytest.approx(lead.end_diameter_mm / 2) + + +def test_the_lead_in_reply_names_its_basis() -> None: + reply = rules.lead_in_reply(rules.lead_in(1.0, 6.0)) + + assert reply == { + "basis": rules.LEAD_IN_BASIS, + "angle_deg": 45.0, + "end_diameter_mm": 4.7, + "length_mm": 0.65, + } + + +@pytest.mark.parametrize( + ("pitch", "diameter", "length"), [(1.0, 6.0, 1.72), (4.0, 39.0, 8.93)] +) +def test_a_tangent_fade_runs_out_where_the_root_leaves_the_rod( + pitch: float, diameter: float, length: float +) -> None: + fade = rules.fade_tangent(pitch, diameter) + + assert fade == {"method": "tangent", "length_mm": length, "path_mm": diameter} + root = diameter / 2 - rules.BASIC_DEPTH * pitch + assert math.hypot(root, length) == pytest.approx(diameter / 2, abs=0.01) diff --git a/tests/solidworks_mcp/adapters/test_thread_rules.py b/tests/solidworks_mcp/adapters/test_thread_rules.py new file mode 100644 index 00000000..27ff5c11 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_thread_rules.py @@ -0,0 +1,148 @@ +"""The rules for modelled threads (queue item 43). Spec: tools/threads.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from solidworks_mcp.adapters import thread_rules as rules +from solidworks_mcp.adapters.base import ThreadParameters +from solidworks_mcp.exceptions import InputRefused + + +@pytest.mark.parametrize( + ("name", "diameter", "pitch", "tpi"), + [ + ("M6x1.0", 6.0, 1.0, None), + ("m1.2x0.25", 1.2, 0.25, None), + ("#10-32", 4.826, 0.7937, 32.0), + ("0.2500-20", 6.35, 1.27, 20.0), + ("1/4-20", 6.35, 1.27, 20.0), + ("1-1/2-6", 38.1, 4.2333, 6.0), + ("2.0000-4.5", 50.8, 5.6444, 4.5), + ], +) +def test_sizes_parse(name: str, diameter: float, pitch: float, tpi: Any) -> None: + size = rules.parse_size(name) + + assert size is not None + assert (size.diameter_mm, size.pitch_mm, size.tpi) == (diameter, pitch, tpi) + + +def test_a_name_in_another_form_is_none() -> None: + assert rules.parse_size("SP400-L-5") is None + + +@pytest.mark.parametrize( + ("diameter_in", "tpi", "label"), + [(0.25, 20, "1/4-20"), (1.5, 6, "1-1/2-6"), (2.0, 4.5, "2-4.5"), (0.2, 20, None)], +) +def test_inch_labels(diameter_in: float, tpi: float, label: str | None) -> None: + assert rules.inch_label(diameter_in, tpi) == label + + +def test_a_size_table_from_the_list_alone() -> None: + table = rules.size_table( + ["#0-80", "#1-64", "#1-72", "0.2500-20", "0.2500-28", "junk"] + ) + + assert [(e["size"], e["pitch_class"]) for e in table] == [ + ("#0-80", "only"), + ("#1-64", "coarse"), + ("#1-72", "fine"), + ("0.2500-20", "coarse"), + ("0.2500-28", "fine"), + ] + quarter = table[3] + assert quarter["also"] == "1/4-20" + assert quarter["tpi"] == 20.0 + assert "also" not in table[0] + assert quarter["runout_mm"] == {"normal": 3.17, "short": 1.59} + + +def test_known_coarse_pitches_decide() -> None: + table = rules.size_table( + ["M6x1.0", "M8x1.25", "M8x1.0", "M7x1.0"], {6.0: 1.0, 8.0: 1.25} + ) + + classes = {e["size"]: e["pitch_class"] for e in table} + + assert classes == { + "M6x1.0": "coarse", + "M7x1.0": "only", + "M8x1.25": "coarse", + "M8x1.0": "fine", + } + assert table[0]["basic_depth_mm"] == pytest.approx(0.5413) + + +def test_coarse_pitches_from_hole_rows() -> None: + rows = [ + {"size": "M6", "dimensions": {"pitch": 1.0}}, + {"size": "M8x1.0", "dimensions": {"pitch": 1.0}}, + {"size": "M10", "dimensions": {"pitch": "?"}}, + {"size": None, "dimensions": None}, + ] + + assert rules.coarse_from_hole_rows(rows) == {6.0: 1.0} + + +@pytest.mark.parametrize( + ("wanted", "found"), + [("m6X1.0", "M6x1.0"), ("1/4-20", "0.2500-20"), ("M6x1", "M6x1.0")], +) +def test_sizes_match(wanted: str, found: str) -> None: + assert rules.match_size(["M6x1.0", "M8x1.25", "0.2500-20"], wanted).size == found + + +@pytest.mark.parametrize( + ("wanted", "nearest"), + [("M7x1.0", "nearest: M6x1.0, M8x1.25"), ("bolt", "nearest: M6x1.0")], +) +def test_an_unknown_size_names_the_nearest(wanted: str, nearest: str) -> None: + with pytest.raises(InputRefused, match=nearest): + rules.match_size(["M6x1.0", "M8x1.25"], wanted) + + +def test_no_sizes_at_all() -> None: + with pytest.raises(InputRefused, match="nearest: none"): + rules.match_size([], "M6x1.0") + + +def test_the_diameter_check() -> None: + m6 = rules.ThreadSize("M6x1.0", 6.0, 1.0) + + rules.check_diameter(m6, "external", 6.0) + rules.check_diameter(m6, "internal", 5.0) + with pytest.raises(InputRefused, match="wants a rod of about 6 mm"): + rules.check_diameter(m6, "external", 10.0) + with pytest.raises( + InputRefused, match=r"wants a hole \(about the tap drill\) of about 5" + ): + rules.check_diameter(m6, "internal", 8.0) + + +def _params(**change: Any) -> ThreadParameters: + values: dict[str, Any] = {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12} + values.update(change) + return ThreadParameters(**values) + + +def test_good_inputs_pass() -> None: + rules.check_inputs(_params()) + + +@pytest.mark.parametrize( + ("change", "words"), + [ + ({"standard": "din"}, "standard must be"), + ({"kind": "male"}, "kind must be"), + ({"hand": "both"}, "hand must be"), + ({"edge_point": [1, 2]}, "edge_point must be"), + ({"length": 0}, "length must be greater than 0"), + ], +) +def test_bad_inputs_are_refused(change: dict[str, Any], words: str) -> None: + with pytest.raises(InputRefused, match=words): + rules.check_inputs(_params(**change)) diff --git a/tests/solidworks_mcp/adapters/thread_calls.py b/tests/solidworks_mcp/adapters/thread_calls.py new file mode 100644 index 00000000..d4fff193 --- /dev/null +++ b/tests/solidworks_mcp/adapters/thread_calls.py @@ -0,0 +1,25 @@ +"""One call of each adapter method queue item 43 adds, shared by the layer tests.""" + +from __future__ import annotations + +from typing import Any + +from solidworks_mcp.adapters.base import ThreadParameters + +from .body_calls import recorder_for + +CALLS: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [ + ("list_thread_sizes", ("metric",), {}), + ( + "create_thread", + (ThreadParameters(size="M6x1.0", edge_point=[3, 25, 0], length=12),), + {}, + ), +] + +IDS = [call[0] for call in CALLS] + + +def recorder() -> Any: + """A mock adapter whose thread methods record their arguments.""" + return recorder_for(IDS) diff --git a/tests/solidworks_mcp/tools/test_error_classifier.py b/tests/solidworks_mcp/tools/test_error_classifier.py index aef3b88e..d2958a1a 100644 --- a/tests/solidworks_mcp/tools/test_error_classifier.py +++ b/tests/solidworks_mcp/tools/test_error_classifier.py @@ -90,6 +90,19 @@ def classifier() -> ErrorClassifier: "feature_not_built", ), ("No body named 'Nope'. Bodies in the part: Block.", "invalid_input"), + ("No thread size 'M7x1.0' in the profile; nearest: M6x1.0", "invalid_input"), + ("No edge at [1, 2, 3] mm; give a point on the circular edge", "invalid_input"), + ("The edge at [1] mm is not a circle; a thread starts", "invalid_input"), + ( + "The edge is 6 mm across but M10x1.5 external wants a rod of about", + "invalid_input", + ), + ("hand must be 'right' or 'left'.", "invalid_input"), + ("length must be greater than 0 mm.", "invalid_input"), + ( + "SolidWorks made no thread (Metric Die M6x1.0 on the 6 mm edge).", + "feature_not_built", + ), ("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"), @@ -172,6 +185,16 @@ def classifier() -> ErrorClassifier: ("No entity found for 'Edge<9>'; check the name", "not_found"), ("No .sldmat libraries found in: C:/x", "not_found"), ("The active part has no sheet-metal body", "not_found"), + ( + "A lead-in chamfers an external thread's free end (ISO 4753); a " + "tapped hole's lead-in is a countersink at its opening.", + "invalid_input", + ), + ( + "SolidWorks made no lead-in: the revolved cut of Sketch3 failed. " + "The thread was removed again.", + "feature_not_built", + ), ], ) def test_known_messages_are_categorised( diff --git a/tests/solidworks_mcp/tools/test_threads.py b/tests/solidworks_mcp/tools/test_threads.py new file mode 100644 index 00000000..507d9533 --- /dev/null +++ b/tests/solidworks_mcp/tools/test_threads.py @@ -0,0 +1,108 @@ +"""The thread tools on the mock adapter (queue item 43). Spec: tools/threads.""" + +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.threads import ( + CreateThreadInput, + ThreadSizesInput, + register_thread_tools, +) + + +async def _tools(adapter: Any) -> dict[str, Any]: + mcp = FastMCP("threads") + assert await register_thread_tools(mcp, adapter, {}) == 2 + return {t.name: t.fn for t in await mcp.list_tools()} + + +@pytest.fixture +async def rod() -> MockSolidWorksAdapter: + """A mock 6 mm rod, 25 mm long.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + await adapter.create_sketch("Top") + await adapter.add_circle(0, 0, 3) + await adapter.exit_sketch() + await adapter.create_extrusion(ExtrusionParameters(depth=25)) + return adapter + + +@pytest.mark.asyncio +async def test_list_sizes(rod: MockSolidWorksAdapter) -> None: + tools = await _tools(rod) + + metric = await tools["list_thread_sizes"]() + inch = await tools["list_thread_sizes"](ThreadSizesInput(standard="inch")) + + assert metric["message"] == "8 metric thread sizes" + assert inch["message"] == "5 inch thread sizes" + + +@pytest.mark.asyncio +async def test_cut_a_thread(rod: MockSolidWorksAdapter) -> None: + reply = await (await _tools(rod))["create_thread"]( + CreateThreadInput(size="M6x1.0", edge_point=[3, 25, 0], length=12) + ) + + assert reply["message"].startswith("Thread1: M6x1.0 external, 12 mm, -") + assert reply["thread"]["runout_mm"] == {"normal": 2.5, "short": 1.25} + + +@pytest.mark.asyncio +async def test_an_unknown_size_is_an_error_reply(rod: MockSolidWorksAdapter) -> None: + reply = await (await _tools(rod))["create_thread"]( + {"size": "M7x1.0", "edge_point": [3, 25, 0], "length": 12} + ) + + assert reply["status"] == "error" + assert reply["error_type"] == "invalid_input" + + +@pytest.mark.parametrize( + "values", + [ + {"size": "M6x1.0", "edge_point": [3, 25], "length": 12}, + {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 0}, + {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 5, "kind": "male"}, + ], +) +def test_inputs_are_strict(values: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + CreateThreadInput(**values) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("runout", "words"), + [("fade", "fading out over 1.72 mm"), ("undercut_a", "Form A undercut (dg 4.4")], +) +async def test_a_runout_is_named_in_the_message( + rod: MockSolidWorksAdapter, runout: str, words: str +) -> None: + tools = await _tools(rod) + + reply = await tools["create_thread"]( + {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "runout": runout} + ) + + assert words in reply["message"] + + +@pytest.mark.asyncio +async def test_a_lead_in_is_named_in_the_message(rod: MockSolidWorksAdapter) -> None: + tools = await _tools(rod) + + reply = await tools["create_thread"]( + {"size": "M6x1.0", "edge_point": [3, 25, 0], "length": 12, "lead_in": True} + ) + + assert "its start chamfered 45° to 4.7 mm" in reply["message"]