From f2ee83d3f7c4abd07a760134d3c3f836a6ff372d Mon Sep 17 00:00:00 2001 From: Andrew Bartels Date: Fri, 20 Nov 2026 14:57:04 -0800 Subject: [PATCH 1/4] fix: add_fillet on SolidWorks 2024, drawing view scale and view_type, API index in the user folder (#255, #256, #257) --- CHANGELOG.md | 13 +++ docs/assets/progress/tool-list-size.md | 8 +- docs/user-guide/tool-catalog/drawing.md | 4 +- .../solidworks-2024-reports/.openspec.yaml | 2 + .../solidworks-2024-reports/proposal.md | 55 +++++++++++ .../specs/tools/api-help-lookup/spec.md | 17 ++++ .../specs/tools/drawing-view-scale/spec.md | 25 +++++ .../specs/tools/edge-treatment/spec.md | 11 +++ .../changes/solidworks-2024-reports/tasks.md | 21 +++++ .../adapters/solidworks/features.py | 94 +++++-------------- src/solidworks_mcp/adapters/solidworks/io.py | 35 +++++-- src/solidworks_mcp/tools/docs_discovery.py | 23 +++-- src/solidworks_mcp/tools/drawing.py | 17 +++- tests/conftest.py | 8 +- .../adapters/solidworks/test_features.py | 24 +++-- .../adapters/solidworks/test_io.py | 81 ++++++++++++++++ .../adapters/solidworks/test_sketch.py | 4 +- .../tools/test_docs_discovery.py | 39 ++++++++ tests/solidworks_mcp/tools/test_drawing.py | 11 +++ 19 files changed, 384 insertions(+), 108 deletions(-) create mode 100644 openspec/changes/solidworks-2024-reports/.openspec.yaml create mode 100644 openspec/changes/solidworks-2024-reports/proposal.md create mode 100644 openspec/changes/solidworks-2024-reports/specs/tools/api-help-lookup/spec.md create mode 100644 openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md create mode 100644 openspec/changes/solidworks-2024-reports/specs/tools/edge-treatment/spec.md create mode 100644 openspec/changes/solidworks-2024-reports/tasks.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 708fa134..06e34ae4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -228,6 +228,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`add_fillet` works on SolidWorks 2024** (#255): below 2025 it called + `IFeatureManager.FeatureFillet3` with 15 arguments where the method takes + 14, so every fillet failed with "Invalid number of parameters". Every + version now makes the call checked live on 2026. +- **`create_drawing_view` applies `scale`** (#256): the view kept the sheet's + scale and `scale_applied` was always false. A given scale is now the view's + own and is read back; left out, the view uses the sheet's scale. With no + `orientation`, a `view_type` such as `isometric` sets the view instead of + giving a front view. +- **API lookups work when the server starts in a read-only folder** (#257): + the index was saved relative to the working folder, which Claude Desktop + started through `uvx` can't write to. It is now saved in + `~/.solidworks_mcp/docs-index`; an index in the old folder is still read. - **`construction` is honoured on SolidWorks**: `add_line`, `add_circle` and `add_rectangle` accepted `construction` but drew normal geometry, while the reply said `"construction": true`. The tools now set it on the new diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index 43b3ebb5..e4e39547 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` | 151 | 245 KB | 62,704 | 100% | +| `all` | `list` | 151 | 245 KB | 62,759 | 100% | | `core` | `list` | 111 | 169 KB | 43,262 | 69% | -| `drawing` | `list` | 21 | 38 KB | 9,616 | 15% | +| `drawing` | `list` | 21 | 38 KB | 9,668 | 15% | | `automation` | `list` | 3 | 6 KB | 1,556 | 2% | | `vba` | `list` | 10 | 17 KB | 4,356 | 7% | -| `docs` | `list` | 6 | 15 KB | 3,914 | 6% | -| `core,drawing` | `list` | 132 | 207 KB | 52,877 | 84% | +| `docs` | `list` | 6 | 15 KB | 3,916 | 6% | +| `core,drawing` | `list` | 132 | 207 KB | 52,930 | 84% | | `all` | `search` | 4 | 4 KB | 908 | 1% | | `core` | `search` | 4 | 4 KB | 908 | 1% | diff --git a/docs/user-guide/tool-catalog/drawing.md b/docs/user-guide/tool-catalog/drawing.md index 28e39e93..acffd757 100644 --- a/docs/user-guide/tool-catalog/drawing.md +++ b/docs/user-guide/tool-catalog/drawing.md @@ -25,8 +25,8 @@ Place one named view of a part or assembly on the active drawing sheet. | `view_type` | `str` | ✅ | `` | Type of view (orthographic, isometric, section, detail) | | `position_x` | `float` | — | `100.0` | X position in drawing (mm) | | `position_y` | `float` | — | `200.0` | Y position in drawing (mm) | -| `scale` | `float` | — | `1.0` | View scale factor | -| `orientation` | `str` | — | `front` | View orientation (front, top, right, isometric) | +| `scale` | `float?` | — | `None` | The view's own scale, e.g. `0.5` for 1:2 (`UseSheetScale` off, `ScaleDecimal`, read back as `scale_applied`); left out, the sheet's scale (`set_sheet_scale`) | +| `orientation` | `str?` | — | `None` | View orientation (front, top, right, isometric); left out, a `view_type` that names one is used, else front | **Sample call:** diff --git a/openspec/changes/solidworks-2024-reports/.openspec.yaml b/openspec/changes/solidworks-2024-reports/.openspec.yaml new file mode 100644 index 00000000..4ee7b3f0 --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-20 diff --git a/openspec/changes/solidworks-2024-reports/proposal.md b/openspec/changes/solidworks-2024-reports/proposal.md new file mode 100644 index 00000000..d97d1e53 --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/proposal.md @@ -0,0 +1,55 @@ +## Why + +A user on SolidWorks 2024 SP5, installed with `uvx` and run from Claude +Desktop, reported three faults on 2026-11-20 (#255, #256, #257). Each is +ours, and each has gone unseen because every live run so far has been on +SolidWorks 2026 from a developer's checkout: + +- **#255** `add_fillet` always fails before 2025: below major version 33 it + calls `IFeatureManager.FeatureFillet3` with 15 arguments, radius first; the + type library's signature has 14, options first. That branch has never run. +- **#256** `create_drawing_view` never changes a view's scale: the view keeps + using the sheet scale (`UseSheetScale` is never turned off), and the reply's + `scale_applied` is always false because it tests `setattr`'s return value. + Also, `view_type` alone never sets the view, because the tool always sends + `orientation` (default `front`). +- **#257** every API lookup fails with `PermissionError` when the server's + working folder isn't writable (Claude Desktop through `uvx`): the index is + saved to a folder relative to it, `.generated/docs-index`. + +## What Changes + +- `add_fillet` uses `IModelDoc2.FeatureFillet3` (9 arguments) on every + SolidWorks version, the call checked live on 2026; the version check and + the broken branch go. +- `create_drawing_view` turns the view's `UseSheetScale` off, sets + `ScaleDecimal`, and reads it back for `scale_applied`. With no + `orientation`, a `view_type` that names a view (`top`, `isometric`, ...) + sets it. +- The API index is saved in the user's own folder (`~/.solidworks_mcp/ + docs-index`, beside the server's other data); the old relative folders are + still read, so an index built there keeps working. + +## Capabilities + +### New Capabilities + +- `tools/drawing-view-scale`: a view's own scale, applied and read back; + `view_type` as the orientation when none is given. + +### Modified Capabilities + +- `tools/edge-treatment`: a fillet works on every supported SolidWorks + version (an added requirement). +- `tools/api-help-lookup`: the index is saved in a user-writable folder (an + added requirement). + +## Impact + +- `adapters/solidworks/features.py` (`_add_fillet_impl`), + `adapters/solidworks/io.py` (`_place_view`), `tools/drawing.py` + (`CreateDrawingViewInput`), `tools/docs_discovery.py` (`_INDEX_DIRS`); + tests beside each; the catalog pages; CHANGELOG. +- No public reply on the issues until the user decides (the user's + instruction, 2026-11-20). Each fix is checked live on 2026; 2024 can only + be confirmed by the reporter. diff --git a/openspec/changes/solidworks-2024-reports/specs/tools/api-help-lookup/spec.md b/openspec/changes/solidworks-2024-reports/specs/tools/api-help-lookup/spec.md new file mode 100644 index 00000000..5e254901 --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/specs/tools/api-help-lookup/spec.md @@ -0,0 +1,17 @@ +## ADDED Requirements + +### Requirement: The index is saved in a folder the user can write to +The API lookups SHALL save a built index in the user's own data folder +(`~/.solidworks_mcp/docs-index`), not a folder relative to the server's +working directory, and SHALL still read an index saved in the old relative +folders. + +#### Scenario: Started by Claude Desktop through uvx +- **WHEN** the server's working folder is not writable and + `lookup_api_method` is called +- **THEN** the index is built and saved under `~/.solidworks_mcp/docs-index` + and the lookup answers + +#### Scenario: An index from before +- **WHEN** an index already exists in `.generated/docs-index` +- **THEN** lookups read it without rebuilding diff --git a/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md b/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md new file mode 100644 index 00000000..594ae3da --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md @@ -0,0 +1,25 @@ +## ADDED Requirements + +### Requirement: A view's own scale is applied and read back +`create_drawing_view` with a `scale` other than 1 SHALL give the new view its +own scale (no longer the sheet's) and reply with `scale_applied` true only +when the scale read back from the view matches. + +#### Scenario: A half-scale top view +- **WHEN** a top view is placed with `scale` 0.5 +- **THEN** the view is drawn at 1:2 while the sheet keeps its scale, and the + reply says `scale_applied: true` + +#### Scenario: A scale SolidWorks doesn't keep +- **WHEN** the view's scale reads back as something else +- **THEN** the reply says `scale_applied: false` + +### Requirement: `view_type` names the view when `orientation` is left out +`create_drawing_view` with no `orientation` SHALL use `view_type` as the +orientation when it names one (`front`, `top`, `right`, `isometric`, ...), +and `front` otherwise. + +#### Scenario: Only view_type +- **WHEN** a view is placed with `view_type` `isometric` and no + `orientation` +- **THEN** it is an isometric view, not a front view diff --git a/openspec/changes/solidworks-2024-reports/specs/tools/edge-treatment/spec.md b/openspec/changes/solidworks-2024-reports/specs/tools/edge-treatment/spec.md new file mode 100644 index 00000000..bb587aff --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/specs/tools/edge-treatment/spec.md @@ -0,0 +1,11 @@ +## ADDED Requirements + +### Requirement: A fillet works on every supported SolidWorks version +`add_fillet` SHALL build the fillet with the same COM call on every +SolidWorks version the server supports, so no version takes a branch that +has never run. + +#### Scenario: SolidWorks 2024 +- **WHEN** `add_fillet` runs against SolidWorks 2024 (major version 32) +- **THEN** it calls `IModelDoc2.FeatureFillet3` with its 9 arguments, as on + 2025 and 2026, and adds the fillet diff --git a/openspec/changes/solidworks-2024-reports/tasks.md b/openspec/changes/solidworks-2024-reports/tasks.md new file mode 100644 index 00000000..5ed63a93 --- /dev/null +++ b/openspec/changes/solidworks-2024-reports/tasks.md @@ -0,0 +1,21 @@ +## 1. Fillet on every version (#255) + +- [x] 1.1 `_add_fillet_impl`: always `IModelDoc2.FeatureFillet3`; the version check and the `IFeatureManager.FeatureFillet3` branch removed +- [x] 1.2 Tests: a 2024 revision takes the same call; the tests that reached the old branch by giving no version move to the model call + +## 2. View scale and view_type (#256) + +- [x] 2.1 `_place_view`: `UseSheetScale` off, `ScaleDecimal` set, read back for `scale_applied` (and the scale read back in the reply) +- [x] 2.2 `CreateDrawingViewInput.orientation` defaults to none; `view_type` that names a view is used, else `front` +- [x] 2.3 Tests beside each; the drawing catalog entry + +## 3. The index folder (#257) + +- [x] 3.1 `_INDEX_DIRS`: `~/.solidworks_mcp/docs-index` first (where an index is saved), then the old relative folders (read only) +- [x] 3.2 Tests: a build saves to the user folder; an old relative index is still found; the catalog and tool description + +## 4. Checks and sign-off + +- [x] 4.1 Unit suite at 100% coverage, ruff, mypy, mkdocs strict, link check; CHANGELOG +- [ ] 4.2 Live on 2026: a fillet, a half-scale view, and a lookup started from a read-only folder +- [ ] 4.3 The user decides what to say on #255, #256, #257 and when; nothing is posted until then diff --git a/src/solidworks_mcp/adapters/solidworks/features.py b/src/solidworks_mcp/adapters/solidworks/features.py index e6c2254b..48ea375b 100644 --- a/src/solidworks_mcp/adapters/solidworks/features.py +++ b/src/solidworks_mcp/adapters/solidworks/features.py @@ -2102,18 +2102,6 @@ def _fillet_operation() -> SolidWorksFeature: LookupError: If an edge or face entry selects nothing. Exception: If the feature is ``None``. """ - # Detect SW major version for FeatureFillet3 parameter count - fillet_sw_major = 0 - if getattr(adapter, "swApp", None): - rev = adapter._attempt( - lambda: adapter._get_attr_or_call(adapter.swApp, "RevisionNumber"), - default="0", - ) - try: - fillet_sw_major = int(str(rev).split(".")[0]) - except (ValueError, IndexError): - fillet_sw_major = 0 - # Only touch the selection when edges/faces were explicitly named. # An empty edge_names means "use whatever is already selected" -- # e.g. entities the user hand-picked in the live UI via @@ -2163,48 +2151,27 @@ def _fillet_operation() -> SolidWorksFeature: if not selected: raise LookupError(f"Failed to select edge: {edge_name}") - # SW 2025+ (major >= 33): IModelDoc2.FeatureFillet3 (9 params). - # Returns a non-zero int on success — NOT an IFeature — so we look up - # the last modified feature afterwards to get the name/id. - # Older builds: IFeatureManager.FeatureFillet3 (15 params, returns IFeature). - if fillet_sw_major >= 33: - result_code = adapter.currentModel.FeatureFillet3( - radius / 1000.0, # R1 in meters - True, # Propagate (VT_BOOL) - 0, # Ftyp (VT_I4) - False, # VarRadTyp (VT_BOOL — must be bool, not int) - 0, # OverflowType (VT_I4) - 0, # NRadii (VT_I4) - None, # Radii (VT_VARIANT) - False, # UseHelpPoint (VT_BOOL) - False, # UseTangentHoldLine (VT_BOOL) - ) - if not result_code: - raise Exception( - "Failed to create fillet (IModelDoc2.FeatureFillet3 returned 0)" - ) - feature = None # int return — retrieve feature object below - else: - feature_manager = adapter.currentModel.FeatureManager - feature = feature_manager.FeatureFillet3( - radius / 1000.0, - 0, - 0, - 0, - 0, - False, - False, - False, - False, - False, - False, - False, - False, - 0, - False, + # IModelDoc2.FeatureFillet3 (9 params) on every version. It returns a + # non-zero int on success, not an IFeature, so the feature is looked + # up afterwards for its name. (Before #255, versions below 2025 called + # IFeatureManager.FeatureFillet3 with 15 arguments, radius first; its + # signature has 14, options first, so it always failed with + # DISP_E_BADPARAMCOUNT on SolidWorks 2024.) + result_code = adapter.currentModel.FeatureFillet3( + radius / 1000.0, # R1 in meters + True, # Propagate (VT_BOOL) + 0, # Ftyp (VT_I4) + False, # VarRadTyp (VT_BOOL — must be bool, not int) + 0, # OverflowType (VT_I4) + 0, # NRadii (VT_I4) + None, # Radii (VT_VARIANT) + False, # UseHelpPoint (VT_BOOL) + False, # UseTangentHoldLine (VT_BOOL) + ) + if not result_code: + raise Exception( + "Failed to create fillet (IModelDoc2.FeatureFillet3 returned 0)" ) - if not feature: - raise Exception("Failed to create fillet") # IModelDoc2.FeatureFillet3 returns non-zero for a selection it then # builds nothing from (e.g. a bare face, seen live on SW 2026), so a @@ -2223,25 +2190,12 @@ def _fillet_operation() -> SolidWorksFeature: "edges could not be filleted at this radius." ) - # Resolve the feature name — FeatureFillet3 on SW 2025+ returns an int, - # not an IFeature, so we can only report a default name here. - feature_name = "Fillet" - if feature is not None: - # Not hasattr(): it only swallows AttributeError, so a stale COM - # dispatch raising on Name would fail a fillet that was created. - try: - feature_name = feature.Name or "Fillet" - except Exception: # noqa: BLE001 - int return / stale dispatch - pass - + # IModelDoc2.FeatureFillet3 returns an int, not an IFeature, so the + # name is SolidWorks' default; list_features gives the numbered one. return SolidWorksFeature( - name=feature_name, + name="Fillet", type="Fillet", - id=( - adapter._attempt(lambda: adapter._get_feature_id(feature), default="") - if feature - else "" - ), + id="", parameters={"radius": radius, "edges": edge_names}, properties={"created": datetime.now().isoformat()}, ) diff --git a/src/solidworks_mcp/adapters/solidworks/io.py b/src/solidworks_mcp/adapters/solidworks/io.py index 144e9dc3..5452d12d 100644 --- a/src/solidworks_mcp/adapters/solidworks/io.py +++ b/src/solidworks_mcp/adapters/solidworks/io.py @@ -3249,7 +3249,17 @@ def _place_view(self, payload: Any) -> AdapterResult[dict[str, Any]]: x = float(_first(data, "position_x", "x", default=100.0)) y = float(_first(data, "position_y", "y", default=150.0)) - requested = str(_first(data, "orientation", "view_type", default="front")) + # With no orientation, a view_type that names a view ("top", + # "isometric") is the orientation; any other ("orthographic") is front + # (#256: view_type alone used to leave every view a front view). + view_type = str(_first(data, "view_type", default="")).strip().lower() + requested = str( + _first( + data, + "orientation", + default=view_type if view_type in _NAMED_VIEWS else "front", + ) + ) view_name = _NAMED_VIEWS.get(requested.strip().lower()) if view_name is None and requested.startswith("*"): view_name = requested @@ -3322,17 +3332,25 @@ def _add() -> dict[str, Any]: added = [n for n in after if n not in before] new_view = added[-1] if added else after[-1] - scale_applied = False + # The view's own scale: UseSheetScale off, then ScaleDecimal, + # read back (#256: the view kept the sheet's scale, and + # scale_applied tested setattr's return value, always None). + scale_read = None if scale and view is not None: wrapped = _as_com(adapter, view, "IView") if wrapped is not None: - scale_applied = ( - adapter._attempt( - lambda: setattr(wrapped, "ScaleRatio", [scale, 1.0]), - default=None, - ) - is not None + adapter._attempt( + lambda: setattr(wrapped, "UseSheetScale", 0), default=None ) + adapter._attempt( + lambda: setattr(wrapped, "ScaleDecimal", scale), default=None + ) + scale_read = adapter._attempt( + lambda: float(wrapped.ScaleDecimal), default=None + ) + scale_applied = scale_read is not None and math.isclose( + scale_read, scale, rel_tol=1e-6 + ) return { "name": new_view, @@ -3341,6 +3359,7 @@ def _add() -> dict[str, Any]: "position": {"x": x, "y": y}, "scale": scale or None, "scale_applied": scale_applied if scale else None, + "scale_read": scale_read, "views_before": len(before), "views_after": len(after), } diff --git a/src/solidworks_mcp/tools/docs_discovery.py b/src/solidworks_mcp/tools/docs_discovery.py index a59a254d..3d8d57fc 100644 --- a/src/solidworks_mcp/tools/docs_discovery.py +++ b/src/solidworks_mcp/tools/docs_discovery.py @@ -50,13 +50,24 @@ # "2.1" adds the enums, so a "2.0" index is rebuilt once. INDEX_FORMAT = "2.1" -#: Where lookups look for a saved index, in order. -_INDEX_DIRS = ( +#: Where a built index is saved: the user's own data folder, beside the +#: server's other data (``config.data_dir``). Relative to the working folder +#: it failed with PermissionError when Claude Desktop started the server +#: through uvx in a folder the user can't write to (#257). +USER_INDEX_DIR = Path.home() / ".solidworks_mcp" / "docs-index" +#: Folders an index was saved in before #257, still read. +_LEGACY_INDEX_DIRS = ( Path(".generated/docs-index"), Path("tests/.generated/solidworks_integration/docs-index"), Path("tests/.generated/docs-index"), ) + +def _index_dirs() -> tuple[Path, ...]: + """Where lookups look for a saved index, in order: the user folder first.""" + return (USER_INDEX_DIR, *_LEGACY_INDEX_DIRS) + + IndexStatus = Literal["ready", "rebuilt", "unavailable"] MemberType = Literal["method", "property"] @@ -159,7 +170,7 @@ class SolidWorksDocsDiscovery: Args: output_dir (Path | None): Where the index is saved. Defaults to - ``.generated/docs-index``. + ``~/.solidworks_mcp/docs-index``. year (int | None): The SolidWorks year whose type library to read; None for the newest installed. strict_year (bool): True when the caller asked for ``year``, so a @@ -183,7 +194,7 @@ def __init__( year (int | None): The SolidWorks year to read, if any. strict_year (bool): True to fail when that year isn't installed. """ - self.output_dir = output_dir or _INDEX_DIRS[0] + self.output_dir = output_dir or USER_INDEX_DIR self.output_dir.mkdir(parents=True, exist_ok=True) self.year = year self.strict_year = strict_year @@ -346,7 +357,7 @@ class DiscoverDocsInput(CompatInput): output_dir: str | None = Field( default=None, description=( - "Folder to save the index in; default .generated/docs-index. The " + "Folder to save the index in; default ~/.solidworks_mcp/docs-index. The " "lookups only read the default folder, so another folder is for " "keeping a copy (pass it back as index_file)." ), @@ -710,7 +721,7 @@ def _find_index_file(year: int) -> Path | None: Path | None: The first ``solidworks_docs_index_.json`` in the index folders, or None. """ - for directory in _INDEX_DIRS: + for directory in _index_dirs(): candidate = directory / f"solidworks_docs_index_{year}.json" if candidate.is_file(): return candidate diff --git a/src/solidworks_mcp/tools/drawing.py b/src/solidworks_mcp/tools/drawing.py index fa0ea39b..806e4185 100644 --- a/src/solidworks_mcp/tools/drawing.py +++ b/src/solidworks_mcp/tools/drawing.py @@ -29,10 +29,10 @@ class CreateDrawingViewInput(BaseModel): Attributes: model_path (str): The model path value. - orientation (str): The orientation value. + orientation (str | None): The orientation; none takes view_type. position_x (float): The position x value. position_y (float): The position y value. - scale (float): The scale value. + scale (float | None): The view's own scale; none uses the sheet's. view_type (str): The view type value. """ @@ -42,9 +42,16 @@ class CreateDrawingViewInput(BaseModel): ) position_x: float = Field(default=100.0, description="X position in drawing (mm)") position_y: float = Field(default=200.0, description="Y position in drawing (mm)") - scale: float = Field(default=1.0, description="View scale factor") - orientation: str = Field( - default="front", description="View orientation (front, top, right, isometric)" + scale: float | None = Field( + default=None, + gt=0, + description="The view's own scale, e.g. 0.5 for 1:2; leave it out to use " + "the sheet's scale (set_sheet_scale)", + ) + orientation: str | None = Field( + default=None, + description="View orientation (front, top, right, isometric); left out, " + "a view_type that names one is used, else front", ) diff --git a/tests/conftest.py b/tests/conftest.py index 9be05b79..a77eb857 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -147,7 +147,9 @@ def _no_solidworks_launch() -> Generator[None]: @pytest.fixture(autouse=True) def _no_real_type_library( - request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, + tmp_path_factory: pytest.TempPathFactory, ) -> None: """Keep the API lookup tools off this machine's SolidWorks type library. @@ -168,6 +170,10 @@ def _no_library(*_args: object, **_kwargs: object) -> None: monkeypatch.setattr(docs_discovery, "load_type_library", _no_library) monkeypatch.setattr(docs_discovery, "target_version", _no_library) monkeypatch.setattr(docs_discovery, "load_constants_library", _no_library) + # Never read or write the real ~/.solidworks_mcp index from a test. + monkeypatch.setattr( + docs_discovery, "USER_INDEX_DIR", tmp_path_factory.mktemp("user-index") + ) @pytest.fixture(scope="session") diff --git a/tests/solidworks_mcp/adapters/solidworks/test_features.py b/tests/solidworks_mcp/adapters/solidworks/test_features.py index 5bf3af02..45bd6ab5 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_features.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_features.py @@ -295,7 +295,9 @@ def test_add_fillet_and_chamfer_selection_and_feature_failures() -> None: ) extension = SimpleNamespace(SelectByID2=lambda edge, *_args: edge != "Edge") adapter.currentModel = SimpleNamespace( - FeatureManager=feature_manager, Extension=extension + FeatureManager=feature_manager, + Extension=extension, + FeatureFillet3=lambda *args: 0, ) fillet_select_error = features._add_fillet_impl(adapter, 2.0, ["Edge"]) @@ -1150,15 +1152,16 @@ def test_feature_cut3_fallback_reverses_direction_not_the_cut_side() -> None: assert cut3_args == cut4_args[:26] -def test_fillet_with_unparseable_version_and_unreadable_feature_name() -> None: - class _Fillet: - @property - def Name(self): # noqa: N802 - raise RuntimeError("stale dispatch") - - adapter = _versioned_adapter("garbage") +@pytest.mark.parametrize("revision", ["32.5.0", "33.2.1", "34.0.0", "garbage"]) +def test_a_fillet_makes_the_same_call_on_every_version(revision: str) -> None: + """#255: SolidWorks 2024 (32) took a 15-argument call with 14 parameters.""" + calls: list[tuple[object, ...]] = [] + adapter = _versioned_adapter(revision) adapter.currentModel = SimpleNamespace( - FeatureManager=SimpleNamespace(FeatureFillet3=lambda *_a: _Fillet()), + FeatureManager=SimpleNamespace( + FeatureFillet3=lambda *_a: pytest.fail("the old call") + ), + FeatureFillet3=lambda *args: calls.append(args) or 1, Extension=SimpleNamespace(SelectByID2=lambda *_a: True), ) @@ -1166,6 +1169,7 @@ def Name(self): # noqa: N802 assert result.is_success, result.error assert result.data.name == "Fillet" + assert calls == [(0.002, True, 0, False, 0, 0, None, False, False)] @pytest.mark.parametrize("percent", [0.0, 100.0, 150.0]) @@ -1977,9 +1981,9 @@ async def test_feature_creation_failure_paths(self, monkeypatch): Extension=SimpleNamespace(SelectByID2=Mock(return_value=True)), FeatureManager=SimpleNamespace( FeatureCut3=Mock(return_value=None), - FeatureFillet3=Mock(return_value=None), FeatureChamfer=Mock(return_value=None), ), + FeatureFillet3=Mock(return_value=0), FirstFeature=SimpleNamespace( GetTypeName2=lambda: "ProfileFeature", Name="Sketch1", diff --git a/tests/solidworks_mcp/adapters/solidworks/test_io.py b/tests/solidworks_mcp/adapters/solidworks/test_io.py index 588c971e..ed53d675 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_io.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_io.py @@ -4481,3 +4481,84 @@ async def test_set_dimension_in_named_configurations(monkeypatch) -> None: refused.error or "" ) assert "No configuration named 'Short'" in (unknown.error or "") + + +def _view_adapter(monkeypatch, view: object): # noqa: ANN202 + """A drawing that places ``view`` and reports one new view.""" + adapter = _build_adapter(monkeypatch) + adapter.currentModel = MagicMock() + adapter.currentModel.GetType.return_value = 3 + adapter.swApp = MagicMock() + adapter.swApp.OpenDoc6.return_value = MagicMock() + monkeypatch.setattr( + "solidworks_mcp.adapters.solidworks.io._dynamic", + SimpleNamespace(Dispatch=lambda obj: obj), + ) + names = iter([[], ["Drawing View1"]]) + monkeypatch.setattr( + "solidworks_mcp.adapters.solidworks.io._view_names", + lambda adapter, drawing: next(names), + ) + adapter.currentModel.CreateDrawViewFromModelView3.return_value = view + return adapter + + +class TestViewScaleAndViewType: + """#256: a view's own scale is set and read back; view_type names the view.""" + + @pytest.mark.asyncio + async def test_a_half_scale_view_reads_back(self, monkeypatch) -> None: + view = SimpleNamespace(UseSheetScale=1, ScaleDecimal=1.0) + adapter = _view_adapter(monkeypatch, view) + + result = await adapter.create_drawing_view( + {"model_path": __file__, "orientation": "top", "scale": 0.5} + ) + + assert view.UseSheetScale == 0 + assert result.data["scale_applied"] is True + assert result.data["scale_read"] == 0.5 + + @pytest.mark.asyncio + async def test_a_scale_solidworks_doesnt_keep_is_reported( + self, monkeypatch + ) -> None: + class _SheetScaled: + UseSheetScale = 1 + + @property + def ScaleDecimal(self) -> float: + return 1.0 + + @ScaleDecimal.setter + def ScaleDecimal(self, _value: float) -> None: + pass + + adapter = _view_adapter(monkeypatch, _SheetScaled()) + + result = await adapter.create_drawing_view( + {"model_path": __file__, "scale": 0.75} + ) + + assert result.data["scale_applied"] is False + assert result.data["scale_read"] == 1.0 + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("payload", "orientation"), + [ + ({"view_type": "isometric"}, "*Isometric"), + ({"view_type": "orthographic"}, "*Front"), + ({"view_type": "isometric", "orientation": "top"}, "*Top"), + ({}, "*Front"), + ], + ) + async def test_view_type_names_the_view_when_orientation_is_left_out( + self, monkeypatch, payload: dict, orientation: str + ) -> None: + adapter = _view_adapter(monkeypatch, SimpleNamespace()) + + result = await adapter.create_drawing_view({"model_path": __file__, **payload}) + + assert result.data["orientation"] == orientation + assert result.data["scale_read"] is None diff --git a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py index 061f871c..86ccff18 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_sketch.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_sketch.py @@ -2218,9 +2218,9 @@ async def test_sketch_geometry_feature_and_mass_property_paths(self, monkeypatch # removes material; the volume is put back for the mass check below. def _fillet(*_args): mass_props.Volume = 1.9e-9 - return feature_obj + return 1 # IModelDoc2.FeatureFillet3 returns an int - feature_manager.FeatureFillet3 = Mock(side_effect=_fillet) + adapter.currentModel.FeatureFillet3 = Mock(side_effect=_fillet) fillet = await adapter.add_fillet(2.0, ["Edge1", "Edge2"]) mass_props.Volume = 2.0e-9 chamfer = await adapter.add_chamfer(1.5, ["Edge1"]) diff --git a/tests/solidworks_mcp/tools/test_docs_discovery.py b/tests/solidworks_mcp/tools/test_docs_discovery.py index 7dc04acd..0907caeb 100644 --- a/tests/solidworks_mcp/tools/test_docs_discovery.py +++ b/tests/solidworks_mcp/tools/test_docs_discovery.py @@ -1647,6 +1647,45 @@ async def test_repeated_lookups_build_the_index_once( assert len(fake_type_library) == 1 +@pytest.mark.asyncio +async def test_a_built_index_is_saved_in_the_user_folder( + mcp_server, mock_config, fake_type_library +) -> None: + """#257: not in the working folder, which uvx may start unwritable.""" + from solidworks_mcp.tools import docs_discovery + + tools = await _docs_tools(mcp_server, mock_config) + + result = await tools["lookup_api_method"]( + {"interface": "ISldWorks", "method": "OpenDoc6"} + ) + + saved = docs_discovery.USER_INDEX_DIR / "solidworks_docs_index_2026.json" + assert result["index_status"] == "rebuilt" + assert saved.is_file() + assert not Path(".generated").exists() + + +@pytest.mark.asyncio +async def test_an_index_in_the_old_folder_is_still_read( + mcp_server, mock_config, fake_type_library +) -> None: + from solidworks_mcp.tools import docs_discovery + + tools = await _docs_tools(mcp_server, mock_config) + arguments = {"interface": "ISldWorks", "method": "OpenDoc6"} + await tools["lookup_api_method"](arguments) + name = "solidworks_docs_index_2026.json" + old = Path(".generated/docs-index") + old.mkdir(parents=True) + (docs_discovery.USER_INDEX_DIR / name).rename(old / name) + + result = await tools["lookup_api_method"](arguments) + + assert result["index_status"] == "ready" + assert len(fake_type_library) == 1 + + @pytest.mark.asyncio async def test_an_index_from_another_type_library_version_is_rebuilt( mcp_server, mock_config, fake_type_library diff --git a/tests/solidworks_mcp/tools/test_drawing.py b/tests/solidworks_mcp/tools/test_drawing.py index 1a373b4a..ef33c80e 100644 --- a/tests/solidworks_mcp/tools/test_drawing.py +++ b/tests/solidworks_mcp/tools/test_drawing.py @@ -8,6 +8,7 @@ from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus from solidworks_mcp.tools.drawing import ( AutoCenterMarksInput, + CreateDrawingViewInput, DimensionInput, DrawingCreationInput, DrawingViewInput, @@ -553,3 +554,13 @@ async def test_add_note_refuses_without_the_capability(mcp_server, mock_config) result = await tool({"text": "X", "position_x": 1, "position_y": 1}) assert result["error_type"] == "not_supported" + + +def test_a_drawing_view_leaves_scale_and_orientation_to_the_sheet_and_view_type() -> ( + None +): + """#256: no scale means the sheet's; no orientation means view_type's.""" + made = CreateDrawingViewInput(model_path="C:/p/plate.sldprt", view_type="top") + + assert made.scale is None + assert made.orientation is None From addf008fe58b0adce9f57c30e12c364d30303148 Mon Sep 17 00:00:00 2001 From: Andrew Bartels Date: Fri, 20 Nov 2026 14:57:41 -0800 Subject: [PATCH 2/4] test(live): the three SolidWorks 2024 reports, by the reporter's steps; scale spec says a missing scale keeps the sheet's --- .../specs/tools/drawing-view-scale/spec.md | 7 +- .../test_live_sw_solidworks_2024_reports.py | 175 ++++++++++++++++++ 2 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 tests/live/test_live_sw_solidworks_2024_reports.py diff --git a/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md b/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md index 594ae3da..bf4b964a 100644 --- a/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md +++ b/openspec/changes/solidworks-2024-reports/specs/tools/drawing-view-scale/spec.md @@ -1,9 +1,10 @@ ## ADDED Requirements ### Requirement: A view's own scale is applied and read back -`create_drawing_view` with a `scale` other than 1 SHALL give the new view its -own scale (no longer the sheet's) and reply with `scale_applied` true only -when the scale read back from the view matches. +`create_drawing_view` with a `scale` SHALL give the new view its own scale +(no longer the sheet's) and reply with `scale_applied` true only when the +scale read back from the view matches. With no `scale` the view SHALL keep +the sheet's scale, so `set_sheet_scale` still governs it. #### Scenario: A half-scale top view - **WHEN** a top view is placed with `scale` 0.5 diff --git a/tests/live/test_live_sw_solidworks_2024_reports.py b/tests/live/test_live_sw_solidworks_2024_reports.py new file mode 100644 index 00000000..19e2d57f --- /dev/null +++ b/tests/live/test_live_sw_solidworks_2024_reports.py @@ -0,0 +1,175 @@ +"""The three SolidWorks 2024 reports (#255, #256, #257), checked on real SolidWorks. + +Each follows the reporter's own steps. On SolidWorks 2026 these check that +the fixes changed nothing that worked; whether 2024 now works can only be +confirmed there. + +1. #255: a 100 x 60 x 10 plate, a 5 mm fillet on a vertical corner edge. +2. #256: views of the plate at 0.5 (top) and 0.75 (isometric, given only as + ``view_type``): each at its own scale, read back, and the isometric view + really isometric. +3. #257: ``lookup_api_method`` from a working folder the server can't write + to: the index is saved in ``~/.solidworks_mcp/docs-index``. + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_solidworks_2024_reports.py + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows. +""" + +from __future__ import annotations + +import math +import os +from pathlib import Path +from typing import Any + +import pytest + +from tests.live.evidence import evidence + +pytestmark = pytest.mark.asyncio + + +async def _tools(adapter: Any) -> dict[str, Any]: + """Every tool, registered against ``adapter``: name -> function.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools import register_tools + + mcp = FastMCP("solidworks-2024-reports-live") + await register_tools(mcp, adapter, {}) + return {t.name: t.fn for t in await mcp.list_tools()} + + +async def _ok(reply: dict[str, Any]) -> dict[str, Any]: + assert reply["status"] == "success", reply + return reply + + +async def _plate(tools: dict[str, Any]) -> None: + """The reporter's plate: a 100 x 60 rectangle on Top, extruded 10 mm.""" + await _ok(await tools["create_part"]({"name": "plate"})) + made = await _ok(await tools["create_sketch"]({"plane": "Top"})) + await _ok(await tools["add_rectangle"]({"x1": -50, "y1": -30, "x2": 50, "y2": 30})) + await _ok(await tools["exit_sketch"]()) + await _ok( + await tools["create_extrusion"]( + {"sketch_name": made["sketch"]["name"], "depth": 10} + ) + ) + + +async def test_a_fillet_on_the_reporters_plate(scratch: Any) -> None: + """#255: one 5 mm fillet on a vertical corner edge removes its corner.""" + tools = await _tools(scratch.adapter) + await _plate(tools) + + fillet = await tools["add_fillet"]({"radius": 5, "edge_names": ["0.05,0.005,0.03"]}) + expected = 100 * 60 * 10 - 5**2 * (1 - math.pi / 4) * 10 + checked = await tools["verify_model"]({"volume_mm3": round(expected, 3)}) + evidence( + "#255: a 5 mm fillet on the plate's corner edge", + {"fillet": fillet.get("message"), "verdict": checked["verdict"]}, + call='add_fillet({"radius": 5, "edge_names": ["0.05,0.005,0.03"]})', + ) + assert fillet["status"] == "success", fillet + assert checked["verdict"] == "pass", checked + + +async def test_views_at_their_own_scale(scratch: Any, tmp_path: Path) -> None: + """#256: 0.5 and 0.75 views read back; view_type alone sets isometric.""" + tools = await _tools(scratch.adapter) + await _plate(tools) + part = str(tmp_path / "plate.SLDPRT") + saved = await scratch.adapter.save_file(part) + assert saved.is_success, saved.error + scratch.written_files.append(part) + await _ok(await tools["create_drawing"]({"name": "plate-views"})) + + top = await _ok( + await tools["create_drawing_view"]( + { + "model_path": part, + "view_type": "top", + "orientation": "top", + "scale": 0.5, + "position_x": 100, + "position_y": 150, + } + ) + ) + iso = await _ok( + await tools["create_drawing_view"]( + { + "model_path": part, + "view_type": "isometric", + "scale": 0.75, + "position_x": 280, + "position_y": 150, + } + ) + ) + sheet = await _ok( + await tools["create_drawing_view"]( + { + "model_path": part, + "view_type": "front", + "position_x": 100, + "position_y": 60, + } + ) + ) + evidence( + "#256: each view at its own scale, read back; view_type sets isometric", + { + "top": { + k: top["data"][k] for k in ("scale", "scale_applied", "scale_read") + }, + "isometric": { + k: iso["data"][k] + for k in ("orientation", "scale", "scale_applied", "scale_read") + }, + "no scale": {"scale_applied": sheet["data"]["scale_applied"]}, + }, + call="create_drawing_view(scale 0.5), (view_type isometric, scale 0.75), " + "(no scale)", + ) + assert top["data"]["scale_applied"] is True, top + assert iso["data"]["orientation"] == "*Isometric", iso + assert iso["data"]["scale_applied"] is True, iso + assert sheet["data"]["scale_applied"] is None, sheet + + +async def test_a_lookup_from_a_folder_it_cant_write( + scratch: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """#257: started in an unwritable folder, the index goes to the user folder.""" + from solidworks_mcp.tools import docs_discovery + + tools = await _tools(scratch.adapter) + locked = tmp_path / "locked" + locked.mkdir() + os.chmod(locked, 0o555) # read-only: Windows honours the read-only flag + monkeypatch.chdir(locked) + + result = await tools["lookup_api_method"]( + {"interface": "IDrawingDoc", "method": "AutoDimension"} + ) + saved = sorted(docs_discovery.USER_INDEX_DIR.glob("solidworks_docs_index_*.json")) + evidence( + "#257: a lookup from a read-only working folder", + { + "status": result["status"], + "found": result.get("result", {}).get("found"), + "index_status": result.get("index_status"), + "saved_in": str(docs_discovery.USER_INDEX_DIR), + "files": [p.name for p in saved], + }, + call='lookup_api_method({"interface": "IDrawingDoc", "method": "AutoDimension"})', + ) + assert result["status"] == "success", result + assert saved, "no index saved in the user folder" + assert not (locked / ".generated").exists() From 261392e30dfd746c0dd94c79e48c0ebb7ea7e1cb Mon Sep 17 00:00:00 2001 From: Andrew Bartels Date: Fri, 20 Nov 2026 19:34:09 -0800 Subject: [PATCH 3/4] chore: SolidWorks 2024 reports checked live on 2026 (3 passed); release and replies tasks --- openspec/changes/solidworks-2024-reports/tasks.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/openspec/changes/solidworks-2024-reports/tasks.md b/openspec/changes/solidworks-2024-reports/tasks.md index 5ed63a93..b82a4db9 100644 --- a/openspec/changes/solidworks-2024-reports/tasks.md +++ b/openspec/changes/solidworks-2024-reports/tasks.md @@ -17,5 +17,6 @@ ## 4. Checks and sign-off - [x] 4.1 Unit suite at 100% coverage, ruff, mypy, mkdocs strict, link check; CHANGELOG -- [ ] 4.2 Live on 2026: a fillet, a half-scale view, and a lookup started from a read-only folder -- [ ] 4.3 The user decides what to say on #255, #256, #257 and when; nothing is posted until then +- [x] 4.2 Live on 2026: a fillet, a half-scale view, and a lookup started from a read-only folder +- [ ] 4.3 The user decides what to say on #255, #256, #257 and when; nothing is posted until then (replies drafted 2026-11-20: fixed in the release, then the selftest on 2024) +- [ ] 4.4 After the merge: release 2.1.0 from main (pyproject, version.py, server.json, CHANGELOG heading), tag pushed by the user's OK From cb71e5644083f9094916712f17d33f460d814403 Mon Sep 17 00:00:00 2001 From: Andrew Bartels Date: Sat, 21 Nov 2026 00:02:14 -0800 Subject: [PATCH 4/4] release: 2.1.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 2 +- server.json | 4 ++-- src/solidworks_mcp/version.py | 2 +- uv.lock | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06e34ae4..6c47794c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.1.0] - 2026-11-21 + ### Changed - **`generate_drawing_package` fits every title-block field** (#158): diff --git a/pyproject.toml b/pyproject.toml index 23619b80..68a1cdb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "solidworks-mcp-python" -version = "2.0.0" +version = "2.1.0" description = "Python MCP server for SolidWorks: lets Claude and other AI agents build parts, assemblies and drawings through the SolidWorks COM API." # The README with relative links made absolute for PyPI: see the fancy-pypi-readme hook. dynamic = ["readme"] diff --git a/server.json b/server.json index fd7cbcb4..71a64d81 100644 --- a/server.json +++ b/server.json @@ -8,12 +8,12 @@ "source": "github" }, "websiteUrl": "https://andrewbartels1.com/SolidworksMCP-python/", - "version": "2.0.0", + "version": "2.1.0", "packages": [ { "registryType": "pypi", "identifier": "solidworks-mcp-python", - "version": "2.0.0", + "version": "2.1.0", "runtimeHint": "uvx", "transport": { "type": "stdio" diff --git a/src/solidworks_mcp/version.py b/src/solidworks_mcp/version.py index 59cfe524..9cf5395a 100644 --- a/src/solidworks_mcp/version.py +++ b/src/solidworks_mcp/version.py @@ -1,6 +1,6 @@ """Version information for SolidWorks MCP Server.""" -__version__ = "2.0.0" +__version__ = "2.1.0" __author__ = "Andrew Bartels" __email__ = "andrewbartels1@gmail.com" __description__ = "SolidWorks MCP Server with FastMCP and PydanticAI" diff --git a/uv.lock b/uv.lock index 3697000f..e420b6e2 100644 --- a/uv.lock +++ b/uv.lock @@ -3375,7 +3375,7 @@ wheels = [ [[package]] name = "solidworks-mcp-python" -version = "2.0.0" +version = "2.1.0" source = { editable = "." } dependencies = [ { name = "aiosqlite" },