diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a7510121..d24346a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,10 @@ jobs: shell: bash -el {0} run: conda run -n solidworks_mcp pip install -e ".[dev,docs,ui]" + - name: Type-check + shell: bash -el {0} + run: make typecheck + - name: Run tests shell: bash -el {0} run: make test diff --git a/CHANGELOG.md b/CHANGELOG.md index 09622dd4..7cae03f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **`save_body_as_part` leaves no extra assembly open** (queue item 27, + #101): a new, unsaved assembly SolidWorks opens alongside Save Bodies is + closed, the part is made active again, and the reply's + `closed_documents` names it. +- **`execute_macro` runs VBA source** (queue item 26, #96), when the server + is started with `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1` (off by default: VBA + can do anything the user can). The source is written to a `.swb` file and + run like a macro file, with the dialog watchdog; the reply names the file + and repeats the source. Refused as `vba_source_off` otherwise. +- **A macro that waits for the user no longer hangs the server** (queue + item 25, #97): while `execute_macro` runs, a watchdog thread (Win32 only, + no COM) looks for a dialog the SolidWorks process opened. One still open + after `dialog_timeout` seconds (30) is answered with Cancel, or its only + button, and the run fails as `macro_waited_for_user`, naming the dialog. + A Yes/No prompt is left for the user. Checked live. +- **Tool catalog check** (queue item 24, #156): a test reads every catalog + page and fails when a tool has no entry, an entry's parameter table + doesn't match the tool's inputs, or its sample call isn't one the tool + accepts. The 20 tools that had no entry have one, about 30 stale tables + and samples are fixed, and `reset_circuit_breaker` has a Server Admin + page. `src/utils/generate_tool_catalog.py`, which overwrote the + hand-written pages, is removed. +- **`get_api_enum`** (queue item 23, #95): an enum's members and their + integer values, by the enum's name or a member's, read from SolidWorks' + constants type library (`swconst.tlb`), checked live (`swUnitSystem_IPS` + is 3). The API index now holds the enums too (format 2.1; a saved index + is rebuilt once). 140 tools. +- **mypy gates CI** (queue item 17, #157): `make typecheck` runs mypy over + the package, and CI fails on any error. The 139 errors on `main` are + fixed with no change in behaviour, apart from one fault it found: + dimension layout raised `TypeError` for a leader with no lines when asked + to place it inside its view; it now goes outside. Every `# type: ignore` + names its error code (checked by a test). - **What each tool needs from SolidWorks** (queue item 16, #79): every tool has a `needs:` tag, `nothing`, `installed` or `running`, from one table (`tools/requirements.py`). The tools overview lists the 20 tools that @@ -794,7 +827,7 @@ Minor release — new tools, all additive and backward compatible. against `ActiveDoc`. - **Granular API-lookup tools** (#64) — `lookup_api_method`, `lookup_api_interface`, `find_related_api_members` in the docs-discovery - layer (`lookup_api_enum` split to a follow-up). + layer (`get_api_enum` split to a follow-up). - **SoC `script_line` capture** (#28) — every `ToolCallRecord` now stores the rendered SolidWorks-as-Code line at write time; a startup `ALTER TABLE` check backfills the column on existing local databases. diff --git a/CLAUDE.md b/CLAUDE.md index 33b6a3d4..07c9e6f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -48,8 +48,9 @@ python -m venv .venv # Run server .\.venv\Scripts\python.exe -m solidworks_mcp.server -# Lint/tests/docs +# Lint/types/tests/docs (CI runs mypy too and fails on any error) .\.venv\Scripts\python.exe -m ruff check src tests +.\.venv\Scripts\python.exe -m mypy src/solidworks_mcp .\.venv\Scripts\python.exe -m pytest tests -m "not solidworks_only" .\.venv\Scripts\python.exe -m mkdocs build --clean ``` diff --git a/Makefile b/Makefile index 72606b0a..6cdb3e00 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # SolidWorks MCP Server - Simplified Makefile -.PHONY: help install test test-context-budget llms links test-full test-clean docs build run clean lint format +.PHONY: help install test test-context-budget llms links test-full test-clean docs build run clean lint typecheck format # Default target .DEFAULT_GOAL := help @@ -140,6 +140,14 @@ lint: ## Run code linting fi $(CONDA_CMD) run -n solidworks_mcp ruff check src/ tests/ +typecheck: ## Type-check the package with mypy (CI fails on any error) + @echo "$(BLUE)Type-checking...$(NC)" + @if [ -z "$(CONDA_CMD)" ]; then \ + echo "$(RED)Error: No conda/mamba/micromamba found$(NC)"; \ + exit 1; \ + fi + $(CONDA_CMD) run -n solidworks_mcp python -m mypy src/solidworks_mcp + format: ## Format code @echo "$(BLUE)Formatting code...$(NC)" @if [ -z "$(CONDA_CMD)" ]; then \ diff --git a/README.md b/README.md index f7ff4153..dc3260db 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 139 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 140 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/) @@ -366,7 +366,7 @@ It works only with the circuit-breaker adapter wrapper (the default for real Sol ### A shorter tool list -All 139 tools cost about 55,000 tokens a turn. `SOLIDWORKS_MCP_TOOL_MODE=search` lists four instead (about 900 tokens); `SOLIDWORKS_MCP_TOOLSETS=core,drawing` lists only those groups. See [Choose which tools a client sees](https://andrewbartels1.com/SolidworksMCP-python/getting-started/installation/#4-choose-which-tools-a-client-sees). +All 140 tools cost about 55,000 tokens a turn. `SOLIDWORKS_MCP_TOOL_MODE=search` lists four instead (about 900 tokens); `SOLIDWORKS_MCP_TOOLSETS=core,drawing` lists only those groups. See [Choose which tools a client sees](https://andrewbartels1.com/SolidworksMCP-python/getting-started/installation/#4-choose-which-tools-a-client-sees). ## Teach your agent the workflow diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index ac743ee7..5cb9e2b1 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,8 +1,8 @@ { "tools": { - "total": 139, + "total": 140, "by_level": { - "stable": 131, + "stable": 132, "beta": 0, "experimental": 0, "planned": 0, @@ -427,7 +427,7 @@ "family": "macro_recording", "level": "stable", "reason": "", - "summary": "Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, calling its `main` procedure once." + "summary": "Run a SolidWorks macro (.swp, or legacy .swb), or VBA source text, in the running SolidWorks, calling its `main` procedure." }, { "name": "exit_sketch", @@ -576,6 +576,13 @@ "reason": "", "summary": "Write a VBA macro that revolves the selected sketch, with both-direction and thin-wall options." }, + { + "name": "get_api_enum", + "family": "docs_discovery", + "level": "stable", + "reason": "", + "summary": "Look up a SolidWorks API enum's members and their integer values." + }, { "name": "get_custom_properties", "family": "engineering_data", @@ -987,11 +994,11 @@ "com": { "type_library": "83A33D31-27C5-11CE-BFD4-00400513BB57x0x34x0", "core": { - "covered": 251, + "covered": 252, "total": 2838 }, "api": { - "covered": 276, + "covered": 277, "total": 5985 }, "interfaces": [ @@ -1009,6 +1016,7 @@ "GetMassProperties", "GetMathUtility", "GetOpenDocumentByName", + "GetProcessID", "GetUserPreferenceStringValue", "GetUserPreferenceToggle", "NewAssembly", diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index 4163a00b..9178b489 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,7 +21,7 @@ -MCP tools: 131 +MCP tools: 132 100% work on SolidWorks today @@ -33,7 +33,7 @@ -stable 131 +stable 132 beta 0 @@ -43,13 +43,13 @@ deprecated 8 Core SolidWorks COM API (12 interfaces) -251 of 2,838 methods · 8.8% +252 of 2,838 methods · 8.9% - - - + + + -Whole API: 276 of 5,985 method names (4.6%), counted by a text scan of the adapters. +Whole API: 277 of 5,985 method names (4.6%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index e538ef0e..1f91af56 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -61,7 +61,7 @@ delete_configurationfile_managementstableDelete a configuration of the active model; not the active one or the only one. delete_featuremodelingstableDelete a feature or sketch from the active model, along with the features that depend on it. discover_solidworks_docsdocs_discoverystableRebuild the SolidWorks API index on purpose. The lookups don't need it. -execute_macromacro_recordingstableRun a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, calling its `main` procedure once. +execute_macromacro_recordingstableRun a SolidWorks macro (.swp, or legacy .swb), or VBA source text, in the running SolidWorks, calling its `main` procedure. exit_sketchsketchingstableClose the open sketch so a feature can use it. export_dwgexportstableExport the active document to DWG, like File > Save As with the DWG type. export_flat_patternengineering_datastableExport the active sheet-metal part's flat pattern to DXF or DWG, for laser or waterjet cutting. @@ -83,6 +83,7 @@ generate_vba_macro_recordervba_generationstableWrite a VBA starting point: a macro skeleton to fill in, or a note on starting and stopping SolidWorks' macro recorder. generate_vba_part_modelingvba_generationstableWrite a VBA macro for a shell or a fillet on the active part. generate_vba_revolvevba_generationstableWrite a VBA macro that revolves the selected sketch, with both-direction and thin-wall options. +get_api_enumdocs_discoverystableLook up a SolidWorks API enum's members and their integer values. get_custom_propertiesengineering_datastableRead the active document's custom properties, such as PartNo, Description or Revision. get_dimensionmodelingstableRead one dimension of the active model by its full name, e.g. "D1@Sketch1". get_file_propertiesfile_managementdeprecated
use `get_model_info`.Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes. @@ -149,7 +150,7 @@ - + diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index 56c726a7..e8d16689 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` | 139 | 224 KB | 57,285 | 100% | -| `core` | `list` | 100 | 151 KB | 38,696 | 68% | -| `drawing` | `list` | 21 | 37 KB | 9,580 | 17% | -| `automation` | `list` | 3 | 5 KB | 1,348 | 2% | -| `vba` | `list` | 10 | 17 KB | 4,356 | 8% | -| `docs` | `list` | 5 | 13 KB | 3,304 | 6% | -| `core,drawing` | `list` | 121 | 189 KB | 48,276 | 84% | +| `all` | `list` | 140 | 227 KB | 58,160 | 100% | +| `core` | `list` | 100 | 151 KB | 38,717 | 67% | +| `drawing` | `list` | 21 | 37 KB | 9,580 | 16% | +| `automation` | `list` | 3 | 6 KB | 1,592 | 3% | +| `vba` | `list` | 10 | 17 KB | 4,356 | 7% | +| `docs` | `list` | 6 | 15 KB | 3,914 | 7% | +| `core,drawing` | `list` | 121 | 189 KB | 48,297 | 83% | | `all` | `search` | 4 | 4 KB | 908 | 2% | | `core` | `search` | 4 | 4 KB | 908 | 2% | diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 56cb7e4d..db6076c6 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -108,6 +108,12 @@ Set them in the `env` of the client's `solidworks` entry. For Claude Desktop or For Claude Code: `claude mcp add solidworks --scope user -e SOLIDWORKS_MCP_TOOL_MODE=search -- `. A name that isn't a toolset, or a mode other than `list` or `search`, stops the server at start with a message listing the valid values, rather than quietly hiding tools. `selftest` reports how many tools your settings list. +## 5. Let `execute_macro` run VBA source (off by default) + +`execute_macro` runs macro files. With **`SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1`** it also runs VBA text, such as what the `generate_vba_*` tools write, so a model can write a macro and run it in one step. The text is saved as a `.swb` file under your temp folder, and the reply names the file and repeats the source that ran. + +VBA can do anything you can do on this computer, including deleting files and running programs. Turn this on only if you trust what your client sends, and look at the source in each reply. When it's off, the call is refused as `vba_source_off` and nothing is written or run. Set it in the `env` of the client's `solidworks` entry, as above. + ## Install from source To work on the server itself, install it from a clone. You need [Python 3.13+](https://www.python.org/downloads/windows/), installed with **Add python.exe to PATH** ticked, and Git. diff --git a/docs/index.md b/docs/index.md index 88bbeba2..3a71a2a1 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. -🚀 **139 Tools** | 🤖 **Agent-Ready Workflows** | ⚡ **Automatic COM/VBA Routing** | 🧪 **Schema-Validated Prompt Runs** +🚀 **140 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 -- 139 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 140 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery - one server API surface for both simple operations and advanced workflows ### 3) Reliable Execution Path for Complex Operations diff --git a/docs/llms.txt b/docs/llms.txt index fb5f99d5..3f365e11 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -26,7 +26,7 @@ ## MCP Server Guide - [Architecture Overview](https://andrewbartels1.com/SolidworksMCP-python/user-guide/architecture/): The SolidWorks MCP Server implements an intelligent, multi-layered architecture designed to overcome the limitations of traditional COM-based SolidWorks automation while providing enterprise-grade reliability and security. -- [Tools Overview](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tools-overview/): The SolidWorks MCP Server provides 139 specialized tools for CAD automation. This page is a navigation map: each card links to the family's catalog page, which lists every tool with its inputs and a sample call. +- [Tools Overview](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tools-overview/): The SolidWorks MCP Server provides 140 specialized tools for CAD automation. This page is a navigation map: each card links to the family's catalog page, which lists every tool with its inputs and a sample call. - [Platform and Connectivity](https://andrewbartels1.com/SolidworksMCP-python/user-guide/platform-connectivity/): This guide explains how to run SolidWorks MCP when your day-to-day workflow is Linux/WSL but real SolidWorks automation must run on Windows. - [Prompting Best Practices for SolidWorks MCP](https://andrewbartels1.com/SolidworksMCP-python/user-guide/prompting-best-practices/): This guide is designed for mechanical engineers and CAD users who are new to MCP tool calling. - [Integration Testing (Real SolidWorks)](https://andrewbartels1.com/SolidworksMCP-python/user-guide/integration-testing/): This project has two test modes: a fast default mode that needs no SolidWorks, and a full mode that adds real SolidWorks integration tests. @@ -36,7 +36,7 @@ ## Tool Catalog -- [Tool Catalog — All 139 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **139 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 140 Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/): This reference documents all **140 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. - [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. - [Sketching Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/sketching/): Build 2-D sketch geometry (lines, circles, arcs, splines, polygons) and apply geometric constraints and driven dimensions. Sketches are the prerequisite for every extrusion, revolve, sweep, and loft feature. - [Drawing Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/drawing/): Create and edit 2-D technical drawings: views, section and detail views, notes, centre marks, dimensions by hand or automatically, the title block and sheet format, and a check that the drawing is complete before it is exported. Every position is in sheet millimetres from the sheet's lower-left corner. @@ -49,8 +49,9 @@ - [Automation Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/automation/): `generate_vba_code` writes a VBA macro skeleton for a step the other tools don't cover. For variants of a part, use configurations (planned in queue item 13). - [VBA Generation Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/vba-generation/): Generate and execute VBA macro code for operations that exceed the COM direct-call parameter limit (typically > 12 params). Covers extrusions, revolves, assembly inserts, mates, drawing views, batch exports, file operations, and macro recording scaffolding. - [Template Management Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/template-management/): Compare two SolidWorks template files (.prtdot, .asmdot, .drwdot) on disk. To start a part from a template, give `template` to `create_part`. -- [Macro Recording Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/macro-recording/): Run a binary SolidWorks macro (`.swp`). Record macros in SolidWorks itself (Tools > Macro > Record); to write one from a description, use `generate_vba_code`. -- [Docs Discovery Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/docs-discovery/): Look up SolidWorks API interfaces, methods and properties, with each member's parameters, return type and description. Everything is read from the SolidWorks type library installed on this machine, so the answers match your SolidWorks version and nothing is hand-typed. +- [Macro Recording Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/macro-recording/): Run a SolidWorks macro file (`.swp` or `.swb`), or VBA source when the server allows it. Record macros in SolidWorks itself (Tools > Macro > Record); to write one from a description, use `generate_vba_code`. +- [Docs Discovery Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/docs-discovery/): Look up SolidWorks API interfaces, methods and properties, with each member's parameters, return type and description, and the integer values of its enums. Everything is read from the SolidWorks type library installed on this machine, so the answers match your SolidWorks version and nothing is hand-typed. +- [Server Admin Tools](https://andrewbartels1.com/SolidworksMCP-python/user-guide/tool-catalog/server-admin/): The server's own state. These never touch SolidWorks. ## Agents and Skills diff --git a/docs/planning/roadmap.md b/docs/planning/roadmap.md index 1cf47a3c..7fe89e9c 100644 --- a/docs/planning/roadmap.md +++ b/docs/planning/roadmap.md @@ -81,7 +81,7 @@ clean-up (PR #177), and the release pipeline (PR #178, which superseded #75). | Order | Issue | What | Size | Note | |---|---|---|---|---| -| 25 | [#95](https://github.com/andrewbartels1/SolidworksMCP-python/issues/95) | `lookup_api_enum` enum value lookup | S | Needs the swconst enums indexed | +| 25 | [#95](https://github.com/andrewbartels1/SolidworksMCP-python/issues/95) | Enum value lookup, built as `get_api_enum` | S | Done 2026-11-16 (queue item 23) | | 27 | [#96](https://github.com/andrewbartels1/SolidworksMCP-python/issues/96) | Generate a runnable binary `.swp` from VBA source | L | | | 28 | [#80](https://github.com/andrewbartels1/SolidworksMCP-python/issues/80) | Prompt-to-SolidWorks tutorials | L | Rescope: SimulationXpress has no COM API (see #76 notes) | | — | [#196](https://github.com/andrewbartels1/SolidworksMCP-python/issues/196) | Parked ideas: tool-surface expansion (#23), SolidWorks-as-Code rewind, pickup and tutorial (#29–#31), agent context and testing (#13, #22), CAD-intent routing and text-to-CAD (#42, #43), live render panel (#44), Simulation wrapper and topology loop (#76, #78) | — | Closed 2026-10-31 to keep the issue list for active work; each is reopened when picked up | diff --git a/docs/user-guide/tool-catalog/analysis.md b/docs/user-guide/tool-catalog/analysis.md index 4745f45f..99cddc6f 100644 --- a/docs/user-guide/tool-catalog/analysis.md +++ b/docs/user-guide/tool-catalog/analysis.md @@ -33,14 +33,7 @@ Measure the active part or assembly's mass properties: volume, surface area, mas **Prerequisite:** Active model with solid geometry -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `model_path` | `str?` | — | `None` | Path to the model file | -| `units` | `str` | — | `metric` | Units for mass properties | -| `include_hidden` | `bool` | — | `False` | Include hidden components | -| `reference_coordinate_system` | `str?` | — | `None` | Reference coordinate system alias | +**Parameters:** none. It always measures the active model; the inputs it used to take are refused. **Sample call:** @@ -74,11 +67,9 @@ Find where the components of the active assembly overlap (Tools > Interference D | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `assembly_path` | `str?` | — | `None` | Assembly path alias | -| `check_all_components` | `bool` | — | `False` | Check all components alias | -| `include_hidden` | `bool` | — | `False` | Include hidden components | -| `components` | `List[str]` | ✅ | `` | List of component names to check for interference | -| `tolerance` | `float` | — | `0.001` | Interference detection tolerance in mm | +| `assembly_path` | `str?` | — | `null` | Assembly path alias | +| `include_hidden` | `bool` | — | `false` | Check hidden components too; by default they are left out, as in SolidWorks' own Interference Detection | +| `components` | `list[str]` | — | `[]` | List of component names to check for interference | **Sample call:** @@ -130,6 +121,21 @@ A model that doesn't match still returns `status: "success"`, because the tool i worked. `measured` holds everything that was read, including the names of the counted features. +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `mass_kg` | `float?` | — | `null` | Expected mass in kg (depends on the material) | +| `volume_mm3` | `float?` | — | `null` | Expected volume, mm³ | +| `bounding_box_mm` | `list[float]?` | — | `null` | Expected overall size [x, y, z] in mm, in model axes | +| `feature_count` | `int?` | — | `null` | Expected number of modelling features (extrudes, cuts, fillets, patterns...); sketches, the origin, folders and the three default planes are not counted | +| `solid_body_count` | `int?` | — | `null` | Expected number of solid bodies (parts) | +| `component_count` | `int?` | — | `null` | Expected top-level components (assemblies) | +| `mate_count` | `int?` | — | `null` | Expected unsuppressed mates (assemblies) | +| `no_interference` | `bool?` | — | `null` | true to require that no components overlap (assemblies) | +| `relative_tolerance` | `float` | — | `0.01` | Allowed relative error for mass and volume (0.01 = 1 %) | +| `length_tolerance_mm` | `float` | — | `0.1` | Allowed error per bounding-box axis, mm | + **Sample call:** ```json diff --git a/docs/user-guide/tool-catalog/automation.md b/docs/user-guide/tool-catalog/automation.md index 65b1ecd2..f56ac5c9 100644 --- a/docs/user-guide/tool-catalog/automation.md +++ b/docs/user-guide/tool-catalog/automation.md @@ -25,12 +25,10 @@ Write a VBA macro skeleton for an operation you describe: the SolidWorks connect | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `operation_description` | `str?` | — | `None` | Description of the operation to generate VBA for | -| `operation_type` | `str?` | — | `None` | Operation type alias | -| `parameters` | `Dict[str, Any]` | ✅ | `` | Operation parameters | -| `target_document` | `str` | — | `Part` | Target document type (Part, Assembly, Drawing) | -| `include_error_handling` | `bool` | — | `True` | Include error handling in generated code | -| `code_style` | `str` | — | `professional` | Code style (simple, professional, advanced) | +| `operation_description` | `str?` | — | `null` | Description of the operation to generate VBA for | +| `operation_type` | `str?` | — | `null` | Operation type alias | +| `target_document` | `str` | — | `"Part"` | The document type the macro runs on; it stops, printing why, on any other | +| `include_error_handling` | `bool` | — | `true` | Include error handling in generated code | **Sample call:** diff --git a/docs/user-guide/tool-catalog/docs-discovery.md b/docs/user-guide/tool-catalog/docs-discovery.md index 0f03b1a5..80e6f43e 100644 --- a/docs/user-guide/tool-catalog/docs-discovery.md +++ b/docs/user-guide/tool-catalog/docs-discovery.md @@ -1,6 +1,6 @@ # Docs Discovery Tools -Look up SolidWorks API interfaces, methods and properties, with each member's parameters, return type and description. Everything is read from the SolidWorks type library installed on this machine, so the answers match your SolidWorks version and nothing is hand-typed. +Look up SolidWorks API interfaces, methods and properties, with each member's parameters, return type and description, and the integer values of its enums. Everything is read from the SolidWorks type library installed on this machine, so the answers match your SolidWorks version and nothing is hand-typed. > **Prerequisite:** SolidWorks installed (it need not be running), on Windows with pywin32. > @@ -8,7 +8,7 @@ Look up SolidWorks API interfaces, methods and properties, with each member's pa > > The year comes from the server's `--year` start-up argument (setup writes it), else the newest installed SolidWorks. Every response reports the `year` and `type_library_version` that answered, and `index_status`: `ready` (saved index), `rebuilt` (built for this call) or `unavailable`. -**Total tools in this category: 5** +**Total tools in this category: 6** --- @@ -100,6 +100,30 @@ Look up one SolidWorks API method or property: parameters, return type, descript --- +### `get_api_enum` + +Look up a SolidWorks API enum's members and their integer values. + +Give the enum or one of its members; a member's name returns its whole enum with `matched_member` set. The values come from SolidWorks' constants type library (`swconst.tlb`), so a call that takes an enum value never needs a guessed number. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | An enum (`swUnitSystem_e`) or member (`swUnitSystem_IPS`); case does not matter | +| `year` | `int?` | — | `null` | SolidWorks year to answer for; usually unset (the server's `--year`) | +| `index_file` | `str?` | — | `null` | A saved index to answer from instead, e.g. copied from another machine | + +**Sample call:** + +```json +{ "name": "swUnitSystem_e" } +``` + +Returns `result.members`: `[{"name": "swUnitSystem_CGS", "value": 1}, {"name": "swUnitSystem_MKS", "value": 2}, {"name": "swUnitSystem_IPS", "value": 3}, ...]`. + +--- + ### `find_related_api_members` Find SolidWorks API members related to an interface or member name. diff --git a/docs/user-guide/tool-catalog/drawing-analysis.md b/docs/user-guide/tool-catalog/drawing-analysis.md index eeb4d10d..a59926c0 100644 --- a/docs/user-guide/tool-catalog/drawing-analysis.md +++ b/docs/user-guide/tool-catalog/drawing-analysis.md @@ -15,10 +15,17 @@ Compare two drawing files on disk: whether they are byte-identical, and how thei **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `drawing_version_1` | `str` | ✅ | | Full path to the first drawing file | +| `drawing_version_2` | `str` | ✅ | | Full path to the second drawing file | + **Sample call:** ```json -{} +{"drawing_version_1": "C:\\Temp\\mcp_demo\\plate_v1.SLDDRW", "drawing_version_2": "C:\\Temp\\mcp_demo\\plate_v2.SLDDRW"} ``` --- diff --git a/docs/user-guide/tool-catalog/drawing-automation.md b/docs/user-guide/tool-catalog/drawing-automation.md index 58693615..d16257eb 100644 --- a/docs/user-guide/tool-catalog/drawing-automation.md +++ b/docs/user-guide/tool-catalog/drawing-automation.md @@ -14,6 +14,13 @@ Bring the model's dimensions into the active drawing's views, each dimension sho **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `view_name` | `str?` | — | `null` | One view, e.g. 'Drawing View1'; every orthographic view when omitted. Find names with list_drawing_views. | +| `include_hole_wizard` | `bool` | — | `true` | Also import Hole Wizard location dimensions | + **Sample call:** ```json @@ -28,6 +35,12 @@ Move drawing dimensions out of their views into tidy rows so nothing overlaps, t **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `view_name` | `str?` | — | `null` | Only move this view's dimensions, e.g. 'Drawing View1'; every view when omitted. The overlap check always covers the whole sheet. | + **Sample call:** ```json @@ -42,10 +55,20 @@ Insert a bill-of-materials table for an assembly view on the active drawing. **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `view_name` | `str` | ✅ | | A view of an assembly, e.g. 'Drawing View1' | +| `template_path` | `str?` | — | `null` | .sldbomtbt template; bom-standard when omitted | +| `bom_type` | `str` | — | `"top_level_only"` | BOM structure | +| `x_mm` | `float?` | — | `null` | Table X on the sheet (mm); the sheet's BOM anchor when omitted | +| `y_mm` | `float?` | — | `null` | Table Y on the sheet (mm) | + **Sample call:** ```json -{} +{"view_name": "Drawing View1"} ``` --- @@ -56,10 +79,17 @@ Set the active drawing sheet's scale, e.g. 1:2; views that use the sheet scale f **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `numerator` | `float` | ✅ | | e.g. 1 for 1:2 | +| `denominator` | `float` | ✅ | | e.g. 2 for 1:2 | + **Sample call:** ```json -{} +{"numerator": 1, "denominator": 2} ``` --- @@ -70,10 +100,78 @@ Create a complete A3 drawing of a part or assembly in one call, and save it with **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `model_path` | `str` | ✅ | | Full path to the .SLDPRT or .SLDASM | +| `output_dir` | `str?` | — | `null` | Where to save the drawing; the model's folder when omitted | +| `title` | `str?` | — | `null` | Short title, e.g. 'Mounting Plate - Rev A'; the file name when omitted | +| `subtitle` | `str?` | — | `null` | Sheet title, e.g. 'Base support' | +| `drawing_number` | `str?` | — | `null` | DWG NO., also the drawing file name, e.g. 'MP-RevA-01' | +| `author` | `str` | — | `""` | DRAWN name | +| `revision` | `str` | — | `"A"` | Revision letter | +| `company` | `str` | — | `""` | Company name | +| `notes` | `list[str]` | — | `[]` | Extra note lines (material, process, connections); 3-7 lines in total | +| `include_isometric` | `bool` | — | `true` | Add an isometric view | +| `write_model_properties` | `bool` | — | `true` | Write Description/Material/Weight into the model so the title block shows them, and save it | +| `title_block_text_height_mm` | `float?` | — | `null` | Largest text height (mm) for the title block's DWG NO. and TITLE, e.g. 3 for smaller text. By default they keep the sheet format's height and are only shrunk to fit their boxes. | +| `include_bom` | `bool` | — | `false` | Assemblies only: put a bill of materials in the top of the isometric view's cell, with the isometric fitted below it | + **Sample call:** ```json -{} +{"model_path": "C:\\Temp\\mcp_demo\\part.SLDPRT"} +``` + +--- + +--- + +### `add_gtol` + +Add a GD&T feature control frame to the active drawing, e.g. position Ø0.2 (M) to A|B|C. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `characteristic` | `str` | ✅ | | Geometric characteristic | +| `tolerance` | `float` | ✅ | | Tolerance value, e.g. 0.2 | +| `diameter_zone` | `bool` | — | `false` | Cylindrical zone: Ø before the tolerance | +| `material_condition` | `str` | — | `"none"` | Material condition modifier | +| `datums` | `list[str]` | — | `[]` | Datum letters, primary first | +| `x_mm` | `float` | — | `0.0` | Frame X on the sheet (mm); not used when on a dimension | +| `y_mm` | `float` | — | `0.0` | Frame Y on the sheet (mm); not used when on a dimension | +| `attach_x_mm` | `float?` | — | `null` | X of a point on the edge the leader points to | +| `attach_y_mm` | `float?` | — | `null` | Y of a point on the edge the leader points to | +| `dimension_view` | `str?` | — | `null` | View holding the dimension to attach to | +| `dimension_name` | `str?` | — | `null` | Model dimension to attach to, e.g. 'D3@Sketch1' (see list_model_dimensions); the frame sits under its text | + +**Sample call:** + +```json +{"characteristic": "position", "tolerance": 0.2, "diameter_zone": true, "datums": ["A", "B"], "dimension_view": "Drawing View1", "dimension_name": "D3@Sketch1"} ``` --- + +### `add_datum_tag` + +Add a datum feature symbol (A, B, C, ...) on an edge of the active drawing. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `label` | `str` | ✅ | | Datum letter, e.g. 'A' | +| `attach_x_mm` | `float` | ✅ | | X of a point on the edge it marks (mm) | +| `attach_y_mm` | `float` | ✅ | | Y of a point on the edge it marks (mm) | +| `x_mm` | `float` | ✅ | | Tag X on the sheet (mm) | +| `y_mm` | `float` | ✅ | | Tag Y on the sheet (mm) | + +**Sample call:** + +```json +{"label": "A", "attach_x_mm": 60, "attach_y_mm": 120, "x_mm": 60, "y_mm": 135} +``` diff --git a/docs/user-guide/tool-catalog/drawing.md b/docs/user-guide/tool-catalog/drawing.md index 2afe4e11..28e39e93 100644 --- a/docs/user-guide/tool-catalog/drawing.md +++ b/docs/user-guide/tool-catalog/drawing.md @@ -31,10 +31,7 @@ Place one named view of a part or assembly on the active drawing sheet. **Sample call:** ```json -{ - "model_path": null, - "view_type": "example" -} +{"model_path": "C:\\Temp\\mcp_demo\\part.SLDPRT", "view_type": "orthographic", "orientation": "front"} ``` --- @@ -223,6 +220,12 @@ Read-only. Errors fail the drawing: `view_off_sheet` and `dangling_annotation`. **Returns:** `passed`, `errors`, `warnings`, `findings` (each `rule`, `severity`, `message` and maybe `view`), `views` and `report` (the facts read: sheet size, view outlines and dimension counts, title block, BOM, dangling count). +**Sample call:** + +```json +{} +``` + --- ### `create_technical_drawing` @@ -235,14 +238,8 @@ Place a model's three standard views (front, top and side) on the active drawing | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `template` | `str?` | — | `None` | Drawing template file path | -| `model_file` | `str?` | — | `None` | Model file to create drawing from | -| `sheet_size` | `str` | — | `A3` | Sheet size | -| `title` | `str` | — | `` | Drawing title | -| `output_path` | `str?` | — | `None` | Output drawing path | -| `sheet_format` | `str?` | — | `None` | Sheet format | -| `scale` | `str` | — | `1:1` | Drawing scale | -| `auto_populate_views` | `bool` | — | `False` | Automatically populate standard views | +| `model_file` | `str?` | — | `null` | Model file (.sldprt or .sldasm) to draw | +| `projection` | `str` | — | `"third_angle"` | Projection the views are laid out in | **Sample call:** diff --git a/docs/user-guide/tool-catalog/engineering-data.md b/docs/user-guide/tool-catalog/engineering-data.md index 42ea4dc5..925f2064 100644 --- a/docs/user-guide/tool-catalog/engineering-data.md +++ b/docs/user-guide/tool-catalog/engineering-data.md @@ -14,6 +14,12 @@ List every dimension in the active part or assembly with its full name and value **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `feature_name` | `str?` | — | `null` | Only list this feature's dimensions, e.g. 'Boss-Extrude1'. Omit to list every dimension in the model. | + **Sample call:** ```json @@ -37,9 +43,7 @@ Measure faces, edges or vertices of the active model with SolidWorks' Measure to **Sample call:** ```json -{ - "entities": [] -} +{"entities": ["face:0,10,0", "face:0,0,0"]} ``` --- @@ -116,6 +120,12 @@ List the materials in the installed SolidWorks material libraries. **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `search` | `str?` | — | `null` | Case-insensitive filter on material name or classification, e.g. 'steel' or '6061' | + **Sample call:** ```json @@ -130,6 +140,12 @@ Read the active document's custom properties, such as PartNo, Description or Rev **Prerequisite:** SolidWorks running +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `configuration` | `str?` | — | `null` | Configuration-specific properties; file-level (what title blocks usually read) when omitted | + **Sample call:** ```json @@ -155,10 +171,7 @@ Create or overwrite one text custom property on the active document, e.g. PartNo **Sample call:** ```json -{ - "name": "MCP_Demo_Part", - "value": 50.0 -} +{"name": "PartNo", "value": "BR-001"} ``` --- @@ -178,9 +191,7 @@ Export the active sheet-metal part's flat pattern to DXF or DWG, for laser or wa **Sample call:** ```json -{ - "file_path": "C:\\Temp\\mcp_demo\\part.sldprt" -} +{"file_path": "C:\\Temp\\mcp_demo\\bracket.dxf"} ``` --- diff --git a/docs/user-guide/tool-catalog/export.md b/docs/user-guide/tool-catalog/export.md index fa247fe1..18daf35e 100644 --- a/docs/user-guide/tool-catalog/export.md +++ b/docs/user-guide/tool-catalog/export.md @@ -18,9 +18,8 @@ Export the active document to STEP, like File > Save As with the STEP type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `file_path` | `str` | ✅ | `` | Full path for the exported file | -| `format_type` | `str` | ✅ | `` | Export format (step, iges, stl, pdf, dwg, jpg, png) | -| `options` | `Dict[str, Any]?` | — | `None` | Format-specific export options | +| `file_path` | `str` | ✅ | | Full path for the exported file | +| `format_type` | `str?` | — | `null` | Not needed: the file extension sets the format; defaults to the tool's own format | **Sample call:** @@ -43,9 +42,8 @@ Export the active document to IGES, like File > Save As with the IGES type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `file_path` | `str` | ✅ | `` | Full path for the exported file | -| `format_type` | `str` | ✅ | `` | Export format (step, iges, stl, pdf, dwg, jpg, png) | -| `options` | `Dict[str, Any]?` | — | `None` | Format-specific export options | +| `file_path` | `str` | ✅ | | Full path for the exported file | +| `format_type` | `str?` | — | `null` | Not needed: the file extension sets the format; defaults to the tool's own format | **Sample call:** @@ -68,9 +66,8 @@ Export the active document to STL, like File > Save As with the STL type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `file_path` | `str` | ✅ | `` | Full path for the exported file | -| `format_type` | `str` | ✅ | `` | Export format (step, iges, stl, pdf, dwg, jpg, png) | -| `options` | `Dict[str, Any]?` | — | `None` | Format-specific export options | +| `file_path` | `str` | ✅ | | Full path for the exported file | +| `format_type` | `str?` | — | `null` | Not needed: the file extension sets the format; defaults to the tool's own format | **Sample call:** @@ -93,9 +90,8 @@ Export the active document to PDF, like File > Save As with the PDF type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `file_path` | `str` | ✅ | `` | Full path for the exported file | -| `format_type` | `str` | ✅ | `` | Export format (step, iges, stl, pdf, dwg, jpg, png) | -| `options` | `Dict[str, Any]?` | — | `None` | Format-specific export options | +| `file_path` | `str` | ✅ | | Full path for the exported file | +| `format_type` | `str?` | — | `null` | Not needed: the file extension sets the format; defaults to the tool's own format | **Sample call:** @@ -118,9 +114,8 @@ Export the active document to DWG, like File > Save As with the DWG type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `file_path` | `str` | ✅ | `` | Full path for the exported file | -| `format_type` | `str` | ✅ | `` | Export format (step, iges, stl, pdf, dwg, jpg, png) | -| `options` | `Dict[str, Any]?` | — | `None` | Format-specific export options | +| `file_path` | `str` | ✅ | | Full path for the exported file | +| `format_type` | `str?` | — | `null` | Not needed: the file extension sets the format; defaults to the tool's own format | **Sample call:** diff --git a/docs/user-guide/tool-catalog/file-management.md b/docs/user-guide/tool-catalog/file-management.md index 9054563c..6183e1ba 100644 --- a/docs/user-guide/tool-catalog/file-management.md +++ b/docs/user-guide/tool-catalog/file-management.md @@ -22,8 +22,8 @@ Save the active document, to its own path or to a new path in its own format. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `force_save` | `bool` | — | `True` | Force save even if no changes | -| `file_path` | `str?` | — | `None` | Optional output path. If omitted, saves the current active document. | +| `file_path` | `str?` | — | `null` | Optional new path, ending in the active document's extension (.sldprt, .sldasm or .slddrw). If omitted, saves the active document to its own path. | +| `overwrite` | `bool` | — | `false` | Replace a file already at file_path. Off by default. | **Sample call:** @@ -134,7 +134,8 @@ List the feature tree of the active part or assembly, in order. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `include_suppressed` | `bool` | — | `False` | Include suppressed features in the returned list | +| `include_suppressed` | `bool` | — | `false` | Include suppressed features in the returned list | +| `max_assembly_depth` | `int` | — | `2` | For Assembly documents, how many levels of sub-assembly to recurse into when flattening component features. Ignored for Part documents. | **Sample call:** @@ -210,7 +211,13 @@ Add a configuration to the active part or assembly, e.g. a long and a short vers Make a configuration of the active model the active one, and rebuild. -**Prerequisite:** Active part or assembly with that configuration. Beta. +**Prerequisite:** Active part or assembly with that configuration. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | The configuration's name, e.g. 'Default' | **Sample call:** @@ -224,7 +231,13 @@ Make a configuration of the active model the active one, and rebuild. Delete a configuration of the active model; not the active one or the only one. -**Prerequisite:** Active part or assembly with that configuration. Beta. +**Prerequisite:** Active part or assembly with that configuration. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | The configuration's name, e.g. 'Default' | **Sample call:** @@ -290,6 +303,13 @@ Save the active part in place, or as a new .sldprt with the target path checked **Prerequisite:** Active Part document +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `file_path` | `str?` | — | `null` | Optional output path. If omitted, saves the active part to its existing location. | +| `overwrite` | `bool` | — | `false` | Overwrite existing file | + **Sample call:** ```json @@ -306,6 +326,14 @@ Save the active assembly in place, or as a new .sldasm, optionally copying the p **Prerequisite:** Active Assembly document +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `file_path` | `str?` | — | `null` | Optional output path. If omitted, saves the active assembly to its existing location. | +| `overwrite` | `bool` | — | `false` | Overwrite existing file | +| `include_references` | `bool` | — | `false` | When true and file_path is set, copy referenced assembly files into the target folder. | + **Sample call:** ```json @@ -454,10 +482,7 @@ Save one solid body of the active multibody part as a new part file (Insert > Fe **Sample call:** ```json -{ - "body_name": "Boss-Extrude1", - "file_path": "C:\parts\bracket_body.sldprt" -} +{"body_name": "Boss-Extrude1", "file_path": "C:\\Temp\\mcp_demo\\body.SLDPRT"} ``` --- diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index 49e2d718..c7d3f013 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,6 +1,6 @@ -# Tool Catalog — All 139 Tools +# Tool Catalog — All 140 Tools -This reference documents all **139 MCP tools** registered by the SolidWorks MCP server. +This reference documents all **140 MCP tools** registered by the SolidWorks MCP server. Each section covers one functional category with parameter tables and copy-paste sample calls. ![Tool categories overview — 109 tools across 12 functional areas](../../assets/images/tool-categories-overview.svg) @@ -11,7 +11,7 @@ Each section covers one functional category with parameter tables and copy-paste |----------|-------|-------------| | [Modeling Tools](modeling.md) | 42 | Parts, assemblies and drawings: extrusions, revolves, sweeps, lofts, cuts, Hole Wizard holes, cosmetic threads, shells, drafts, ribs, sheet metal (flanges, bends, the flat pattern), fillets, chamfers, patterns, reference geometry, mates, dimensions, feature renaming and the document unit system. | | [Sketching Tools](sketching.md) | 19 | Sketches on a plane or a flat face: lines, circles, arcs, splines, polygons, relations, dimensions, offsets, mirrors and patterns. | -| [Drawing Tools](drawing.md) | 13 | Drawings from a model: views, notes and centre marks. Section and detail views, dimensions, the title block and a drawing check are planned. | +| [Drawing Tools](drawing.md) | 13 | Drawings from a model: standard, section and detail views, dimensions, notes, centre marks, the sheet format and title block, and a drawing check. | | [Drawing Analysis Tools](drawing-analysis.md) | 1 | Compare two versions of a drawing file. | | [Drawing Automation Tools](drawing-automation.md) | 7 | Model dimensions laid out without overlaps, datum tags, tolerances, BOM tables, sheet scale and complete A3 drawings. | | [Engineering Data Tools](engineering-data.md) | 8 | Read and edit the data drawings and BOMs are built from: model dimensions by name, measurements, materials, custom properties and sheet-metal flat patterns. | @@ -22,10 +22,11 @@ Each section covers one functional category with parameter tables and copy-paste | [VBA Generation Tools](vba-generation.md) | 10 | VBA macro text for steps the tools don't cover. | | [Template Management Tools](template-management.md) | 1 | Compare two template files. | | [Macro Recording Tools](macro-recording.md) | 1 | Run a binary SolidWorks macro (`.swp`). | -| [Docs Discovery Tools](docs-discovery.md) | 5 | Look up SolidWorks API interfaces and member signatures, read from the installed SolidWorks type library. | +| [Docs Discovery Tools](docs-discovery.md) | 6 | Look up SolidWorks API interfaces, member signatures and enum values, read from the installed SolidWorks type libraries. | +| [Server Admin Tools](server-admin.md) | 1 | Reset the circuit breaker the server uses to pause a failing operation. | -`reset_circuit_breaker` (server admin) has no page of its own; see the -[progress page](../../progress.md). Eight tools are deprecated: each one's +Every tool's support level is on the [progress page](../../progress.md). +Eight tools are deprecated: each one's section opens with "Deprecated" and names its replacement. ## Standard Response Envelope diff --git a/docs/user-guide/tool-catalog/macro-recording.md b/docs/user-guide/tool-catalog/macro-recording.md index db1a8369..32d25a04 100644 --- a/docs/user-guide/tool-catalog/macro-recording.md +++ b/docs/user-guide/tool-catalog/macro-recording.md @@ -1,6 +1,6 @@ # Macro Recording Tools -Run a binary SolidWorks macro (`.swp`). Record macros in SolidWorks itself +Run a SolidWorks macro file (`.swp` or `.swb`), or VBA source when the server allows it. Record macros in SolidWorks itself (Tools > Macro > Record); to write one from a description, use `generate_vba_code`. > **Prerequisite:** SolidWorks running. Macro execution requires a valid .swp file path. @@ -11,7 +11,9 @@ Run a binary SolidWorks macro (`.swp`). Record macros in SolidWorks itself ### `execute_macro` -Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, calling its `main` procedure once. +Run a SolidWorks macro (.swp, or legacy .swb), or VBA source text, in the running SolidWorks, calling its `main` procedure. + +VBA source runs only when the server was started with `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1` ([why it's off by default](../../getting-started/installation.md#5-let-execute_macro-run-vba-source-off-by-default)); otherwise it is refused as `vba_source_off`. The source is saved as a `.swb` file, and the reply gives `source_file` and the `vba_source` that ran. **Prerequisite:** SolidWorks running @@ -19,16 +21,13 @@ Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `macro_path` | `str?` | — | `None` | Path to a binary macro (.swp or .swb) | -| `macro_file` | `str?` | — | `None` | Alternative to macro_path (.swp or .swb) | -| `parameters` | `Dict[str, Any]` | ✅ | `` | Macro parameters | -| `target_file` | `str?` | — | `None` | Target file | -| `execution_mode` | `str?` | — | `None` | Execution mode | -| `pause_on_error` | `bool` | — | `False` | Pause on error | -| `log_execution` | `bool` | — | `False` | Log execution | -| `execution_parameters` | `Dict[str, Any]?` | — | `None` | Execution parameters | -| `repeat_count` | `int` | — | `1` | Number of times to execute | -| `pause_between_runs` | `float` | — | `0.0` | Pause between executions in seconds | +| `macro_path` | `str?` | — | `null` | Path to a SolidWorks macro file (.swp, or legacy .swb). For VBA source text, use vba_source. | +| `macro_file` | `str?` | — | `null` | Alternative to macro_path (.swp or .swb) | +| `vba_source` | `str?` | — | `null` | The macro's VBA text, instead of a file: written to a .swb and run. Only when the server allows it (SOLIDWORKS_MCP_ALLOW_VBA_SOURCE) | +| `proc_name` | `str` | — | `"main"` | The macro procedure to call; main by default | +| `repeat_count` | `int` | — | `1` | How many times to run the macro (1-100); it stops at the first failure | +| `pause_between_runs` | `float` | — | `0.0` | Seconds to wait between runs | +| `dialog_timeout` | `float` | — | `30.0` | Seconds a dialog the macro opens (MsgBox, form, prompt) may wait before it is answered with Cancel (or its only button) and the run fails as `macro_waited_for_user` | **Sample call:** diff --git a/docs/user-guide/tool-catalog/modeling.md b/docs/user-guide/tool-catalog/modeling.md index c888b9b5..77e6175d 100644 --- a/docs/user-guide/tool-catalog/modeling.md +++ b/docs/user-guide/tool-catalog/modeling.md @@ -86,9 +86,8 @@ Create a new, empty assembly document and make it active, ready for `insert_comp | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `name` | `str` | ✅ | `` | Name for the new assembly | -| `template` | `str?` | — | `None` | Assembly template file path | -| `components` | `List[str]` | ✅ | `` | Component list | +| `name` | `str` | ✅ | | A label for your own reference; SolidWorks names the new assembly itself (Assem1, ...) and the file takes the name of the path you save it to with save_assembly | +| `template` | `str?` | — | `null` | Assembly template (.asmdot) path; omit to use the SolidWorks default | **Sample call:** @@ -111,10 +110,8 @@ Create a new, empty drawing document and make it active. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `name` | `str` | ✅ | `` | Name for the new drawing | -| `template` | `str?` | — | `None` | Drawing template file path | -| `model_path` | `str?` | — | `None` | Source model path | -| `sheet_format` | `str?` | — | `None` | Sheet format template | +| `name` | `str` | ✅ | | A label for your own reference; SolidWorks names the new drawing itself (Draw1, ...) and the file takes the name of the path you save it to with save_file | +| `template` | `str?` | — | `null` | Drawing template (.drwdot) path; omit to use the SolidWorks default | **Sample call:** @@ -156,17 +153,17 @@ Extrude the sketch you just closed into a solid boss, added to the active part. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `sketch_name` | `str` | ✅ | `` | Sketch name to extrude | -| `depth` | `float` | ✅ | `` | Extrusion depth in millimeters | -| `direction` | `str` | — | `blind` | Extrusion direction | -| `reverse` | `bool?` | — | `None` | Reverse direction alias | +| `sketch_name` | `str?` | — | `null` | Sketch to use, by its name in the feature tree (e.g. "Sketch2"); omit to use the sketch `exit_sketch` closed last | +| `depth` | `float` | ✅ | | Extrusion depth in millimeters | +| `reverse` | `bool?` | — | `null` | Reverse direction alias | | `draft_angle` | `float` | — | `0.0` | Draft angle in degrees | -| `reverse_direction` | `bool` | — | `False` | Reverse extrusion direction | -| `both_directions` | `bool` | — | `False` | Extrude in both directions | -| `thin_feature` | `bool` | — | `False` | Create as thin wall feature | -| `thin_thickness` | `float?` | — | `None` | Thickness for thin wall feature in mm | -| `end_condition` | `str` | — | `Blind` | End condition type | -| `merge_result` | `bool` | — | `True` | Merge with existing geometry | +| `reverse_direction` | `bool` | — | `false` | Reverse extrusion direction | +| `both_directions` | `bool` | — | `false` | Extrude symmetrically about the sketch plane (mid-plane): `depth` is the total thickness, half on each side | +| `thin_feature` | `bool` | — | `false` | Make a thin wall of `thin_thickness` from the sketch's outline; the sketch may be an open chain (a bent plate's centreline) | +| `thin_thickness` | `float?` | — | `null` | Wall thickness in mm; required with thin_feature | +| `thin_side` | `str` | — | `"one_side"` | Which side of the sketch line the thin wall grows on: one_side, other_side, or mid_plane (half each side) | +| `end_condition` | `str` | — | `"Blind"` | End condition type | +| `merge_result` | `bool` | — | `true` | Merge with existing geometry | **Sample call:** @@ -189,15 +186,14 @@ Revolve the sketch you just closed around the centreline drawn in it, adding a s | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `sketch_name` | `str` | ✅ | `` | Sketch name to revolve | -| `axis_entity` | `str` | ✅ | `` | Axis entity for the revolve | -| `angle` | `float` | ✅ | `` | Revolve angle in degrees | -| `direction` | `str` | — | `one_direction` | Revolve direction | -| `reverse_direction` | `bool` | — | `False` | Reverse revolve direction | -| `both_directions` | `bool` | — | `False` | Revolve in both directions | -| `thin_feature` | `bool` | — | `False` | Create as thin wall feature | -| `thin_thickness` | `float?` | — | `None` | Thickness for thin wall feature in mm | -| `merge_result` | `bool` | — | `True` | Merge with existing geometry | +| `sketch_name` | `str?` | — | `null` | Sketch to use, by its name in the feature tree (e.g. "Sketch2"); omit to use the sketch `exit_sketch` closed last | +| `axis_entity` | `str?` | — | `null` | A reference axis to revolve about, by its name in the feature tree (e.g. "Axis1" from `create_axis`); omit to use the centreline drawn in the sketch | +| `angle` | `float` | ✅ | | Revolve angle in degrees | +| `reverse_direction` | `bool` | — | `false` | Reverse revolve direction | +| `both_directions` | `bool` | — | `false` | Revolve in both directions | +| `thin_feature` | `bool` | — | `false` | Create as thin wall feature | +| `thin_thickness` | `float?` | — | `null` | Thickness for thin wall feature in mm | +| `merge_result` | `bool` | — | `true` | Merge with existing geometry | **Sample call:** @@ -227,7 +223,7 @@ Read one dimension of the active model by its full name, e.g. "D1@Sketch1". **Sample call:** ```json -{} +{"name": "D1@Boss-Extrude1"} ``` --- @@ -358,6 +354,12 @@ The edges become the live selection, so a following `add_chamfer` / `add_fillet` } ``` +**Sample call:** + +```json +{"side": "top", "edge_type": "linear"} +``` + --- ### `rebuild_model` @@ -534,14 +536,15 @@ Repeat features of the active part in a row or a grid, e.g. a row of holes. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `features` | `list[str]` | ✅ | `` | Names of the features to repeat | -| `direction` | `list[float]` or `str` | ✅ | `` | `[x, y, z]` mm on a straight edge, or an axis name | -| `count` | `int` | ✅ | `` | Instances along it, the original included (2+) | -| `spacing` | `float` | ✅ | `` | Distance between instances, mm | -| `direction2` | `list[float]` or `str` | — | `None` | Second direction, for a grid | +| `features` | `list[str]` | — | `[]` | Names of the features to repeat. At least one required. | +| `direction` | `list[float] | str` | ✅ | | First direction: [x, y, z] in mm on a straight edge, or an axis name such as 'Axis1' | +| `count` | `int` | ✅ | | Instances along the first direction, original included (2+) | +| `spacing` | `float` | ✅ | | Distance between instances, mm | +| `direction2` | `list[float] | str?` | — | `null` | Second direction, as `direction`; omit for one row | | `count2` | `int` | — | `1` | Instances along the second direction | -| `spacing2` | `float` | — | `0` | Spacing along the second direction, mm | -| `reverse`, `reverse2` | `bool` | — | `false` | Flip a direction | +| `spacing2` | `float` | — | `0.0` | Spacing along the second direction, mm | +| `reverse` | `bool` | — | `false` | Flip the first direction | +| `reverse2` | `bool` | — | `false` | Flip the second direction | **Sample call:** @@ -728,3 +731,331 @@ Add a rib from a sketched line, stiffening a wall or the inside of a shell. ``` --- + +--- + +### `create_cut_extrude` + +Cut material from the active part with a closed sketch profile: holes, slots, windows. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `depth` | `float` | ✅ | | Cut depth in millimeters | +| `draft_angle` | `float` | — | `0.0` | Draft angle in degrees | +| `reverse_direction` | `bool` | — | `false` | Cut against the sketch normal instead of along it. Usually not needed: if the requested direction finds no material, the cut is retried the other way and the reply sets direction_flipped | +| `end_condition` | `str` | — | `"Blind"` | 'Blind' (cut 'depth' mm), 'ThroughAll' (through the body, one way) or 'ThroughAllBoth' (through the body both ways, for a sketch inside the body) | +| `both_directions` | `bool` | — | `false` | With end_condition 'ThroughAll', cut through the body both ways (same as 'ThroughAllBoth') | +| `sketch_name` | `str?` | — | `null` | Sketch to cut from, e.g. 'Sketch3'. If omitted, the sketch most recently created/exited in this session is used, but only if it still exists in the model — there is no other fallback. Pass this explicitly whenever more than one unconsumed sketch could exist, or after any operation that might have changed the active sketch. | + +**Sample call:** + +```json +{"depth": 5, "end_condition": "Blind"} +``` + +--- + +### `add_fillet` + +Round edges of the active part with a constant-radius fillet. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `radius` | `float` | ✅ | | Fillet radius in millimeters | +| `edge_names` | `list[str]` | — | `[]` | Edges (or faces) to fillet. Accepts a topology name (e.g. 'Edge<1>'), a coordinate hint in metres ('x,y,z') to select the nearest edge, or 'face:x,y,z' to select a whole face — which fillets every edge bounding it in one call. Prefer 'face:' over a coordinate on an edge that sits exactly on a shared boundary between two faces (e.g. a hole rim flush with a flat face): the nearest-edge match there can silently resolve to a different, unrelated edge. Leave empty to use whatever is *currently selected* in the live SolidWorks UI (e.g. entities read back via get_selected_entities and left selected) without touching the selection — this is the most reliable option when the user has hand-picked specific edges, since it never round-trips through coordinates. Falls back to filleting all edges only if nothing at all is selected. | + +**Sample call:** + +```json +{"radius": 2, "edge_names": ["Edge1", "Edge2"]} +``` + +--- + +### `add_chamfer` + +Bevel edges of the active part with a chamfer: `distance` along one face at `angle` (45 by default). + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `distance` | `float` | ✅ | | Chamfer distance in millimeters, along one of the edge's faces | +| `angle` | `float` | — | `45.0` | Chamfer angle in degrees, between 0 and 90; 45 makes both legs equal to distance | +| `flip` | `bool` | — | `false` | Measure distance along the edge's other face (swaps the long and short legs of an angled chamfer) | +| `edge_names` | `list[str]` | — | `[]` | Edges (or faces) to chamfer. Accepts a topology name (e.g. 'Edge<1>'), a coordinate hint in metres ('x,y,z') to select the nearest edge, or 'face:x,y,z' to select a whole face — which chamfers every edge bounding it in one call. Prefer 'face:' over a coordinate on an edge that sits exactly on a shared boundary between two faces (e.g. a hole rim flush with a flat face): the nearest-edge match there can silently resolve to a different, unrelated edge. Leave empty to use whatever is *currently selected* in the live SolidWorks UI (e.g. entities read back via get_selected_entities and left selected) without touching the selection — this is the most reliable option when the user has hand-picked specific edges, since it never round-trips through coordinates. Falls back to chamfering all edges only if nothing at all is selected. | + +**Sample call:** + +```json +{"distance": 1, "angle": 45, "edge_names": ["Edge1"]} +``` + +--- + +### `create_sweep` + +Sweep a closed profile sketch along a path sketch to make a solid (Insert > Boss/Base > Sweep). + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `path` | `str` | ✅ | | Name or ID of the sweep path | +| `twist_along_path` | `bool` | — | `false` | Twist along path | +| `twist_angle` | `float` | — | `0.0` | Twist angle in degrees | +| `merge_result` | `bool` | — | `true` | Merge with existing geometry | + +**Sample call:** + +```json +{"path": "Sketch2"} +``` + +--- + +### `create_loft` + +Loft a solid through two or more closed profile sketches, in order (Insert > Boss/Base > Loft). + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `profiles` | `list[str]` | ✅ | | List of profile names or IDs | +| `guide_curves` | `list[str]?` | — | `null` | List of guide curve names or IDs | +| `start_tangent` | `str?` | — | `null` | Start tangent condition | +| `end_tangent` | `str?` | — | `null` | End tangent condition | +| `merge_result` | `bool` | — | `true` | Merge with existing geometry | + +**Sample call:** + +```json +{"profiles": ["Sketch1", "Sketch2"]} +``` + +--- + +### `insert_component` + +Insert a part or sub-assembly file into the active assembly at a position in mm. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `file_path` | `str` | ✅ | | Absolute path to the .sldprt or .sldasm to insert | +| `x` | `float` | — | `0.0` | X position in millimetres | +| `y` | `float` | — | `0.0` | Y position in millimetres | +| `z` | `float` | — | `0.0` | Z position in millimetres | + +**Sample call:** + +```json +{"file_path": "C:\\Temp\\mcp_demo\\pin.SLDPRT", "x": 0, "y": 0, "z": 0} +``` + +--- + +### `add_mate` + +Mate two components of the active assembly: coincident, concentric, parallel, perpendicular, tangent, distance or angle. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `component_a` | `str` | ✅ | | First component instance name, as reported by list_components | +| `component_b` | `str` | ✅ | | Second component instance name | +| `entity_a` | `str?` | — | `null` | Named reference plane or axis on the first component, e.g. 'Front Plane'; defaults to 'Front Plane' when face_a is not given either | +| `entity_b` | `str?` | — | `null` | Named reference plane or axis on the second component; defaults to 'Front Plane' when face_b is not given either | +| `face_a` | `list[float]?` | — | `null` | [x, y, z] in mm on a face of the first component, in that part's own coordinates (as it was modelled), instead of entity_a: e.g. a point on a pin's round face for a concentric mate | +| `face_b` | `list[float]?` | — | `null` | [x, y, z] in mm on a face of the second component, in its own part coordinates, instead of entity_b | +| `mate_type` | `str` | — | `"coincident"` | coincident, concentric, perpendicular, parallel, tangent, distance or angle | +| `alignment` | `str` | — | `"aligned"` | aligned, anti_aligned or closest | +| `distance` | `float` | — | `0.0` | Distance in millimetres, for a distance mate | +| `angle` | `float` | — | `0.0` | Angle in degrees, for an angle mate | + +**Sample call:** + +```json +{"component_a": "base-1", "component_b": "pin-1", "mate_type": "concentric", "face_a": [0, 10, 0], "face_b": [0, 5, 0]} +``` + +--- + +### `set_component_state` + +Fix or float a component of the active assembly, or make a sub-assembly rigid or flexible. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `component` | `str` | ✅ | | Component instance name, as reported by list_components | +| `fixed` | `bool?` | — | `null` | true fixes the component in place; false floats it so mates can move it; leave it out to keep it as it is | +| `flexible` | `bool?` | — | `null` | For a sub-assembly: true lets its own mates move inside this assembly (a crank that turns); false makes it rigid; leave it out to keep it as it is | + +**Sample call:** + +```json +{"component": "pin-1", "fixed": false} +``` + +--- + +### `list_components` + +List the top-level components of the active assembly by instance name, e.g. "bracket-1". + +**Parameters:** none + +**Sample call:** + +```json +{} +``` + +--- + +### `delete_feature` + +Delete a feature or sketch from the active model, along with the features that depend on it. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | Feature or sketch name, e.g. 'Boss-Extrude1' or 'Sketch1' | + +**Sample call:** + +```json +{"name": "Fillet1"} +``` + +--- + +### `suppress_feature` + +Suppress or unsuppress a feature of the active model; suppressed features stay in the tree but are not built. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `name` | `str` | ✅ | | Feature name, e.g. 'Fillet1' | +| `suppress` | `bool` | — | `true` | True to suppress, False to unsuppress | +| `configurations` | `str | list[str]` | — | `"this"` | Where it applies: 'this' (the active configuration), 'all', or a list of configuration names from `list_configurations` | + +**Sample call:** + +```json +{"name": "Fillet1", "suppress": true} +``` + +--- + +### `undo` + +Undo the last operations in the active model (Edit > Undo). + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `count` | `int` | — | `1` | Number of operations to undo | + +**Sample call:** + +```json +{} +``` + +--- + +### `create_reference_plane` + +Add a reference plane offset from, at an angle to, or on a plane or flat face. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `reference` | `str` | — | `""` | Name of the reference plane, e.g. 'Front Plane' or 'Plane1'; leave it out when giving face_point | +| `face_point` | `list[float]?` | — | `null` | [x, y, z] in mm on a flat face of the part (sloped or not), to use that face as the reference instead of a named plane | +| `offset` | `float` | — | `0.0` | Offset distance in millimetres. Non-zero for a named plane; 0 with face_point puts the plane on the face | +| `angle` | `float` | — | `0.0` | Angle in degrees between the new plane and the reference, about axis | +| `axis` | `str?` | — | `null` | Name of the axis the plane rotates about, e.g. 'Axis1' from create_axis; required with angle | +| `flip` | `bool` | — | `false` | Reverse the offset side or the angle direction | + +**Sample call:** + +```json +{"reference": "Top Plane", "offset": 20} +``` + +--- + +### `create_axis` + +Add a reference axis along the model's x, y or z direction, through the origin. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `reference` | `str` | ✅ | | Principal axis direction: 'x', 'y' or 'z' (case-insensitive; a leading +/- is stripped) | + +**Sample call:** + +```json +{"reference": "y"} +``` + +--- + +### `mirror_feature` + +Mirror solid bodies or features of the active part about a plane. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `features` | `list[str]` | — | `[]` | Body or feature names to mirror. At least one required. For a body mirror these are the names as they appear under Solid Bodies, which for a lofted wing is the loft's own name | +| `mirror_plane` | `str` | ✅ | | Plane name to mirror about, e.g. 'Right Plane' | +| `merge` | `bool` | — | `true` | Merge the mirrored result with the original body | +| `mirror_bodies` | `bool` | — | `true` | Mirror whole solid bodies rather than individual features. Defaults to True, which is what works for anything built from a loft or sweep - a feature mirror only resolves when the feature's own sketch sits on the mirror plane | + +**Sample call:** + +```json +{"features": ["Boss-Extrude1"], "mirror_plane": "Right Plane"} +``` + +--- + +### `pattern_circular` + +Repeat features of the active part around an axis, e.g. a ring of bosses or ribs. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `features` | `list[str]` | — | `[]` | Names of the features to pattern. At least one required. | +| `axis` | `str` | ✅ | | Name of the axis to rotate about, e.g. 'Axis1' as created by create_axis | +| `count` | `int` | ✅ | | Total number of instances including the original. Must be at least 2 - a pattern of one is just the original feature | +| `angle` | `float` | — | `360.0` | Total angle in degrees to spread the instances over. Defaults to a full 360 | +| `equal_spacing` | `bool` | — | `true` | Space instances evenly across 'angle' | + +**Sample call:** + +```json +{"features": ["Cut-Extrude1"], "axis": "Axis1", "count": 6} +``` diff --git a/docs/user-guide/tool-catalog/server-admin.md b/docs/user-guide/tool-catalog/server-admin.md new file mode 100644 index 00000000..817d7c53 --- /dev/null +++ b/docs/user-guide/tool-catalog/server-admin.md @@ -0,0 +1,23 @@ +# Server Admin Tools + +The server's own state. These never touch SolidWorks. + +**Total tools in this category: 1** + +--- + +### `reset_circuit_breaker` + +Let calls through again to operations the server paused after repeated failures. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `operation` | `str?` | — | `null` | The operation to reset, as named in the circuit_open error (e.g. create_extrusion); leave it out to reset every operation | + +**Sample call:** + +```json +{} +``` diff --git a/docs/user-guide/tool-catalog/sketching.md b/docs/user-guide/tool-catalog/sketching.md index 5b31cd0e..3916911f 100644 --- a/docs/user-guide/tool-catalog/sketching.md +++ b/docs/user-guide/tool-catalog/sketching.md @@ -39,6 +39,12 @@ fillet) fails with `error_type: "invalid_input"` and opens no sketch. } ``` +**Sample call:** + +```json +{"plane": "Top"} +``` + --- ### `add_line` @@ -355,6 +361,12 @@ Add a geometric relation between sketch entities: horizontal, vertical, parallel } ``` +**Sample call:** + +```json +{"entity1": "Line1", "relation_type": "horizontal"} +``` + --- ### `add_sketch_dimension` @@ -485,3 +497,20 @@ Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane --- +--- + +### `check_sketch_fully_defined` + +Check whether a sketch is fully defined, under-defined or over-defined. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `sketch_name` | `str?` | — | `null` | Optional sketch name. If omitted, checks the active or last sketch. | + +**Sample call:** + +```json +{} +``` diff --git a/docs/user-guide/tool-catalog/template-management.md b/docs/user-guide/tool-catalog/template-management.md index f2126b3b..dbf3a780 100644 --- a/docs/user-guide/tool-catalog/template-management.md +++ b/docs/user-guide/tool-catalog/template-management.md @@ -19,14 +19,8 @@ Compare two template files on disk: whether they are byte-identical, and how the | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `template1_path` | `str` | ✅ | `` | Path to first template | -| `template2_path` | `str` | ✅ | `` | Path to second template | -| `comparison_type` | `str` | — | `full` | Comparison type (full, properties, dimensions) | -| `comparison_depth` | `str` | — | `full` | Comparison depth alias | -| `include_properties` | `bool` | — | `True` | Include properties | -| `include_dimensions` | `bool` | — | `True` | Include dimensions | -| `include_materials` | `bool` | — | `True` | Include materials | -| `generate_report` | `bool` | — | `True` | Generate comparison report | +| `template1_path` | `str` | ✅ | | Path to first template | +| `template2_path` | `str` | ✅ | | Path to second template | **Sample call:** diff --git a/docs/user-guide/tools-overview.md b/docs/user-guide/tools-overview.md index 90b415bc..e0067971 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -1,6 +1,6 @@ # Tools Overview -The SolidWorks MCP Server provides 139 specialized tools for CAD automation. This page is a navigation map: each card links to the family's catalog page, which lists every tool with its inputs and a sample call. +The SolidWorks MCP Server provides 140 specialized tools for CAD automation. This page is a navigation map: each card links to the family's catalog page, which lists every tool with its inputs and a sample call. ## Read this first @@ -23,7 +23,7 @@ add-in (Simulation, PDM, Routing, PhotoView) or a feature SolidWorks sells only with Professional or Premium. Every live check ran on SOLIDWORKS Professional for Makers 2026; Standard itself hasn't been run yet. -Each tool's `needs:` tag says what it needs. All but the 20 below need +Each tool's `needs:` tag says what it needs. All but the 21 below need SolidWorks running (`needs:running`). ### Needs nothing @@ -41,7 +41,7 @@ These work with no SolidWorks on the machine (`needs:nothing`): These read SolidWorks' installed files and never start it (`needs:installed`): `discover_solidworks_docs`, `search_solidworks_api_help`, `lookup_api_method`, `lookup_api_interface`, -`find_related_api_members`, `list_hole_sizes`. +`get_api_enum`, `find_related_api_members`, `list_hole_sizes`. ## Tool Categories @@ -67,7 +67,7 @@ These read SolidWorks' installed files and never start it --- - Drawings from a model: views, notes and centre marks. Section and detail views, dimensions and the title block are planned. + Drawings from a model: standard, section and detail views, dimensions, notes, centre marks, the sheet format and title block, and a drawing check. [**13 tools available** :octicons-arrow-right-24:](tool-catalog/drawing.md) @@ -151,13 +151,21 @@ These read SolidWorks' installed files and never start it [**1 tool available** :octicons-arrow-right-24:](tool-catalog/template-management.md) +- :material-restart:{ .lg .middle } **Server Admin** + + --- + + Reset the circuit breaker the server uses to pause a failing operation. + + [**1 tool available** :octicons-arrow-right-24:](tool-catalog/server-admin.md) + - :material-book-search:{ .lg .middle } **Docs Discovery** --- Look up SolidWorks API interfaces and members in the installed type library. - [**5 tools available** :octicons-arrow-right-24:](tool-catalog/docs-discovery.md) + [**6 tools available** :octicons-arrow-right-24:](tool-catalog/docs-discovery.md) - :material-server:{ .lg .middle } **Server Admin** @@ -169,7 +177,7 @@ These read SolidWorks' installed files and never start it -**Total: 139 Tools** +**Total: 140 Tools** ## Deprecated tools diff --git a/mkdocs.yml b/mkdocs.yml index 6afc9957..cc202c32 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -62,6 +62,7 @@ nav: - Template Management: user-guide/tool-catalog/template-management.md - Macro Recording: user-guide/tool-catalog/macro-recording.md - Docs Discovery: user-guide/tool-catalog/docs-discovery.md + - Server Admin: user-guide/tool-catalog/server-admin.md - Agents and Skills: - Agents and Prompt Testing: agents/agents-and-testing.md - Family-Gated Tool Routing: agents/family-gated-tool-routing.md diff --git a/openspec/changes/archive/2026-11-16-api-enum-lookup/.openspec.yaml b/openspec/changes/archive/2026-11-16-api-enum-lookup/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-api-enum-lookup/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-16-api-enum-lookup/design.md b/openspec/changes/archive/2026-11-16-api-enum-lookup/design.md new file mode 100644 index 00000000..4dc0fe0f --- /dev/null +++ b/openspec/changes/archive/2026-11-16-api-enum-lookup/design.md @@ -0,0 +1,20 @@ +## Context + +`swconst.tlb` sits beside `sldworks.tlb` and is registered under its own +GUID, `{4687F359-55D0-4CD3-B6CF-2EB42C11F989}`, at the same version (34.0 +for SolidWorks 2026, checked with a read-only load). All 983 of its type +infos are enums (`TKIND_ENUM`); each variable's `VARDESC.value` is the +integer. + +## Decisions + +- **Load by GUID at the main library's version**, with `LoadRegTypeLib`, + as the main library is loaded. A failure leaves `enums` empty and records + why in the index (`enums_note`), so the method lookups never fail because + of it. +- **Saved in the same index** under `enums`: `{name: {description, + members: [{name, value}]}}`. Format 2.1 makes a 2.0 index rebuild. +- **Member lookup** by scanning the enums for a member of that name: 983 + enums, about 20,000 members, well under a millisecond. +- **`search_solidworks_api_help` is unchanged**; enums are reached through + the new tool. diff --git a/openspec/changes/archive/2026-11-16-api-enum-lookup/proposal.md b/openspec/changes/archive/2026-11-16-api-enum-lookup/proposal.md new file mode 100644 index 00000000..8e2d48bc --- /dev/null +++ b/openspec/changes/archive/2026-11-16-api-enum-lookup/proposal.md @@ -0,0 +1,34 @@ +## Why + +Issue #95: an agent writing a SolidWorks call can look up a method's +parameters but not the values of the enums they take. Guessing goes wrong: +building `set_units`, `swUnitSystem_IPS` turned out to be 3, not 4, and the +user preference `swUnitSystem` 263, not 48. The values live in SolidWorks' +constants type library (`swconst.tlb`), installed and registered beside the +main one, which the lookups don't read today. + +## What Changes + +- The API index also reads the constants type library: every enum, its + description, and each member's name and integer value (983 enums on + SolidWorks 2026). The index format goes from 2.0 to 2.1, so a saved + index is rebuilt once (about a second). +- A new tool, `get_api_enum`: an enum name gives its members and values. + A member name (`swUnitSystem_IPS`) gives the enum it belongs to, with + that member marked. Names match regardless of case. No match says so. +- The tool needs SolidWorks installed, not running (`needs:installed`), + like the other lookups. 140 tools. + +## Capabilities + +### New Capabilities +None. + +### Modified Capabilities +- `tools/api-help-lookup`: adds the enum lookup the spec deferred to #95. + +## Impact + +`tools/type_library.py`, `tools/docs_discovery.py`, the hints, levels and +requirements tables, the docs-discovery catalog page and tool counts, the +live API-lookup test. diff --git a/openspec/changes/archive/2026-11-16-api-enum-lookup/specs/tools/api-help-lookup/spec.md b/openspec/changes/archive/2026-11-16-api-enum-lookup/specs/tools/api-help-lookup/spec.md new file mode 100644 index 00000000..8f31f136 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-api-enum-lookup/specs/tools/api-help-lookup/spec.md @@ -0,0 +1,26 @@ +## ADDED Requirements + +### Requirement: Enum values + +`get_api_enum` SHALL return an enum's members and their integer values +from the installed SolidWorks constants type library. Given a member name +instead, it SHALL return the enum that member belongs to, and say which +member matched. Names SHALL match regardless of case. A name that is +neither SHALL be reported as not found, with the reason, rather than +raising. + +#### Scenario: An enum by name +- **WHEN** `get_api_enum` is called with `swUnitSystem_e` +- **THEN** the result lists its members with `swUnitSystem_IPS` = 3 and `swUnitSystem_MMGS` = 5 + +#### Scenario: A member by name +- **WHEN** it is called with `swunitsystem_ips` +- **THEN** the result is `swUnitSystem_e`, with `matched_member` `swUnitSystem_IPS` + +#### Scenario: An unknown name +- **WHEN** it is called with a name that is neither an enum nor a member +- **THEN** `found` is false and the note says so + +#### Scenario: No constants library +- **WHEN** the constants type library can't be loaded +- **THEN** the index is built without enums, the other lookups still work, and `get_api_enum` says why it has nothing diff --git a/openspec/changes/archive/2026-11-16-api-enum-lookup/tasks.md b/openspec/changes/archive/2026-11-16-api-enum-lookup/tasks.md new file mode 100644 index 00000000..6d1cc9ba --- /dev/null +++ b/openspec/changes/archive/2026-11-16-api-enum-lookup/tasks.md @@ -0,0 +1,15 @@ +## 1. Index + +- [x] 1.1 `type_library.py`: `ApiEnum`, `index_enums(lib)`, `load_constants_library(major, minor)` +- [x] 1.2 `docs_discovery.py`: the index reads the enums (format 2.1); a failure leaves them empty with a note + +## 2. Tool + +- [x] 2.1 `get_api_enum` with `GetApiEnumInput` and `EnumLookup`; hints, level, `needs:installed` +- [x] 2.2 Unit tests: an enum, a member, case, unknown, no constants library, the index format +- [x] 2.3 Live: `swUnitSystem_e` read from this machine's library (in `test_live_sw_api_lookup.py`) + +## 3. Docs + +- [x] 3.1 Catalog entry, overview list, counts (140), CHANGELOG +- [x] 3.2 Full suite at 100%, ruff, mypy, docs strict diff --git a/openspec/changes/archive/2026-11-16-mypy-gates-ci/.openspec.yaml b/openspec/changes/archive/2026-11-16-mypy-gates-ci/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-mypy-gates-ci/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-16-mypy-gates-ci/design.md b/openspec/changes/archive/2026-11-16-mypy-gates-ci/design.md new file mode 100644 index 00000000..c69043b2 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-mypy-gates-ci/design.md @@ -0,0 +1,33 @@ +## Context + +`mypy src/solidworks_mcp` on 2026-11-16: 139 errors in 22 files. The large +groups: `hole_library.py` (50; dict literals typed too narrowly and a +SQLAlchemy `select` on a reflected `Table`), `documentation.py` (37; mostly +lambdas passed to `_attempt`, "Cannot infer type of lambda"), +`drawing_standard.py` (18), `features.py` (14), the adapters (21). + +## Decisions + +- **Gate, not remove.** The repo's rule is typed code with docstrings; a + gate keeps that true. The count is small enough to clear in one change. +- **Generic `_attempt`.** `def _attempt[T](self, op: Callable[[], T], + default: T) -> T` clears most of `documentation.py`. +- **`platform = "win32"`** in `[tool.mypy]`, so `sys.platform` branches + are checked the same everywhere. +- **No behaviour change.** Fixes are annotations, `cast`, and narrowing + that the code already implies. Where narrowing would need a new runtime + check, the check must be one a test already reaches; otherwise use a cast. +- **Bare-ignore check** as a unit test that scans `src/` for + `# type: ignore` without `[code]`. + +## What the fix found + +- 47 errors were lambdas binding loop values as defaults (`lambda i=i:`), + which mypy can't match to `Callable[[], T]`; the `_attempt` helpers now + take `Callable[..., T]`. +- One real fault: `plan_layout` with `inside_first` raised `TypeError` for + a leader dimension with no lines (`leader_anchor` returns `None`). It now + places that dimension outside, with a test. +- The stub packages `types-PyYAML` and `types-defusedxml` join the dev + extra. +- **CI step** `make typecheck` before `make test`, in the same job. diff --git a/openspec/changes/archive/2026-11-16-mypy-gates-ci/proposal.md b/openspec/changes/archive/2026-11-16-mypy-gates-ci/proposal.md new file mode 100644 index 00000000..5a08e6ab --- /dev/null +++ b/openspec/changes/archive/2026-11-16-mypy-gates-ci/proposal.md @@ -0,0 +1,30 @@ +## Why + +Issue #157: mypy is configured in `pyproject.toml` but nothing runs it, and +`main` has 139 errors in 22 files. New code adds more and nobody notices, +while the project's rule is that every function is typed. The issue's other +half, the stale `src/utils/validate_coverage.py`, was already deleted by an +earlier change. + +## What Changes + +- Fix the 139 errors without changing behaviour: annotations, narrowing and + `cast` where COM returns `Any`. A `# type: ignore` names its error code + (the code base already has 30 that do). +- mypy checks as if on Windows (`platform = "win32"`), so CI on Linux and a + developer on Windows see the same result. +- `make typecheck` runs it, and CI runs `make typecheck` before the tests. + +## Capabilities + +### New Capabilities +- `release/type-checking`: mypy gates CI with zero errors. + +### Modified Capabilities +None. + +## Impact + +`pyproject.toml`, `Makefile`, `.github/workflows/ci.yml`, the 22 files with +errors. No tool's behaviour changes; the unit suite at 100% coverage is the +check. diff --git a/openspec/changes/archive/2026-11-16-mypy-gates-ci/specs/release/type-checking/spec.md b/openspec/changes/archive/2026-11-16-mypy-gates-ci/specs/release/type-checking/spec.md new file mode 100644 index 00000000..939eddb5 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-mypy-gates-ci/specs/release/type-checking/spec.md @@ -0,0 +1,24 @@ +## ADDED Requirements + +### Requirement: mypy gates CI + +CI SHALL run mypy over `src/solidworks_mcp` with the project's +configuration and fail on any error. mypy SHALL check as if on Windows, so +the result doesn't depend on the machine running it. + +#### Scenario: A type error is pushed +- **WHEN** a commit adds code mypy reports an error in +- **THEN** the CI job fails at the type-check step, before the tests + +#### Scenario: The code base is clean +- **WHEN** `make typecheck` runs on `main` after this change +- **THEN** mypy reports no errors + +### Requirement: Suppressions are explained + +A `# type: ignore` SHALL name its error code. A new one SHALL also say +why, on its line or the one above. + +#### Scenario: A bare ignore +- **WHEN** the source contains `# type: ignore` without an error code +- **THEN** the check fails and names the line diff --git a/openspec/changes/archive/2026-11-16-mypy-gates-ci/tasks.md b/openspec/changes/archive/2026-11-16-mypy-gates-ci/tasks.md new file mode 100644 index 00000000..60f35b45 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-mypy-gates-ci/tasks.md @@ -0,0 +1,11 @@ +## 1. Errors + +- [x] 1.1 `platform = "win32"` in `[tool.mypy]`; re-count +- [x] 1.2 Fix every error, file by file, with no behaviour change +- [x] 1.3 Test: no bare `# type: ignore` in `src/` + +## 2. Gate + +- [x] 2.1 `make typecheck`; CI runs it before the tests +- [x] 2.2 CONTRIBUTING or CLAUDE.md: mypy is part of the checks +- [x] 2.3 Full suite at 100%, ruff, mypy clean, docs strict diff --git a/openspec/changes/archive/2026-11-16-tool-catalog-check/.openspec.yaml b/openspec/changes/archive/2026-11-16-tool-catalog-check/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tool-catalog-check/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-16-tool-catalog-check/design.md b/openspec/changes/archive/2026-11-16-tool-catalog-check/design.md new file mode 100644 index 00000000..7b512eae --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tool-catalog-check/design.md @@ -0,0 +1,28 @@ +## Context + +The catalog pages are hand-written: a description, prerequisites, a +parameter table, a sample call and often response fields per tool. The +generator produced a cruder version and overwrote the hand text, so it +was not run after 2026-11-15. The four harness tests that read its JSON +(`tests/.generated/tool_catalog.json`) skip when the file is missing, +which is always so in CI. + +## Decisions + +- **The pages are the source; the check keeps them honest.** It parses each + entry: from its `### \`name\`` heading to the next heading of that level. + - The parameter table is the one after `**Parameters:**`, rows starting + `| \`field\` |`. + - The sample is the first ```json block after `**Sample call:**`. +- **Input model** from the tool function's `input_data` annotation, so the + sample is validated exactly as a call would be; field names come from the + model's fields (aliases are not listed). +- **Family pages**: the page is named after the family tag; `server_admin` + gets `server-admin.md`. +- **Missing entries written from the tool's docstring:** + - its first line is the entry's description; + - its `Example input:` is the sample call, where the docstring has one; + - the table comes from the model's field descriptions, then is reviewed + by hand. +- **Generator removed** rather than fixed: two sources for one page drift + again. diff --git a/openspec/changes/archive/2026-11-16-tool-catalog-check/proposal.md b/openspec/changes/archive/2026-11-16-tool-catalog-check/proposal.md new file mode 100644 index 00000000..0c273b5f --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tool-catalog-check/proposal.md @@ -0,0 +1,42 @@ +## Why + +Issue #156: the tool catalog pages drift from the tools and nothing checks +them. Today 20 of the 140 registered tools have no catalog entry at all +(16 of them modeling tools), and about 30 entries list inputs the tool no +longer takes, or miss ones it does. The issue proposed regenerating the +pages from `src/utils/generate_tool_catalog.py`. That script overwrites the +hand-written text the pages are made of (it wiped them once, 2026-11-15), +ignores `--help`, and nothing has run it in months. + +## What Changes + +- **A check instead of a generator.** A test reads every catalog page and + fails when: + - a registered tool has no entry, or one on a page other than its + family's; + - an entry names a tool that isn't registered; + - an entry's parameter table doesn't list exactly the tool's inputs; + - an entry's sample call isn't valid JSON that the tool's input model + accepts. So a `null` for a required field fails. +- **The gaps filled by hand:** + - entries for the 20 missing tools; + - the stale parameter tables corrected; + - a page for the server-admin family (`reset_circuit_breaker`). +- **The generator is removed**, with the four harness tests that read its + JSON output. They were always skipped in CI, and the new check covers + what they asked. + +## Capabilities + +### New Capabilities +- `docs/tool-catalog`: what every catalog entry must hold, and the check. + +### Modified Capabilities +None. + +## Impact + +`docs/user-guide/tool-catalog/*.md` (and a new `server-admin.md`), +`mkdocs.yml` nav, `src/utils/generate_tool_catalog.py` (deleted), +`tests/integration/test_all_endpoints_harness.py`, a new +`tests/integration/test_tool_catalog.py`. diff --git a/openspec/changes/archive/2026-11-16-tool-catalog-check/specs/docs/tool-catalog/spec.md b/openspec/changes/archive/2026-11-16-tool-catalog-check/specs/docs/tool-catalog/spec.md new file mode 100644 index 00000000..7e86166b --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tool-catalog-check/specs/docs/tool-catalog/spec.md @@ -0,0 +1,29 @@ +## ADDED Requirements + +### Requirement: Every tool has one catalog entry + +Every registered tool SHALL have exactly one entry, a `### \`\`` +heading, on the catalog page of its family (the family tag with `_` as +`-`). No entry SHALL name a tool that isn't registered. + +#### Scenario: A new tool without an entry +- **WHEN** a tool is registered and no catalog page has its heading +- **THEN** the catalog check fails and names the tool and the page it belongs on + +#### Scenario: A removed tool's entry +- **WHEN** a page has an entry for a name no tool has +- **THEN** the check fails and names it + +### Requirement: An entry matches the tool's inputs + +An entry's parameter table SHALL list exactly the tool's input fields; a +tool without inputs says `**Parameters:** none`. Its sample call SHALL be +JSON that the tool's input model accepts. + +#### Scenario: A field added to a tool +- **WHEN** a tool gains an input the entry's table doesn't list +- **THEN** the check fails and names the field + +#### Scenario: A placeholder sample +- **WHEN** a sample call has `null` for a required field, or isn't valid JSON +- **THEN** the check fails with the validation error diff --git a/openspec/changes/archive/2026-11-16-tool-catalog-check/tasks.md b/openspec/changes/archive/2026-11-16-tool-catalog-check/tasks.md new file mode 100644 index 00000000..fbbe0a88 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tool-catalog-check/tasks.md @@ -0,0 +1,10 @@ +## 1. Check + +- [x] 1.1 `tests/integration/test_tool_catalog.py`: entries, family page, parameter table, sample validated against the input model +- [x] 1.2 Remove `src/utils/generate_tool_catalog.py` and the harness tests that read its JSON + +## 2. Pages + +- [x] 2.1 Entries for the 20 missing tools; `server-admin.md` in the nav and the catalog index +- [x] 2.2 Fix every stale parameter table and sample the check reports +- [x] 2.3 Full suite at 100%, ruff, mypy, `mkdocs build --strict`, `llms.txt` rebuilt diff --git a/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/.openspec.yaml b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/design.md b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/design.md new file mode 100644 index 00000000..7e550ebf --- /dev/null +++ b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/design.md @@ -0,0 +1,28 @@ +## Context + +`RunMacro2` blocks the connect thread until the macro returns, and COM calls +can't move to another thread (CLAUDE.md, COM threading). Only the user, +or something acting like them on the dialog, can make it return. + +## Decisions + +- **Watchdog thread, Win32 only.** + - Before `RunMacro2`, the adapter reads `ISldWorks.GetProcessID()` on the + connect thread and notes the dialogs that process already has open. + - A daemon thread then polls every 0.5 s for visible top-level windows + of that process with a dialog class: `#32770` (message boxes, file + prompts) or `ThunderDFrame` (VBA user forms). +- **Answer only with the non-committal choice.** + - A child button whose text, without `&`, is `Cancel`: click it. + - Else a single button: click it (an OK acknowledgement). + - Else no buttons: `WM_CLOSE`. + - Anything else is left for the user and logged once. +- **What the watchdog reads:** title (`GetWindowText`), the static texts, + the button labels, and what it did. These are returned to the adapter, + which raises `SolidWorksMCPError` after `RunMacro2` returns. The + classifier maps "waited for the user" to `macro_waited_for_user`. +- **`dialog_timeout`** is a tool input, 1–600 s, default 30. The adapter + takes it in the macro params. +- **Testability:** the Win32 calls go through one small object (`Win32Windows`) + that tests replace. The real one is a thin pass-through over `win32gui`, + covered with a fake `win32gui` module. diff --git a/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/proposal.md b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/proposal.md new file mode 100644 index 00000000..c7e30776 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/proposal.md @@ -0,0 +1,37 @@ +## Why + +Issue #97: a macro that opens a dialog (a `MsgBox`, a user form, a +SolidWorks prompt) waits for an answer nobody gives. `RunMacro2` doesn't +return, so the server hangs; 2 min 17 s was seen live before the dialog was +closed by hand. The tool's description already says a macro must not wait +for the user, but nothing enforces it. + +## What Changes + +- While `execute_macro` runs a macro, a watchdog thread looks for a dialog + opened by the SolidWorks process. It uses only Win32 window calls, never + COM, so the COM threading rule holds. +- When a dialog stays open longer than `dialog_timeout` seconds (a new + input; default 30), the watchdog: + - reads its title, text and buttons; + - answers it with the non-committal choice: **Cancel** when there is + one, else the only button when there is just one (OK), else it closes + the window. It never picks Yes, No, Retry or Abort. +- The call then returns an error that names the dialog, what it said and + how it was answered, and repeats that macros run here must not wait for + the user. `error_type` is `macro_waited_for_user`. +- A dialog it can't answer that way (for example Yes/No with no Cancel) + is reported in the log after the timeout and left for the user, as today. +- A macro that runs long without a dialog is not interrupted. + +## Capabilities + +### Modified Capabilities +- `tools/macro-execution`: a macro that waits for the user fails cleanly. + +## Impact + +A new `adapters/solidworks/dialog_watch.py`; `pywin32_adapter.py` +(`_invoke_run_macro2`); `tools/macro_recording.py` (the input field); the +error classifier; the catalog entry. Live check: a macro with a `MsgBox` +(left for the user's run). diff --git a/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/specs/tools/macro-execution/spec.md b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/specs/tools/macro-execution/spec.md new file mode 100644 index 00000000..3037a737 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/specs/tools/macro-execution/spec.md @@ -0,0 +1,27 @@ +## ADDED Requirements + +### Requirement: A macro that waits for the user fails cleanly + +While `execute_macro` runs a macro, a dialog that SolidWorks' process +keeps open longer than `dialog_timeout` seconds SHALL be answered with +Cancel when it has one, or with its only button when it has just one, or +closed when it has no buttons. The call SHALL then return an error with +`error_type` `macro_waited_for_user` that names the dialog's title and +text and how it was answered. A dialog with several buttons and no Cancel +SHALL be left open and logged. The watchdog SHALL make no COM calls. + +#### Scenario: A MsgBox with OK +- **WHEN** a macro shows `MsgBox "Done"` and `dialog_timeout` is 5 +- **THEN** after about 5 s the box is answered OK and the reply is an error naming "Done" and the answer + +#### Scenario: A prompt with Cancel +- **WHEN** a dialog with OK and Cancel stays open past the timeout +- **THEN** it is answered Cancel, never OK + +#### Scenario: Yes and No only +- **WHEN** a dialog's only buttons are Yes and No +- **THEN** neither is pressed, and the log says the dialog needs the user + +#### Scenario: No dialog +- **WHEN** a macro runs for longer than the timeout without opening a dialog +- **THEN** it is not interrupted and its result is returned as before diff --git a/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/tasks.md b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/tasks.md new file mode 100644 index 00000000..a881a6a3 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-macro-dialog-watchdog/tasks.md @@ -0,0 +1,11 @@ +## 1. Watchdog + +- [x] 1.1 `adapters/solidworks/dialog_watch.py`: `DialogWatch` (start/stop, the answer rules), `Win32Windows` +- [x] 1.2 `_invoke_run_macro2` runs the macro inside the watch and raises when a dialog was answered +- [x] 1.3 `dialog_timeout` on `MacroPlaybackInput`; classifier rule `macro_waited_for_user` + +## 2. Checks + +- [x] 2.1 Unit tests: each answer rule, pre-existing dialogs ignored, no dialog, the adapter error +- [x] 2.2 Live test (passed 2026-11-17, run by the user): a `MsgBox` answered OK and an OK/Cancel prompt answered Cancel after 3 s (`tests/live/test_live_sw_macro_dialog.py`) +- [x] 2.3 Catalog entry, CHANGELOG, full suite at 100%, ruff, mypy diff --git a/openspec/changes/macro-from-vba-source/.openspec.yaml b/openspec/changes/macro-from-vba-source/.openspec.yaml new file mode 100644 index 00000000..bbe8b393 --- /dev/null +++ b/openspec/changes/macro-from-vba-source/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/macro-from-vba-source/design.md b/openspec/changes/macro-from-vba-source/design.md new file mode 100644 index 00000000..0775ce3d --- /dev/null +++ b/openspec/changes/macro-from-vba-source/design.md @@ -0,0 +1,14 @@ +## Decisions + +- **`.swb`, not `.swp`.** The live run of #244 ran three text `.swb` + macros through `RunMacro2` with `errors == 0`. Building a binary `.swp` + (OLE2 streams, or the MacroBuilder library) isn't needed for running; + it stays out of scope. +- **The setting lives in the config** (`allow_vba_source`, from + `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE` like every other setting), read when + the tool runs. Default off. +- **Files:** `/solidworks_mcp/macros/vba-.swb`, written as + Windows-1252 text (what the VBA editor reads). They are kept, so what + ran can be looked at afterwards; the reply names the file. +- **Refusal** raises `ToolOperationError` with a message the classifier + maps to `vba_source_off`. diff --git a/openspec/changes/macro-from-vba-source/proposal.md b/openspec/changes/macro-from-vba-source/proposal.md new file mode 100644 index 00000000..a96f9d63 --- /dev/null +++ b/openspec/changes/macro-from-vba-source/proposal.md @@ -0,0 +1,33 @@ +## Why + +Issue #96: the `generate_vba_*` tools write VBA, and `execute_macro` runs +only a macro file, so "write a macro and run it" stopped at a hand step in +the VBA editor. The live check of #244 showed `RunMacro2` runs a plain-text +legacy macro (`.swb`) as it runs a binary `.swp`, so no binary file has to +be built: the source can be written to a `.swb` and run. + +Running VBA an AI wrote is running code on the user's machine (VBA can +delete files or call the shell), so the user chose (2026-11-17) to make it +opt-in. + +## What Changes + +- `execute_macro` takes `vba_source`, the macro's text, instead of a file. + It is written to a new `.swb` under the temp folder and run the same way, + with the dialog watchdog. The reply gives the file and the exact source. +- Off unless the server is started with + `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1` (config `allow_vba_source`). When off, + the call is refused as `vba_source_off` and says how to turn it on. +- Exactly one of `macro_path`, `macro_file` and `vba_source` is given. + Source that can't be written as Windows-1252 text is refused. +- The docs explain the risk and the setting. + +## Capabilities + +### Modified Capabilities +- `tools/macro-execution`: runs VBA source, when allowed. + +## Impact + +`config.py`, `tools/macro_recording.py`, the error classifier, the +macro-recording catalog page and the installation guide. No adapter change. diff --git a/openspec/changes/macro-from-vba-source/specs/tools/macro-execution/spec.md b/openspec/changes/macro-from-vba-source/specs/tools/macro-execution/spec.md new file mode 100644 index 00000000..893b1c47 --- /dev/null +++ b/openspec/changes/macro-from-vba-source/specs/tools/macro-execution/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: VBA source runs only when the user allowed it + +`execute_macro` SHALL accept `vba_source` in place of a macro file. When +the server's `allow_vba_source` setting is on, the source SHALL be written +to a new `.swb` file and run as a macro file is, and the reply SHALL give +the file's path and the source that ran. When the setting is off, the call +SHALL be refused with `error_type` `vba_source_off`, and nothing SHALL be +written or run. + +#### Scenario: Allowed +- **WHEN** `allow_vba_source` is on and an agent calls `execute_macro` with `vba_source` +- **THEN** a `.swb` holding that source is run, and the reply names the file and repeats the source + +#### Scenario: Not allowed +- **WHEN** the setting is off +- **THEN** the reply is an error, `vba_source_off`, naming `SOLIDWORKS_MCP_ALLOW_VBA_SOURCE`, and no file is written + +#### Scenario: Two sources +- **WHEN** both `vba_source` and `macro_path` are given +- **THEN** the input is refused as invalid diff --git a/openspec/changes/macro-from-vba-source/tasks.md b/openspec/changes/macro-from-vba-source/tasks.md new file mode 100644 index 00000000..81f7ae30 --- /dev/null +++ b/openspec/changes/macro-from-vba-source/tasks.md @@ -0,0 +1,11 @@ +## 1. Tool + +- [x] 1.1 `allow_vba_source` in the config +- [x] 1.2 `vba_source` on `MacroPlaybackInput` (one source only; Windows-1252); written to a `.swb` and run; reply gives `source_file` and `vba_source` +- [x] 1.3 Refused as `vba_source_off` when the setting is off + +## 2. Checks and docs + +- [x] 2.1 Unit tests: allowed, refused, two sources, bad characters +- [ ] 2.2 Live test written (run pending): a sketch added by VBA source +- [x] 2.3 Catalog entry, installation guide (the setting and its risk), CHANGELOG; full suite, ruff, mypy, docs strict diff --git a/openspec/changes/save-body-no-stray-assembly/.openspec.yaml b/openspec/changes/save-body-no-stray-assembly/.openspec.yaml new file mode 100644 index 00000000..bbe8b393 --- /dev/null +++ b/openspec/changes/save-body-no-stray-assembly/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/save-body-no-stray-assembly/design.md b/openspec/changes/save-body-no-stray-assembly/design.md new file mode 100644 index 00000000..ac6acf89 --- /dev/null +++ b/openspec/changes/save-body-no-stray-assembly/design.md @@ -0,0 +1,11 @@ +## Decisions + +- **Clean up after, not change the call.** `CreateSaveBodyFeature` + takes `(Bodies, FilePaths, AssemName, ConsumeBody, CopyCustomProperty)`; + no argument turns the assembly off (checked in the type library), and + the cause can't be probed without SolidWorks. Closing what the call left + works whatever triggers it. +- **Only what is safe to close:** new since the call (by title), an + assembly, and no file (`GetPathName` empty). Closing it loses nothing. +- **The part becomes active again** with `ActivateDoc3`, so the next tool + acts on it. diff --git a/openspec/changes/save-body-no-stray-assembly/proposal.md b/openspec/changes/save-body-no-stray-assembly/proposal.md new file mode 100644 index 00000000..d07e7508 --- /dev/null +++ b/openspec/changes/save-body-no-stray-assembly/proposal.md @@ -0,0 +1,24 @@ +## Why + +Issue #101: after `save_body_as_part` succeeds, an extra unsaved assembly +(`Assem`) is open in SolidWorks, and the reply doesn't mention it. The +part file is written correctly; the assembly is clutter the user has to +close, and it becomes the active document, so the next tool acts on it. + +## What Changes + +- Before the Save Bodies call, the adapter notes the open documents. After + it, any document that is new, an assembly and unsaved is closed, and the + part is made active again. +- The reply's `closed_documents` lists what was closed. Nothing that was + open before, or that has a file, is touched. + +## Capabilities + +### Modified Capabilities +- `tools/multibody-part-export`: no document left open behind the call. + +## Impact + +`adapters/solidworks/io.py` (`save_body_as_part`), the mock adapter, the +tool description, and the live test in `test_live_sw_wave3.py`. diff --git a/openspec/changes/save-body-no-stray-assembly/specs/tools/multibody-part-export/spec.md b/openspec/changes/save-body-no-stray-assembly/specs/tools/multibody-part-export/spec.md new file mode 100644 index 00000000..358da454 --- /dev/null +++ b/openspec/changes/save-body-no-stray-assembly/specs/tools/multibody-part-export/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Save Bodies leaves no document behind + +After `save_body_as_part`, no document SHALL be open that wasn't open +before the call, except the part itself. A new, unsaved assembly that +SolidWorks opened alongside SHALL be closed, the part made active again, +and the reply's `closed_documents` SHALL name it. + +#### Scenario: SolidWorks opens an assembly +- **WHEN** the Save Bodies call leaves a new, unsaved assembly open +- **THEN** it is closed, the part is active, and `closed_documents` names it + +#### Scenario: The user's own assembly +- **WHEN** an assembly was open before the call, or has a file +- **THEN** it is left open diff --git a/openspec/changes/save-body-no-stray-assembly/tasks.md b/openspec/changes/save-body-no-stray-assembly/tasks.md new file mode 100644 index 00000000..ea47f33e --- /dev/null +++ b/openspec/changes/save-body-no-stray-assembly/tasks.md @@ -0,0 +1,6 @@ +## 1. Fix + +- [x] 1.1 Note the open documents before Save Bodies; close new unsaved assemblies after; reactivate the part; `closed_documents` in the reply +- [x] 1.2 Unit test: the new assembly closed, the user's saved one left +- [ ] 1.3 Live: `test_save_body_as_part_writes_the_body_file` checks no unsaved assembly is open afterwards (run pending) +- [x] 1.4 Tool description, mock adapter, CHANGELOG; full suite, ruff, mypy diff --git a/openspec/queue.md b/openspec/queue.md index c7062431..9a0f0c65 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -31,8 +31,13 @@ Last updated 2026-11-16. | 14 | Optional toolsets and a discovery mode, to cut the tool list's size | #176 | `tool-discovery-mode` (archived) | Done 2026-11-16: `SOLIDWORKS_MCP_TOOLSETS` and `SOLIDWORKS_MCP_TOOL_MODE=search` (4 tools, about 900 tokens a turn instead of about 55,000), checked live; the size table is in the installation guide | | 15 | Sheet metal: base flange, edge flange, sketched bend, flat pattern | #57 | `sheet-metal` (archived) | Done 2026-11-16: `create_base_flange`, `add_edge_flange`, `create_sketched_bend`, `set_flat_pattern`, checked live (the blank 78.7124 mm against 78.712 by hand). A sketched bend's fixed side can't be chosen through the API (#239) | | 16 | README: licence-tier tags | #79 (other half) | `tool-requirements` (archived) | Done 2026-11-16: no tool needs more than the licence that runs SolidWorks, so each tool is tagged with what it needs instead: `needs:nothing` (14), `needs:installed` (6) or `needs:running` | -| 17 | Remove the stale `validate_coverage.py`; decide whether mypy gates CI | #157 | not yet written | | +| 17 | Remove the stale `validate_coverage.py`; decide whether mypy gates CI | #157 | `mypy-gates-ci` (archived) | Done 2026-11-16: mypy gates CI with zero errors (139 fixed); `validate_coverage.py` had already been deleted | | 18 | Skills that improve the agent's results, measured on the U-joint prompt | #207 | not yet written | Tabled 2026-11-09: needs research first (what "better" means, a harness to run and score sessions). See `openspec/research/agent-skill-evaluation.md` | +| 23 | Enum values: an enum's members and their integers, read from SolidWorks' constants type library, so an agent never guesses one (`swUnitSystem_IPS` is 3, not 4). Named `get_api_enum` under the tool-naming rule | #95 | `api-enum-lookup` (archived) | Done 2026-11-16: `get_api_enum`, checked live against this machine's swconst.tlb (983 enums) | +| 24 | The tool catalog pages drift from the registered tools with no check: some tools are missing and some sample payloads are null. A check that every registered tool has a catalog entry with its inputs, and the gaps filled | #156 | `tool-catalog-check` (archived) | Done 2026-11-16: a check reads every catalog page against the registered tools; 20 missing entries written, about 30 stale tables and samples fixed; the generator removed | +| 25 | `execute_macro` hangs with no timeout on a macro that waits for the user: a time limit, and a clear error when it's hit | #97 | `macro-dialog-watchdog` (archived) | Done 2026-11-17: a dialog left waiting is answered (Cancel, or its only button) and the run fails as `macro_waited_for_user`; checked live (#244) | +| 26 | `execute_macro` runs VBA source text (a `generate_vba_*` result, or the agent's own), saved as a `.swb` and run with the dialog watchdog. Opt-in (`SOLIDWORKS_MCP_ALLOW_VBA_SOURCE`), the user's choice 2026-11-17 | #96 | `macro-from-vba-source` | Built, unit-tested; live check pending (`tests/live/test_live_sw_macro_source.py`) | +| 27 | `save_body_as_part` leaves an extra unsaved assembly open (the Save Bodies feature's create-assembly option) | #101 | `save-body-no-stray-assembly` | Built, unit-tested; live check pending (`test_live_sw_wave3.py::test_save_body_as_part_writes_the_body_file`) | ## Removed tools (item 10, release 2.1.0) 33 tools were registered but never implemented: every call returned diff --git a/openspec/specs/docs/tool-catalog/spec.md b/openspec/specs/docs/tool-catalog/spec.md new file mode 100644 index 00000000..c496662d --- /dev/null +++ b/openspec/specs/docs/tool-catalog/spec.md @@ -0,0 +1,33 @@ +# docs/tool-catalog Specification + +## Purpose +TBD - created by archiving change tool-catalog-check. Update Purpose after archive. +## Requirements +### Requirement: Every tool has one catalog entry + +Every registered tool SHALL have exactly one entry, a `### \`\`` +heading, on the catalog page of its family (the family tag with `_` as +`-`). No entry SHALL name a tool that isn't registered. + +#### Scenario: A new tool without an entry +- **WHEN** a tool is registered and no catalog page has its heading +- **THEN** the catalog check fails and names the tool and the page it belongs on + +#### Scenario: A removed tool's entry +- **WHEN** a page has an entry for a name no tool has +- **THEN** the check fails and names it + +### Requirement: An entry matches the tool's inputs + +An entry's parameter table SHALL list exactly the tool's input fields; a +tool without inputs says `**Parameters:** none`. Its sample call SHALL be +JSON that the tool's input model accepts. + +#### Scenario: A field added to a tool +- **WHEN** a tool gains an input the entry's table doesn't list +- **THEN** the check fails and names the field + +#### Scenario: A placeholder sample +- **WHEN** a sample call has `null` for a required field, or isn't valid JSON +- **THEN** the check fails with the validation error + diff --git a/openspec/specs/release/type-checking/spec.md b/openspec/specs/release/type-checking/spec.md new file mode 100644 index 00000000..4fd55310 --- /dev/null +++ b/openspec/specs/release/type-checking/spec.md @@ -0,0 +1,28 @@ +# release/type-checking Specification + +## Purpose +TBD - created by archiving change mypy-gates-ci. Update Purpose after archive. +## Requirements +### Requirement: mypy gates CI + +CI SHALL run mypy over `src/solidworks_mcp` with the project's +configuration and fail on any error. mypy SHALL check as if on Windows, so +the result doesn't depend on the machine running it. + +#### Scenario: A type error is pushed +- **WHEN** a commit adds code mypy reports an error in +- **THEN** the CI job fails at the type-check step, before the tests + +#### Scenario: The code base is clean +- **WHEN** `make typecheck` runs on `main` after this change +- **THEN** mypy reports no errors + +### Requirement: Suppressions are explained + +A `# type: ignore` SHALL name its error code. A new one SHALL also say +why, on its line or the one above. + +#### Scenario: A bare ignore +- **WHEN** the source contains `# type: ignore` without an error code +- **THEN** the check fails and names the line + diff --git a/openspec/specs/tools/api-help-lookup/spec.md b/openspec/specs/tools/api-help-lookup/spec.md index 4116d929..73e3d4d5 100644 --- a/openspec/specs/tools/api-help-lookup/spec.md +++ b/openspec/specs/tools/api-help-lookup/spec.md @@ -8,8 +8,8 @@ the existing full-text `search_solidworks_api_help`. ### Requirement: Structured lookups for methods and interfaces The adapter SHALL expose `lookup_api_method` (interface + method name → signature) and `lookup_api_interface` (interface name → all indexed -members). An enum-value lookup is not part of this capability yet (issue -#95). Each SHALL indicate no match found, rather than raising, when the name isn't +members). Enum values are looked up by `get_api_enum` (see "Enum values" +below). Each SHALL indicate no match found, rather than raising, when the name isn't in the indexed documentation. Names SHALL match regardless of case, as COM late binding does. A found member SHALL be reported under its real name and casing from the type library, and the response SHALL say when the caller's @@ -173,3 +173,28 @@ answering from any built-in list of names. `auto_discover_if_missing` set - **THEN** the call is accepted and behaves as it would without it +### Requirement: Enum values + +`get_api_enum` SHALL return an enum's members and their integer values +from the installed SolidWorks constants type library. Given a member name +instead, it SHALL return the enum that member belongs to, and say which +member matched. Names SHALL match regardless of case. A name that is +neither SHALL be reported as not found, with the reason, rather than +raising. + +#### Scenario: An enum by name +- **WHEN** `get_api_enum` is called with `swUnitSystem_e` +- **THEN** the result lists its members with `swUnitSystem_IPS` = 3 and `swUnitSystem_MMGS` = 5 + +#### Scenario: A member by name +- **WHEN** it is called with `swunitsystem_ips` +- **THEN** the result is `swUnitSystem_e`, with `matched_member` `swUnitSystem_IPS` + +#### Scenario: An unknown name +- **WHEN** it is called with a name that is neither an enum nor a member +- **THEN** `found` is false and the note says so + +#### Scenario: No constants library +- **WHEN** the constants type library can't be loaded +- **THEN** the index is built without enums, the other lookups still work, and `get_api_enum` says why it has nothing + diff --git a/openspec/specs/tools/macro-execution/spec.md b/openspec/specs/tools/macro-execution/spec.md index 0c9d77d9..a613a6fd 100644 --- a/openspec/specs/tools/macro-execution/spec.md +++ b/openspec/specs/tools/macro-execution/spec.md @@ -19,3 +19,29 @@ SHALL state that number, not the number asked for. - **WHEN** the second of three runs fails - **THEN** the reply is an error saying 1 run completed and the second failed, and no third run is attempted +### Requirement: A macro that waits for the user fails cleanly + +While `execute_macro` runs a macro, a dialog that SolidWorks' process +keeps open longer than `dialog_timeout` seconds SHALL be answered with +Cancel when it has one, or with its only button when it has just one, or +closed when it has no buttons. The call SHALL then return an error with +`error_type` `macro_waited_for_user` that names the dialog's title and +text and how it was answered. A dialog with several buttons and no Cancel +SHALL be left open and logged. The watchdog SHALL make no COM calls. + +#### Scenario: A MsgBox with OK +- **WHEN** a macro shows `MsgBox "Done"` and `dialog_timeout` is 5 +- **THEN** after about 5 s the box is answered OK and the reply is an error naming "Done" and the answer + +#### Scenario: A prompt with Cancel +- **WHEN** a dialog with OK and Cancel stays open past the timeout +- **THEN** it is answered Cancel, never OK + +#### Scenario: Yes and No only +- **WHEN** a dialog's only buttons are Yes and No +- **THEN** neither is pressed, and the log says the dialog needs the user + +#### Scenario: No dialog +- **WHEN** a macro runs for longer than the timeout without opening a dialog +- **THEN** it is not interrupted and its result is returned as before + diff --git a/pyproject.toml b/pyproject.toml index 23233515..23619b80 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,6 +71,8 @@ dev = [ # Code quality and linting "coverage[toml]>=7.3.0", "mypy>=1.6.0", + "types-PyYAML>=6.0", # stubs mypy needs (make typecheck) + "types-defusedxml>=0.7", "ruff>=0.1.0", "black>=23.9.0", @@ -287,6 +289,7 @@ exclude_lines = [ [tool.mypy] python_version = "3.13" +platform = "win32" exclude = [ "src/utils/", ] @@ -310,6 +313,13 @@ module = [ "pywintypes", "win32api", "win32con", + "win32gui", + "win32process", + # Optional extras, not installed by every environment that type-checks. + "PIL", + "PIL.*", + "faiss", + "sentence_transformers", ] ignore_missing_imports = true diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index 49d3cedf..2ceb895d 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -196,8 +196,8 @@ def _should_allow_request(self, bucket: Any = None) -> bool: bucket.half_open_calls = 0 return True return False - elif bucket.state == CircuitState.HALF_OPEN: - return bucket.half_open_calls < self.half_open_max_calls + # HALF_OPEN, the only state left. + return bool(bucket.half_open_calls < self.half_open_max_calls) def _record_success(self, bucket: Any = None) -> None: """Record successful operation. diff --git a/src/solidworks_mcp/adapters/mock_adapter.py b/src/solidworks_mcp/adapters/mock_adapter.py index 8dcf16c3..a190423a 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -14,7 +14,7 @@ import uuid from collections.abc import Callable from datetime import datetime -from typing import Any +from typing import Any, cast from ..exceptions import SolidWorksOperationError from .base import ( @@ -194,7 +194,7 @@ def __init__(self, config: object | None = None) -> None: # component name. See ``_flatten_assembly_components`` for shape. # Empty means "use the canned default fixture" (see list_features). self._assembly_components: dict[str, dict[str, Any]] = {} - self._sketches: dict[str, str] = {} + self._sketches: dict[str, str | None] = {} self._current_sketch: str | None = None self._configurations_made: dict[str, list[str]] = {} #: Per-configuration dimension values and suppressed features. @@ -521,7 +521,7 @@ async def list_features( await asyncio.sleep(self._delays["feature_operation"] / 2) self._operation_count += 1 - is_assembly = self._current_model.type == "Assembly" + is_assembly = self._model_in_use().type == "Assembly" # Seed realistic feature names for empty mock state. if not self._features: @@ -911,7 +911,12 @@ async def add_chamfer( """Mock angle-distance chamfer (see :meth:`_mock_edge_feature`).""" result = await self._mock_edge_feature("Chamfer", distance, edge_names) if result.is_success: - result.data.parameters.update({"angle": angle, "flip": flip}) + feature = cast(SolidWorksFeature, result.data) + feature.parameters = { + **(feature.parameters or {}), + "angle": angle, + "flip": flip, + } return result async def _mock_edge_feature( @@ -1005,9 +1010,13 @@ def _mock_face_at(point: list[float]) -> tuple[float, float, float] | None: return (normal[0], normal[1], normal[2]) return None + def _model_in_use(self) -> SolidWorksModel: + """The open model, for code that has already checked one is open.""" + return cast(SolidWorksModel, self._current_model) + def _mock_configs(self) -> list[str]: """The active model's configurations: Default, any made, and the active one.""" - model = self._current_model + model = self._model_in_use() made = self._configurations_made.setdefault(model.name, ["Default"]) active = model.configuration or "Default" if active not in made: @@ -1112,8 +1121,9 @@ async def activate_configuration(self, name: str) -> AdapterResult[dict[str, Any refused = self._mock_unknown(name) if refused: return refused - previous = self._current_model.configuration or "Default" - self._current_model.configuration = name + model = self._model_in_use() + previous = model.configuration or "Default" + model.configuration = name self._dimensions.update(self._config_dimensions.get(name, {})) if name in self._config_suppressed or previous in self._config_suppressed: self._suppressed_features = set(self._config_suppressed.get(name, set())) @@ -1141,7 +1151,7 @@ async def delete_configuration(self, name: str) -> AdapterResult[dict[str, Any]] status=AdapterResultStatus.ERROR, error=f"'{name}' is the model's only configuration.", ) - if (self._current_model.configuration or "Default") == name: + if (self._model_in_use().configuration or "Default") == name: return AdapterResult( status=AdapterResultStatus.ERROR, error=f"'{name}' is the active configuration; activate another first.", @@ -1212,7 +1222,7 @@ async def create_part( status=AdapterResultStatus.ERROR, error="Not connected to SolidWorks" ) - token = "mm" + token: str | None = "mm" if units is not None and str(units).strip(): token = _normalise_mock_unit_system(str(units)) if token is None: @@ -2828,7 +2838,7 @@ async def get_model_geometry_summary(self) -> AdapterResult[dict[str, Any]]: await asyncio.sleep(self._delays["model_operation"] / 2) self._operation_count += 1 - is_assembly = self._current_model.type == "Assembly" + is_assembly = self._model_in_use().type == "Assembly" summary: dict[str, Any] = { "document_type": "assembly" if is_assembly else "part", "volume_mm3": None, @@ -3152,6 +3162,7 @@ async def save_body_as_part( "file_path": target, "feature": f"Save Bodies{self._operation_count}", "solid_bodies": [body_name], + "closed_documents": [], }, execution_time=self._delays["model_operation"], ) diff --git a/src/solidworks_mcp/adapters/mock_drawing_pack.py b/src/solidworks_mcp/adapters/mock_drawing_pack.py index 40f47080..85dd5848 100644 --- a/src/solidworks_mcp/adapters/mock_drawing_pack.py +++ b/src/solidworks_mcp/adapters/mock_drawing_pack.py @@ -52,12 +52,14 @@ def _pack_state(self) -> dict[str, Any]: def _pack_guard(self, operation: str) -> AdapterResult[dict[str, Any]] | None: """An error unless a drawing is active.""" - guard = self._mock_doc_error({"Drawing"}, operation) # type: ignore[attr-defined] + guard: AdapterResult[dict[str, Any]] | None = self._mock_doc_error( # type: ignore[attr-defined] + {"Drawing"}, operation + ) return guard def _pack_outline(self, name: str) -> Box: """A view's outline: a 100 x 80 mm box per view, left to right.""" - outlines = self._pack_state()["outlines"] + outlines: dict[str, Box] = self._pack_state()["outlines"] if name not in outlines: index = ( self._drawing_views.index(name) if name in self._drawing_views else 0 diff --git a/src/solidworks_mcp/adapters/pywin32_adapter.py b/src/solidworks_mcp/adapters/pywin32_adapter.py index 28377f15..e0d67f9e 100644 --- a/src/solidworks_mcp/adapters/pywin32_adapter.py +++ b/src/solidworks_mcp/adapters/pywin32_adapter.py @@ -5,6 +5,7 @@ """ import asyncio +import contextlib import os import platform import re @@ -37,6 +38,7 @@ SolidWorksTemplatesMixin, bitmap, ) +from .solidworks.dialog_watch import DialogWatch, waited_message from .solidworks.feature_walk import walk_feature_tree from .solidworks.features import _null_callout, _select_feature_by_name from .solidworks.io import _byref_int @@ -1298,7 +1300,7 @@ def try_select_by_component( for candidate in candidate_names: component_name = candidate.split("@", 1)[0] component = self._adapter._attempt( - lambda name=component_name: get_component_by_name(name), # type: ignore[misc] + lambda name=component_name: get_component_by_name(name), default=None, ) if component is None: @@ -1369,13 +1371,13 @@ def try_select_by_feature_tree( # Unflagged, GetNextFeature/Select2 resolve as properties and the # walk dies with "Member not found" (confirmed live 2026-10-13). self._adapter._attempt( - lambda f=feature_ref: sw_type_info.flag_members( # type: ignore[misc] + lambda f=feature_ref: sw_type_info.flag_members( f, "GetNextFeature", "Select2" ), default=0, ) tree_name = self._adapter._attempt( - lambda current_feature=feature_ref: str(current_feature.Name or ""), # type: ignore[misc] + lambda current_feature=feature_ref: str(current_feature.Name or ""), default="", ) if self._matches_candidate_name( @@ -1392,7 +1394,7 @@ def try_select_by_feature_tree( except Exception: pass next_feature = self._adapter._attempt( - lambda current_feature=feature_ref: current_feature.GetNextFeature() # type: ignore[misc] + lambda current_feature=feature_ref: current_feature.GetNextFeature() ) if next_feature is None: break @@ -1646,7 +1648,7 @@ def _list_assembly_component_features( ), default=0, ) - sw_type_info.flag_doc(resolved_doc, resolved_doc_type) + sw_type_info.flag_doc(resolved_doc, resolved_doc_type or 0) component_path, _title = self._adapter._document_routing.document_identity( resolved_doc ) @@ -2057,7 +2059,7 @@ def _handle_com_operation( # type: ignore[override] _settle_after(operation_name) def _attempt( - self, operation: Callable[[], T], default: T | None = None + self, operation: Callable[..., T], default: T | None = None ) -> T | None: """Build internal attempt. @@ -2065,7 +2067,8 @@ def _attempt( blocks throughout operation code. Args: - operation (Callable[[], T]): Callable object executed by the helper. + operation (Callable[..., T]): Called with no arguments (a lambda may + bind loop values as defaults). default (T | None): Fallback value returned when the operation fails. Defaults to None. @@ -2261,13 +2264,13 @@ def _window_aspect(self, target_doc: Any) -> float | None: ``ActiveView``; ``None`` when either is unreadable or not positive. """ view = self._attempt(lambda: target_doc.ActiveView) - size = [ + width, height = ( self._attempt(lambda name=name: int(getattr(view, name))) for name in ("FrameWidth", "FrameHeight") - ] - if not all(isinstance(v, int) and v > 0 for v in size): + ) + if not width or not height or width < 0 or height < 0: return None - return size[0] / size[1] + return width / height def _save_screenshot_with_saveas3( self, target_doc: Any, resolved_path: str @@ -2649,20 +2652,30 @@ def _get_document_type(self) -> str: return type_map.get(doc_type, "Unknown") def _invoke_run_macro2( - self, macro_path: str, module_name: str, proc_name: str + self, + macro_path: str, + module_name: str, + proc_name: str, + dialog_timeout: float = 30.0, ) -> dict[str, Any]: """Call swApp.RunMacro2 and parse the result into a result dict. + A :class:`DialogWatch` runs beside the call: a dialog the macro leaves + waiting longer than ``dialog_timeout`` is answered (Cancel, or its + only button), so the call returns, and the run is then an error. + Args: macro_path: Absolute path to the VBA macro file. module_name: VB module name (parsed from the file or stem fallback). proc_name: Entry-point procedure name, typically "main". + dialog_timeout: Seconds a dialog may wait before it is answered. Returns: dict[str, Any]: {"macro_path", "module_name", "errors"} on success. Raises: - SolidWorksMCPError: If RunMacro2 reports failure. + SolidWorksMCPError: If RunMacro2 reports failure, or the macro + waited on a dialog. """ # nRetval (5th arg) is ByRef Long. Passing a plain 0 raises # DISP_E_TYPEMISMATCH ('Type mismatch.', arg index 5) under pywin32 @@ -2674,9 +2687,14 @@ def _invoke_run_macro2( proc_name, ) retval = _byref_long(0) - result = self.swApp.RunMacro2( # type: ignore[union-attr] - macro_path, module_name, proc_name, 0, retval - ) + pid = self._attempt(lambda: int(self.swApp.GetProcessID())) # type: ignore[union-attr] + watch = DialogWatch(pid, dialog_timeout) if pid else None + with watch or contextlib.nullcontext(): + result = self.swApp.RunMacro2( # type: ignore[union-attr] + macro_path, module_name, proc_name, 0, retval + ) + if watch is not None and watch.seen: + raise SolidWorksMCPError(waited_message(watch.seen, dialog_timeout)) if isinstance(result, (list, tuple)): success, errors = result[0], result[1] else: @@ -2741,6 +2759,11 @@ def _run() -> dict[str, Any]: """ module_name = _parse_vb_module_name(macro_path) proc_name = params.get("proc_name", "main") - return self._invoke_run_macro2(macro_path, module_name, proc_name) + return self._invoke_run_macro2( + macro_path, + module_name, + proc_name, + float(params.get("dialog_timeout") or 30.0), + ) return self._handle_com_operation("execute_macro", _run) diff --git a/src/solidworks_mcp/adapters/solidworks/dialog_watch.py b/src/solidworks_mcp/adapters/solidworks/dialog_watch.py new file mode 100644 index 00000000..2f2f6200 --- /dev/null +++ b/src/solidworks_mcp/adapters/solidworks/dialog_watch.py @@ -0,0 +1,261 @@ +"""Answer a dialog a running macro left waiting for the user (issue #97). + +``RunMacro2`` doesn't return while a macro waits on a dialog (a ``MsgBox``, a +user form, a SolidWorks prompt), and COM calls can't move off the connect +thread to time it out. :class:`DialogWatch` runs beside the call on its own +thread and uses only Win32 window calls, never COM. When a dialog the +SolidWorks process opened stays up longer than the timeout, it reads the +dialog and answers it with the non-committal choice: + +- **Cancel**, when the dialog has that button; +- else its **only button**, when it has just one (an OK acknowledgement); +- else, with **no buttons** (a VBA user form), it closes the window. + +A dialog with several buttons and no Cancel (Yes/No) is left for the user +and logged: pressing Yes or No could change the model. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass, field +from types import TracebackType +from typing import Any, Protocol + +from loguru import logger + +#: Window classes of a message box or common dialog, and of a VBA user form. +DIALOG_CLASSES = frozenset({"#32770", "ThunderDFrame"}) +_WM_CLOSE = 0x0010 +_WM_COMMAND = 0x0111 + + +@dataclass(frozen=True) +class DialogSeen: + """A dialog the watch found waiting, and what it did. + + Attributes: + title: The dialog's title. + text: Its message, the static texts joined. + buttons: Its button labels, without ``&``. + answer: ``"Cancel"``, the single button's label, ``"closed"``, or + None when it was left for the user. + """ + + title: str + text: str + buttons: tuple[str, ...] + answer: str | None + + def describe(self) -> str: + """One line: the dialog, its text, and how it was answered.""" + said = f": {self.text!r}" if self.text else "" + if self.answer is None: + how = "left open: it has no Cancel and more than one button" + elif self.answer == "closed": + how = "closed" + else: + how = f"answered {self.answer!r}" + return f"{self.title!r}{said} ({how})" + + +class Windows(Protocol): + """The Win32 window calls the watch makes.""" + + def dialogs(self, pid: int) -> list[int]: + """Visible top-level dialog windows of process ``pid``.""" + + def title(self, hwnd: int) -> str: + """A window's title.""" + + def children(self, hwnd: int) -> list[tuple[int, str, str]]: + """A window's children as ``(hwnd, class name, text)``.""" + + def control_id(self, hwnd: int) -> int: + """A child control's ID.""" + + def post(self, hwnd: int, message: int, wparam: int, lparam: int) -> None: + """Post a message to a window without waiting for it.""" + + +class Win32Windows: + """:class:`Windows` over ``win32gui`` and ``win32process``. + + Args: + gui: The ``win32gui`` module; imported when None. + process: The ``win32process`` module; imported when None. + """ + + def __init__(self, gui: Any = None, process: Any = None) -> None: + """Keep the two modules.""" + if gui is None or process is None: + import win32gui + import win32process + + gui, process = gui or win32gui, process or win32process + self._gui = gui + self._process = process + + def dialogs(self, pid: int) -> list[int]: + """Visible top-level dialog windows of process ``pid``.""" + found: list[int] = [] + + def _visit(hwnd: int, _extra: Any) -> bool: + if ( + self._gui.IsWindowVisible(hwnd) + and self._gui.GetClassName(hwnd) in DIALOG_CLASSES + and self._process.GetWindowThreadProcessId(hwnd)[1] == pid + ): + found.append(hwnd) + return True + + self._gui.EnumWindows(_visit, None) + return found + + def title(self, hwnd: int) -> str: + """A window's title.""" + return str(self._gui.GetWindowText(hwnd)) + + def children(self, hwnd: int) -> list[tuple[int, str, str]]: + """A window's children as ``(hwnd, class name, text)``.""" + kids: list[tuple[int, str, str]] = [] + + def _visit(child: int, _extra: Any) -> bool: + kids.append( + (child, self._gui.GetClassName(child), self._gui.GetWindowText(child)) + ) + return True + + self._gui.EnumChildWindows(hwnd, _visit, None) + return kids + + def control_id(self, hwnd: int) -> int: + """A child control's ID.""" + return int(self._gui.GetDlgCtrlID(hwnd)) + + def post(self, hwnd: int, message: int, wparam: int, lparam: int) -> None: + """Post a message to a window without waiting for it.""" + self._gui.PostMessage(hwnd, message, wparam, lparam) + + +@dataclass +class DialogWatch: + """Watch process ``pid`` for a dialog left waiting, while a call runs. + + Use it as a context manager around the blocking call. Dialogs already + open when it starts are ignored. + + Attributes: + pid: The SolidWorks process ID. + timeout: Seconds a dialog may stay open before it is answered. + windows: The window calls; the real Win32 ones by default. + poll: Seconds between looks. + clock: The time source, in seconds. + seen: Every dialog answered or left, in the order found. + """ + + pid: int + timeout: float + windows: Windows = field(default_factory=Win32Windows) + poll: float = 0.5 + clock: Callable[[], float] = time.monotonic + seen: list[DialogSeen] = field(default_factory=list) + + def __post_init__(self) -> None: + """Set up the thread state.""" + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._before: set[int] = set() + self._first: dict[int, float] = {} + self._handled: set[int] = set() + + def __enter__(self) -> DialogWatch: + """Note the dialogs already open and start watching.""" + self._before = set(self.windows.dialogs(self.pid)) + self._thread = threading.Thread( + target=self._run, name="macro-dialog-watch", daemon=True + ) + self._thread.start() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Stop watching.""" + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=5) + + def _run(self) -> None: + """Look every ``poll`` seconds until stopped; a failure ends the watch.""" + try: + while not self._stop.wait(self.poll): + self.check() + except Exception as exc: # noqa: BLE001 - a watch never fails the macro + logger.warning("[macro] the dialog watch stopped: {}", exc) + + def check(self) -> None: + """Answer any new dialog that has been open longer than the timeout.""" + now = self.clock() + for hwnd in self.windows.dialogs(self.pid): + if hwnd in self._before or hwnd in self._handled: + continue + opened = self._first.setdefault(hwnd, now) + if now - opened >= self.timeout: + self._handled.add(hwnd) + self._answer(hwnd) + + def _answer(self, hwnd: int) -> None: + """Read one dialog and answer it with the non-committal choice.""" + kids = self.windows.children(hwnd) + text = " ".join( + t.strip() for _h, cls, t in kids if cls == "Static" and t.strip() + ) + buttons = [ + (h, t.replace("&", "").strip()) for h, cls, t in kids if cls == "Button" + ] + labels = tuple(label for _h, label in buttons) + cancel = [h for h, label in buttons if label.lower() == "cancel"] + answer: str | None + if cancel or len(buttons) == 1: + button = cancel[0] if cancel else buttons[0][0] + answer = "Cancel" if cancel else buttons[0][1] + # The button's own click: WM_COMMAND with its ID (BN_CLICKED is 0). + self.windows.post( + hwnd, _WM_COMMAND, self.windows.control_id(button), button + ) + elif not buttons: + answer = "closed" + self.windows.post(hwnd, _WM_CLOSE, 0, 0) + else: + answer = None + seen = DialogSeen(self.windows.title(hwnd), text, labels, answer) + self.seen.append(seen) + if answer is None: + logger.warning("[macro] a dialog needs the user: {}", seen.describe()) + else: + logger.warning("[macro] a dialog was waiting: {}", seen.describe()) + + +def waited_message(seen: list[DialogSeen], timeout: float) -> str: + """The error for a macro that waited on dialogs. + + Args: + seen: The dialogs the watch found. + timeout: The timeout that was used, in seconds. + + Returns: + str: What happened, and that macros here must not wait for the user. + """ + dialogs = "; ".join(d.describe() for d in seen) + return ( + f"The macro waited for the user: after {timeout:g} s a dialog was still " + f"open, {dialogs}. It may have done part of its work before that. " + "Macros run by execute_macro must not wait for the user: remove the " + "MsgBox, form or prompt, or raise dialog_timeout." + ) diff --git a/src/solidworks_mcp/adapters/solidworks/dimension_layout.py b/src/solidworks_mcp/adapters/solidworks/dimension_layout.py index 2f4da348..547a5cc2 100644 --- a/src/solidworks_mcp/adapters/solidworks/dimension_layout.py +++ b/src/solidworks_mcp/adapters/solidworks/dimension_layout.py @@ -255,7 +255,7 @@ def length_inside(seg: Segment, box: Box) -> float: t1 = min(t1, t) if t0 > t1: return 0.0 - return (t1 - t0) * (dx * dx + dy * dy) ** 0.5 + return float((t1 - t0) * (dx * dx + dy * dy) ** 0.5) def shift_box(box: Box, dx: float, dy: float) -> Box: @@ -395,10 +395,12 @@ def _leader_inside( def _inside_candidates( - dim: DimensionGeometry, outline: Box + dim: DimensionGeometry, outline: Box, anchor: tuple[float, float] ) -> list[tuple[str, float, float]]: - """Moves putting a leader's text inside its view, toward the view's centre.""" - anchor = leader_anchor(dim) + """Moves putting a leader's text inside its view, toward the view's centre. + + ``anchor`` is where the leader meets the part (:func:`leader_anchor`). + """ tb = dim.text_box w, h = tb[2] - tb[0], tb[3] - tb[1] cx, cy = (tb[0] + tb[2]) / 2.0, (tb[1] + tb[3]) / 2.0 @@ -637,11 +639,13 @@ def plan_layout( continue chosen = None candidates = _candidates(dim, outline) - if dim.key in (inside_first or set()) and dim.orientation is None: - candidates = _inside_candidates(dim, outline) + candidates + anchor = leader_anchor(dim) + try_inside = dim.key in (inside_first or set()) and dim.orientation is None + if try_inside and anchor is not None: + candidates = _inside_candidates(dim, outline, anchor) + candidates features = [ *feature_points(dims, dim.view, outline, skip=dim.key), - leader_anchor(dim), + anchor, ] for side, dx, dy in candidates: box = shift_box(dim.text_box, dx, dy) diff --git a/src/solidworks_mcp/adapters/solidworks/documentation.py b/src/solidworks_mcp/adapters/solidworks/documentation.py index 4cfab5b5..92ea9307 100644 --- a/src/solidworks_mcp/adapters/solidworks/documentation.py +++ b/src/solidworks_mcp/adapters/solidworks/documentation.py @@ -132,12 +132,12 @@ def _parse_material_library(path: str) -> list[dict[str, str]]: for each material; empty when the file cannot be parsed or is refused. """ try: - root = ET.parse(path).getroot() + tree = ET.parse(path) except (ET.ParseError, OSError, DefusedXmlException): return [] database = os.path.splitext(os.path.basename(path))[0] materials: list[dict[str, str]] = [] - for classification in root.iter(): + for classification in tree.iter(): if classification.tag.rsplit("}", 1)[-1] != "classification": continue class_name = classification.get("name", "") @@ -246,10 +246,10 @@ def _material_entry( ) for path in ordered: try: - root = ET.parse(path).getroot() + tree = ET.parse(path) except (ET.ParseError, OSError, DefusedXmlException): continue - for element in root.iter(): + for element in tree.iter(): if element.tag.rsplit("}", 1)[-1] != "material": continue if element.get("name") == name: @@ -415,7 +415,7 @@ def _handle_com_operation( ) -> AdapterResult[Any]: ... def _attempt( - self, operation: Callable[[], Any], default: Any = None + self, operation: Callable[..., Any], default: Any = None ) -> Any: ... def _get_attr_or_call(self, obj: Any, name: str) -> Any: ... @@ -1295,7 +1295,7 @@ def _import_dimensions( self._attempt(lambda: model.ClearSelection2(True), default=None) self._attempt(lambda: model.EditRebuild3(), default=None) - per_view = [] + per_view: list[dict[str, Any]] = [] for name in names: after = self._view_dimension_count(views[name]) per_view.append( @@ -1512,7 +1512,8 @@ def _collect_layout( continue outline = self._attempt(lambda v=view: v.GetOutline(), default=None) if isinstance(outline, (list, tuple)) and len(outline) >= 4: - outlines[name] = tuple(float(c) for c in outline[:4]) + left, bottom, right, top = (float(c) for c in outline[:4]) + outlines[name] = (left, bottom, right, top) for an, geometry in self._read_view_dimensions(view, name): annotations[geometry.key] = an geometries.append(geometry) @@ -1557,7 +1558,9 @@ def _arrange_layout( _layout.attach_boxes(geometries, attached or {}) before = _layout.find_overlaps(geometries, outlines, sheet, obstacles) after = before - moved, unplaced, passes, trace = 0, [], 0, [] + unplaced: list[str] = [] + trace: list[Any] = [] + moved, passes = 0, 0 # The first pass plans every movable dimension from where it was # imported. SolidWorks does not always draw a dimension where the # plan put it, so later passes re-plan only the dimensions still in diff --git a/src/solidworks_mcp/adapters/solidworks/drawing_standard.py b/src/solidworks_mcp/adapters/solidworks/drawing_standard.py index 7b69b6ee..3872a6c4 100644 --- a/src/solidworks_mcp/adapters/solidworks/drawing_standard.py +++ b/src/solidworks_mcp/adapters/solidworks/drawing_standard.py @@ -492,7 +492,7 @@ def _handle_com_operation( ) -> AdapterResult[Any]: ... def _attempt( - self, operation: Callable[[], Any], default: Any = None + self, operation: Callable[..., Any], default: Any = None ) -> Any: ... def _require_drawing(self) -> AdapterResult[Any] | None: ... @@ -1270,7 +1270,8 @@ def _note_box( lambda: self._dimension_geometry(an, "note", "sheet"), default=None ) if geometry is not None: - return geometry.text_box + box: Box = geometry.text_box + return box width = 0.62 * height * len(fallback_text) return (x, y - height, x + width, y) @@ -1428,8 +1429,10 @@ def _fit_views(self, s: _Sheet) -> dict[str, Any]: def _fit_iso(self, s: _Sheet) -> None: """Scale the isometric to the largest standard scale that fits its cell.""" - s.iso_scale = iso_fit_scale(s.iso_size, s.cells["iso"]) - iso = s.views[s.iso_name] + # Called once the isometric is placed, so its size and name are set. + size = cast("tuple[float, float]", s.iso_size) + s.iso_scale = iso_fit_scale(size, s.cells["iso"]) + iso = s.views[cast(str, s.iso_name)] ratio = _double_array([float(s.iso_scale[0]), float(s.iso_scale[1])]) self._attempt(lambda: setattr(iso, "UseSheetScale", False), default=None) self._attempt(lambda: setattr(iso, "ScaleRatio", ratio), default=None) @@ -1534,7 +1537,7 @@ def _format_notes(self, drawing: Any) -> list[tuple[Any, str, Box | None]]: lambda: _sw_type_info.flagged(drawing.GetFirstView(), "IView"), default=None, ) - found = [] + found: list[Any] = [] note = self._attempt(lambda: sheet_view.GetFirstNote(), default=None) while note is not None and len(found) < 500: n = _sw_type_info.flagged(note, "INote") @@ -1900,7 +1903,8 @@ def failed(error: str) -> AdapterResult[dict[str, Any]]: if name == "bom": data["bom"] = done.data if name == "views": - data["hidden_lines_visible"] = done.data["hidden_lines_visible"] + views_data = cast("dict[str, Any]", done.data) + data["hidden_lines_visible"] = views_data["hidden_lines_visible"] if name == "check": data["overlap_check"] = done.data data.update( @@ -1967,13 +1971,13 @@ def failed(error: str) -> AdapterResult[dict[str, Any]]: ) if overlaps: check = data["overlap_check"] - found = [ + remaining = [ *check.get("remaining_overlaps", []), *check.get("annotation_overlaps", []), ] named = "; ".join( f"{o['dimension']} vs {o['conflicts_with']} ({o['kind']})" - for o in found[:5] + for o in remaining[:5] ) return failed( f"Drawing saved but {overlaps} overlap(s) remain - the no-overlap " diff --git a/src/solidworks_mcp/adapters/solidworks/face_selection.py b/src/solidworks_mcp/adapters/solidworks/face_selection.py index 138164b8..43e0a3f4 100644 --- a/src/solidworks_mcp/adapters/solidworks/face_selection.py +++ b/src/solidworks_mcp/adapters/solidworks/face_selection.py @@ -239,7 +239,7 @@ def describe_edge(adapter: Any, edge: Any) -> dict[str, Any]: elif _attempt(adapter, lambda: curve.IsLine(), False): entry["curve"] = "linear" - points = [] + points: list[Any] = [] for getter in ("GetStartVertex", "GetEndVertex"): vertex = _attempt(adapter, lambda g=getter: getattr(edge, g)()) if vertex is None: diff --git a/src/solidworks_mcp/adapters/solidworks/features.py b/src/solidworks_mcp/adapters/solidworks/features.py index c86432e1..5209f8d9 100644 --- a/src/solidworks_mcp/adapters/solidworks/features.py +++ b/src/solidworks_mcp/adapters/solidworks/features.py @@ -5,7 +5,7 @@ import math from datetime import datetime from types import SimpleNamespace -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from .. import sw_type_info from ..base import ( @@ -13,6 +13,7 @@ AdapterResultStatus, ExtrusionParameters, LoftParameters, + MassProperties, RevolveParameters, SolidWorksFeature, SweepParameters, @@ -30,6 +31,17 @@ class SolidWorksFeaturesMixin: """Expose SolidWorks feature methods via mixin-local implementation helpers.""" + if TYPE_CHECKING: + # Provided by the adapter this mixin is part of. + @staticmethod + def _adapter(obj: Any) -> Any: ... + + async def get_mass_properties(self) -> AdapterResult[MassProperties]: ... + + async def list_features( + self, include_suppressed: bool = False, max_assembly_depth: int = 2 + ) -> AdapterResult[list[dict[str, Any]]]: ... + async def create_extrusion( self, params: ExtrusionParameters ) -> AdapterResult[SolidWorksFeature]: @@ -107,8 +119,11 @@ async def add_fillet( "faces of the body." ), ) - result.data.properties["volume_before"] = volume_before - result.data.properties["volume_after"] = volume_after + result.data.properties = { + **(result.data.properties or {}), + "volume_before": volume_before, + "volume_after": volume_after, + } return result async def add_chamfer( @@ -3355,7 +3370,7 @@ def _create_reference_point_impl( ) along_type = _SW_REF_POINT_ALONG_CURVE_DISTANCE along_value = float(distance) / 1000.0 - else: + elif percent is not None: # exactly one of the two is given if not 0.0 < float(percent) < 100.0: return AdapterResult( status=AdapterResultStatus.ERROR, diff --git a/src/solidworks_mcp/adapters/solidworks/hole_library.py b/src/solidworks_mcp/adapters/solidworks/hole_library.py index 76ed6b5d..5ff05c31 100644 --- a/src/solidworks_mcp/adapters/solidworks/hole_library.py +++ b/src/solidworks_mcp/adapters/solidworks/hole_library.py @@ -31,7 +31,7 @@ from sqlalchemy import Engine, MetaData, Table, inspect from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.pool import NullPool -from sqlmodel import create_engine, select +from sqlmodel import create_engine from ...exceptions import InputRefused @@ -396,7 +396,8 @@ class SqliteHoleLibrary(HoleLibrary): Table names come from the library's own rows; each is checked against the file's own table list and reflected, never taken from a caller, and - rows are read with SQLModel's ``select()``: no SQL is built as text. + rows are read with the reflected table's ``select()``: no SQL is built as + text. Rows are read once per table, and the file is closed after each read, so SolidWorks (or Toolbox Settings) can always replace it. @@ -428,7 +429,7 @@ def _rows(self, table: str) -> list[dict[str, Any]]: No SQL is written as text: the table is reflected from the file (named only if the file's own table list has it) and read with - ``select()``, so SQLAlchemy quotes every identifier. + its ``select()``, so SQLAlchemy quotes every identifier. Raises: HoleLibraryError: When the file can't be read or lacks the table. @@ -451,7 +452,7 @@ def _rows(self, table: str) -> list[dict[str, Any]]: reflected = Table(real, MetaData(), autoload_with=connection) rows = [ {str(key).lower(): value for key, value in row.items()} - for row in connection.execute(select(reflected)).mappings() + for row in connection.execute(reflected.select()).mappings() ] except SQLAlchemyError as exc: raise HoleLibraryError( @@ -653,7 +654,7 @@ def _sizes(table: list[tuple[str, dict[str, float]]]) -> list[dict[str, Any]]: def _metric( - column: str, values: dict[str, float] + column: str, values: dict[float, float] ) -> list[tuple[str, dict[str, float]]]: """``M`` rows with a diameter and one more column.""" return [(f"M{n:g}", {"diameter": n, column: v}) for n, v in values.items()] diff --git a/src/solidworks_mcp/adapters/solidworks/io.py b/src/solidworks_mcp/adapters/solidworks/io.py index 53417aa0..144e9dc3 100644 --- a/src/solidworks_mcp/adapters/solidworks/io.py +++ b/src/solidworks_mcp/adapters/solidworks/io.py @@ -1034,6 +1034,51 @@ def _describe_open_document( } +def _open_documents(adapter: Any) -> list[dict[str, Any]]: + """Every open document's title, path and type (``_describe_open_document``).""" + docs = _coerce_dispatch_sequence( + adapter._attempt(lambda: adapter.swApp.GetDocuments(), default=None) + ) + return [_describe_open_document(adapter, d, None, None) for d in docs] + + +def _close_new_unsaved_assemblies( + adapter: Any, before: set[str | None], return_to: str | None +) -> list[str]: + """Close assemblies a call opened and never saved; reactivate ``return_to``. + + SolidWorks' Save Bodies feature can leave a new, unsaved assembly open + (issue #101). Only a document that wasn't open before the call, is an + assembly and has no file is closed, so nothing the user had open is + touched and nothing saved is lost. + + Args: + adapter: A connected adapter. + before: Titles of the documents open before the call. + return_to: Title of the document to make active again, if one was + closed. + + Returns: + list[str]: Titles of the documents closed. + """ + closed = [] + for doc in _open_documents(adapter): + title = doc["title"] + if ( + title + and title not in before + and doc["type"] == "Assembly" + and not doc["path"] + ): + adapter._attempt(lambda t=title: adapter.swApp.CloseDoc(t)) + closed.append(title) + if closed and return_to: + adapter._attempt( + lambda: adapter.swApp.ActivateDoc3(return_to, False, 0, _byref_int()) + ) + return closed + + # --- Geometry summary ------------------------------------------------------ # Read-only helpers for ``get_model_geometry_summary``. None of them rebuilds # the model or touches the selection (COM pitfall #23), so the summary can be @@ -3705,7 +3750,9 @@ async def save_body_as_part( Returns: AdapterResult[dict[str, Any]]: The body, the written path, the new - feature's name, and every solid-body name found. ``ERROR`` when + feature's name, every solid-body name found, and + ``closed_documents``: any new, unsaved assembly SolidWorks opened + alongside, which is closed (issue #101). ``ERROR`` when the active document is not a part, the body is absent, the parent directory is missing, or no file was written. """ @@ -3777,6 +3824,10 @@ def _save_body() -> dict[str, Any]: if os.path.exists(target): os.remove(target) + open_before = {d["title"] for d in _open_documents(adapter)} + part_title = adapter._attempt( + lambda: adapter._get_attr_or_call(model, "GetTitle"), default=None + ) feature = adapter._attempt( lambda: manager.CreateSaveBodyFeature( _variant_array(pythoncom.VT_DISPATCH, [match]), @@ -3788,6 +3839,9 @@ def _save_body() -> dict[str, Any]: default=None, ) adapter._attempt(lambda: model.EditRebuild3(), default=None) + closed = _close_new_unsaved_assemblies( + adapter, open_before, str(part_title) if part_title else None + ) if not os.path.exists(target): raise Exception( @@ -3808,6 +3862,7 @@ def _save_body() -> dict[str, Any]: "file_path": target, "feature": str(feat_name) if feat_name else None, "solid_bodies": names, + "closed_documents": closed, } return cast( diff --git a/src/solidworks_mcp/adapters/solidworks/part_features.py b/src/solidworks_mcp/adapters/solidworks/part_features.py index 622838a4..a34bc39f 100644 --- a/src/solidworks_mcp/adapters/solidworks/part_features.py +++ b/src/solidworks_mcp/adapters/solidworks/part_features.py @@ -116,7 +116,7 @@ def _cap_thread_depth( if data is None: return None data = sw_type_info.flagged(data, "IWizardHoleFeatureData2") - thread = adapter._attempt(lambda: float(data.ThreadDepth), None) + thread: float | None = adapter._attempt(lambda: float(data.ThreadDepth), None) cap = depth_m * _THREAD_SHARE if thread is None or thread <= cap: return thread diff --git a/src/solidworks_mcp/adapters/solidworks/selection.py b/src/solidworks_mcp/adapters/solidworks/selection.py index 9dd428f9..74cbf9d4 100644 --- a/src/solidworks_mcp/adapters/solidworks/selection.py +++ b/src/solidworks_mcp/adapters/solidworks/selection.py @@ -35,7 +35,7 @@ def _handle_com_operation( ) -> AdapterResult[Any]: ... def _attempt( - self, operation: Callable[[], Any], *, default: Any = None + self, operation: Callable[..., Any], *, default: Any = None ) -> Any: ... async def list_features( @@ -130,7 +130,9 @@ async def select_feature( ) def _select() -> dict[str, Any]: - payload = self._feature_selector.select_feature(feature_name, append) + payload: dict[str, Any] = self._feature_selector.select_feature( + feature_name, append + ) if not payload or not payload.get("selected"): raise LookupError( f"Feature not found or could not be selected: {feature_name}" diff --git a/src/solidworks_mcp/adapters/solidworks/sketch.py b/src/solidworks_mcp/adapters/solidworks/sketch.py index f139ba51..fac1744c 100644 --- a/src/solidworks_mcp/adapters/solidworks/sketch.py +++ b/src/solidworks_mcp/adapters/solidworks/sketch.py @@ -1392,7 +1392,7 @@ def _try_create_angular_dimension() -> Any: if not adapter._select_sketch_entity(entity2_obj, append=True): raise Exception(f"Failed to select secondary entity '{entity2}'") display_dim = _two_entity_linear_dimension( - adapter, (entity1, entity2), entity1_obj, entity2_obj, direction + adapter, (entity1, entity2 or ""), entity1_obj, entity2_obj, direction ) else: adapter.currentModel.ClearSelection2(True) diff --git a/src/solidworks_mcp/config.py b/src/solidworks_mcp/config.py index e6ffe9b3..40d53e77 100644 --- a/src/solidworks_mcp/config.py +++ b/src/solidworks_mcp/config.py @@ -401,6 +401,14 @@ class SolidWorksMCPConfig(BaseModel): "call_tool in their place) (SOLIDWORKS_MCP_TOOL_MODE).", ) + # === Running VBA source (queue item 26) === + allow_vba_source: bool = Field( + default=False, + description="Let execute_macro run VBA source text, not only macro " + "files. VBA can do anything the user can, so it is off unless set " + "(SOLIDWORKS_MCP_ALLOW_VBA_SOURCE).", + ) + model_config = ConfigDict( extra="allow" # Allow extra fields for test configurations ) diff --git a/src/solidworks_mcp/doc_links/links.py b/src/solidworks_mcp/doc_links/links.py index 670b3da8..ca153047 100644 --- a/src/solidworks_mcp/doc_links/links.py +++ b/src/solidworks_mcp/doc_links/links.py @@ -145,9 +145,10 @@ def check_internal(root: Path, site: Site, links: Iterable[Link]) -> list[str]: ) continue if path.is_dir(): - path = _index_of(path) - if path is None: + index = _index_of(path) + if index is None: continue + path = index if anchor and path.suffix == ".md": if path not in ids: ids[path] = heading_ids(path.read_text(encoding="utf-8")) diff --git a/src/solidworks_mcp/progress/generate.py b/src/solidworks_mcp/progress/generate.py index 573ce2d6..8c916ec8 100644 --- a/src/solidworks_mcp/progress/generate.py +++ b/src/solidworks_mcp/progress/generate.py @@ -26,9 +26,10 @@ from dataclasses import dataclass from html import escape from pathlib import Path -from typing import Any +from typing import Any, cast from fastmcp import FastMCP +from fastmcp.tools.function_tool import FunctionTool from fastmcp.utilities.docstring_parsing import parse_docstring from ..adapters.mock_adapter import MockSolidWorksAdapter @@ -78,7 +79,8 @@ async def tool_rows() -> list[ToolRow]: mcp = FastMCP("progress") await register_tools(mcp, MockSolidWorksAdapter({}), {}) rows = [] - for tool in await mcp.list_tools(): + for listed in await mcp.list_tools(): + tool = cast(FunctionTool, listed) # every tool is a decorated function support = SUPPORT_LEVELS[tool.name] text = parse_docstring(tool.fn).description or "" rows.append( diff --git a/src/solidworks_mcp/selftest/cli.py b/src/solidworks_mcp/selftest/cli.py index 95a81114..98d6dd16 100644 --- a/src/solidworks_mcp/selftest/cli.py +++ b/src/solidworks_mcp/selftest/cli.py @@ -11,7 +11,7 @@ import subprocess from collections.abc import Callable from pathlib import Path -from typing import Any +from typing import Any, cast import typer @@ -92,7 +92,7 @@ async def _start_server(config: SolidWorksMCPConfig) -> Any: config.model_copy(update={"toolsets": "all", "tool_mode": "list"}) ) await server.setup() - await server.adapter.connect() + await cast(Any, server.adapter).connect() # setup() created it return server diff --git a/src/solidworks_mcp/selftest/runner.py b/src/solidworks_mcp/selftest/runner.py index 4a11d56a..3ea2f37e 100644 --- a/src/solidworks_mcp/selftest/runner.py +++ b/src/solidworks_mcp/selftest/runner.py @@ -12,8 +12,13 @@ class Area(Protocol): """One part of the selftest: what it needs, and how it runs.""" - name: str - needs: tuple[str, ...] + @property + def name(self) -> str: + """The area's name in the report.""" + + @property + def needs(self) -> tuple[str, ...]: + """The areas whose saved files this one opens.""" async def run(self, ctx: Context, checks: list[Check]) -> None: """Call tools and append a check per value read back. diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/vba-fallback.md b/src/solidworks_mcp/skills/solidworks-mcp/references/vba-fallback.md index ccbe87f8..081366b4 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/vba-fallback.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/vba-fallback.md @@ -27,4 +27,5 @@ After the user runs a macro, read the model back (`get_model_info`, macro did. To look up a SolidWorks API call while writing VBA, use -`lookup_api_method`, `lookup_api_interface` or `search_solidworks_api_help`. +`lookup_api_method`, `lookup_api_interface` or `search_solidworks_api_help`; +for the integer value of an enum argument, `get_api_enum`. diff --git a/src/solidworks_mcp/tools/docs_discovery.py b/src/solidworks_mcp/tools/docs_discovery.py index 579b8673..a59a254d 100644 --- a/src/solidworks_mcp/tools/docs_discovery.py +++ b/src/solidworks_mcp/tools/docs_discovery.py @@ -19,7 +19,7 @@ import time from dataclasses import dataclass from pathlib import Path -from typing import Any, Literal, TypeVar +from typing import Any, Literal, TypeVar, cast from fastmcp import FastMCP from loguru import logger @@ -30,12 +30,16 @@ from .tool_boundary import ToolOperationError, normalize_input, with_tool_boundary from .type_library import ( Access, + ApiEnum, + ApiEnumMember, ApiMember, ApiMethod, ApiParameter, ApiProperty, TypeLibraryUnavailable, + index_enums, index_type_library, + load_constants_library, load_type_library, target_version, year_of, @@ -43,7 +47,8 @@ # Index files written before the index came from the type library are "1.0"; # their member lists were largely hand-typed and are never answered from. -INDEX_FORMAT = "2.0" +# "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 = ( @@ -56,7 +61,8 @@ MemberType = Literal["method", "property"] #: Validates one saved member record into its model. -_MEMBER: TypeAdapter[ApiMethod | ApiProperty] = TypeAdapter(ApiMember) +#: (pydantic takes the annotated union; some versions' stubs expect a class.) +_MEMBER: TypeAdapter[ApiMethod | ApiProperty] = TypeAdapter(cast(Any, ApiMember)) #: Each interface record's name lists, by member type. _MEMBER_LISTS: tuple[tuple[MemberType, str], ...] = ( @@ -186,6 +192,8 @@ def __init__( "type_library": None, "solidworks_version": None, "com_objects": {}, + "enums": {}, + "enums_note": None, "vba_references": {}, "total_methods": 0, "total_properties": 0, @@ -219,6 +227,28 @@ def discover_com_objects(self) -> dict[str, Any]: ) return {name: record.model_dump() for name, record in interfaces.items()} + def discover_enums(self) -> dict[str, Any]: + """Index every enum in the constants library of the version just read. + + Call after :meth:`discover_com_objects`. When the constants library + can't be loaded, the index has no enums and ``enums_note`` says why; + the other lookups are unaffected. + + Returns: + dict[str, Any]: Enum name -> its description and members, as saved. + """ + major, minor = ( + int(p) for p in self.index["type_library"]["version"].split(".") + ) + try: + enums = index_enums(load_constants_library(major, minor)) + except TypeLibraryUnavailable as exc: + logger.warning("[docs_discovery] No enum values: {}", exc) + self.index["enums_note"] = str(exc) + return {} + logger.info("[docs_discovery] Constants library: {} enums", len(enums)) + return {name: record.model_dump() for name, record in enums.items()} + def discover_vba_references(self) -> dict[str, Any]: """Discover VBA/TypeLib references via the Windows Registry. @@ -251,6 +281,7 @@ def discover_all(self, include_vba: bool = True) -> dict[str, Any]: """ logger.info("Discovering COM objects...") self.index["com_objects"] = self.discover_com_objects() + self.index["enums"] = self.discover_enums() if include_vba: logger.info("Discovering VBA references...") @@ -428,6 +459,22 @@ class LookupApiInterfaceInput(ApiIndexInput): ) +class GetApiEnumInput(ApiIndexInput): + """Input schema for ``get_api_enum``. + + Attributes: + name (str): An enum name, or one of its members' names. + """ + + name: str = Field( + description=( + "An enum name, e.g. 'swUnitSystem_e', or a member name, e.g. " + "'swUnitSystem_IPS'; case does not matter" + ), + min_length=2, + ) + + class FindRelatedApiInput(ApiIndexInput): """Input schema for ``find_related_api_members``. @@ -513,6 +560,33 @@ class InterfaceLookup(BaseModel): note: str | None = Field(default=None, description="Why no index could be built") +class EnumLookup(BaseModel): + """``get_api_enum``'s result. + + Attributes: + found (bool): Whether an enum or member of that name is indexed. + name (str): The name asked for. + enum (str | None): The enum, as SolidWorks spells it. + matched_member (str | None): The member asked for, when the name was + a member's. + description (str | None): The enum's help string, if any. + members (list[ApiEnumMember] | None): Its members and their values. + note (str | None): Why there's no match. + """ + + found: bool = Field(description="True when an enum or member of that name exists") + name: str = Field(description="The name asked for") + enum: str | None = Field(default=None, description="The enum's name") + matched_member: str | None = Field( + default=None, description="The member asked for, as SolidWorks spells it" + ) + description: str | None = Field(default=None, description="Help string") + members: list[ApiEnumMember] | None = Field( + default=None, description="Members in declaration order, with their values" + ) + note: str | None = Field(default=None, description="Why there is no match") + + class SearchMatch(BaseModel): """One ``search_solidworks_api_help`` match. @@ -725,7 +799,9 @@ def _maybe_refresh_index( return discovery.index, fresh_file -_LookupResultT = TypeVar("_LookupResultT", MemberLookup, InterfaceLookup, RelatedLookup) +_LookupResultT = TypeVar( + "_LookupResultT", MemberLookup, InterfaceLookup, EnumLookup, RelatedLookup +) @dataclass(frozen=True) @@ -949,6 +1025,42 @@ def _lookup_interface(index: dict[str, Any], interface: str) -> InterfaceLookup: ) +def _lookup_enum(index: dict[str, Any], name: str) -> EnumLookup: + """An enum's members and values, found by its name or a member's. + + Args: + index (dict[str, Any]): The index. + name (str): An enum or member name; case is ignored. + + Returns: + EnumLookup: The enum, or a no-match saying why. + """ + enums: dict[str, Any] = index.get("enums") or {} + lowered = name.lower() + for enum_name, record in enums.items(): + enum = ApiEnum.model_validate(record) + matched = None + if enum_name.lower() != lowered: + matched = next( + (m.name for m in enum.members if m.name.lower() == lowered), None + ) + if matched is None: + continue + return EnumLookup( + found=True, + name=name, + enum=enum_name, + matched_member=matched, + description=enum.description, + members=enum.members, + ) + note = index.get("enums_note") or ( + f"'{name}' is neither an enum nor an enum member in the indexed " + "constants type library." + ) + return EnumLookup(found=False, name=name, note=note) + + def _lookup_method(index: dict[str, Any], interface: str, method: str) -> MemberLookup: """Look up a method or property's signature on an interface. @@ -1428,6 +1540,57 @@ async def lookup_api_interface( "execution_time": time.time() - start_time, } + @mcp.tool() + async def get_api_enum( + input_data: GetApiEnumInput | None = None, + ) -> dict[str, Any]: + """Look up a SolidWorks API enum's members and their integer values. + + Use this when a call takes an enum value, such as a unit system or a + user preference, instead of guessing the number: the values aren't in + the API help pages. Give the enum (``swUnitSystem_e``) or one of its + members (``swUnitSystem_IPS``); a member's name returns its whole + enum with ``matched_member`` set. Names match regardless of case. The + values come from SolidWorks' constants type library installed on this + machine. + + Setup: none. SolidWorks must be installed, not running; it is never + contacted. Read-only. The first lookup builds the index (about a + second) and later ones reuse it. ``index_status`` is ``ready``, + ``rebuilt`` or ``unavailable``. + + Returns ``result`` with ``enum``, ``description`` and ``members`` + (``name`` and ``value`` in declaration order). ``result.found`` false + means there's no such enum or member, or no index could be built; + ``result.note`` says which. + + Example input: ``{"name": "swUnitSystem_e"}`` + + Args: + input_data (GetApiEnumInput | None): The enum. `name` (an + enum or member name) is required; `year` has a default. + + Returns: + dict[str, Any]: ``result``, ``year``, ``type_library_version``, + ``index_status`` and ``source_index_file``, plus + ``status``/``message``/``execution_time``. + """ + start_time = time.time() + normalized = normalize_input(input_data, GetApiEnumInput) + source = _index_for_lookup(normalized.year, normalized.index_file, config) + result = source.annotate(_lookup_enum(source.index, normalized.name)) + return { + "status": "success", + "message": ( + f"{result.enum}: {len(result.members or [])} members" + if result.found + else "No enum or enum member of that name" + ), + **source.payload(), + "result": result.model_dump(exclude_unset=True), + "execution_time": time.time() - start_time, + } + @mcp.tool() async def find_related_api_members( input_data: FindRelatedApiInput | None = None, @@ -1481,6 +1644,6 @@ async def find_related_api_members( } # discover_solidworks_docs, search_solidworks_api_help, lookup_api_method, - # lookup_api_interface, find_related_api_members - tool_count = 5 + # lookup_api_interface, get_api_enum, find_related_api_members + tool_count = 6 return tool_count diff --git a/src/solidworks_mcp/tools/error_classifier.py b/src/solidworks_mcp/tools/error_classifier.py index cad8febc..b0dee428 100644 --- a/src/solidworks_mcp/tools/error_classifier.py +++ b/src/solidworks_mcp/tools/error_classifier.py @@ -127,6 +127,22 @@ def matches(self, message: str, hresult: int | None) -> bool: r"not available", ), ), + ErrorRule( + error_type="vba_source_off", + hint=( + "Ask the user whether to start the server with " + "SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1; don't set it yourself." + ), + patterns=(r"running vba source is turned off",), + ), + ErrorRule( + error_type="macro_waited_for_user", + hint=( + "The macro opened a dialog and waited for an answer. Remove the " + "MsgBox, form or prompt from the macro, then run it again." + ), + patterns=(r"the macro waited for the user",), + ), ErrorRule( error_type="wrong_document_type", hint=( diff --git a/src/solidworks_mcp/tools/file_management.py b/src/solidworks_mcp/tools/file_management.py index c3957abb..669ddaf2 100644 --- a/src/solidworks_mcp/tools/file_management.py +++ b/src/solidworks_mcp/tools/file_management.py @@ -1420,8 +1420,9 @@ async def save_body_as_part( Use it to split a multibody part into parts, e.g. after `create_extrusion` without merging. Needs: an open, active part with the named body and an existing target folder. Changes: adds a Save Bodies feature to the part and writes the - new .sldprt. Returns: `data` with `body`, `file_path`, `feature` and - `solid_bodies` (every body name, to correct a wrong one). + new .sldprt; closes any new, unsaved assembly SolidWorks opens alongside. + Returns: `data` with `body`, `file_path`, `feature`, `solid_bodies` (every + body name, to correct a wrong one) and `closed_documents`. Args: input_data: The body. `body_name` and `file_path` (a .sldprt) are diff --git a/src/solidworks_mcp/tools/macro_recording.py b/src/solidworks_mcp/tools/macro_recording.py index 89b72fec..3c3a5d20 100644 --- a/src/solidworks_mcp/tools/macro_recording.py +++ b/src/solidworks_mcp/tools/macro_recording.py @@ -1,9 +1,12 @@ """Macro Recording and Playback tools for SolidWorks MCP Server. -Provides ``execute_macro``, which runs a binary SolidWorks macro (``.swp``). +Provides ``execute_macro``, which runs a SolidWorks macro file (``.swp`` or +``.swb``), or VBA source text when the server allows it. """ import asyncio +import tempfile +import uuid from pathlib import Path from typing import Any @@ -34,18 +37,30 @@ class MacroPlaybackInput(CompatInput): proc_name (str): The procedure to call. pause_between_runs (float): The pause between runs value. repeat_count (int): The repeat count value. + dialog_timeout (float): Seconds a dialog the macro opens may wait + before it is answered and the run fails. + vba_source (str | None): The macro's VBA text, instead of a file. """ macro_path: str | None = Field( default=None, description=( - "Path to a binary SolidWorks macro (.swp, or legacy .swb). " - "VBA source (.vb, .bas, text) cannot be run directly." + "Path to a SolidWorks macro file (.swp, or legacy .swb). For VBA " + "source text, use vba_source." ), ) macro_file: str | None = Field( default=None, description="Alternative to macro_path (.swp or .swb)" ) + vba_source: str | None = Field( + default=None, + min_length=1, + max_length=200_000, + description=( + "The macro's VBA text, instead of a file: written to a .swb and " + "run. Only when the server allows it (SOLIDWORKS_MCP_ALLOW_VBA_SOURCE)" + ), + ) proc_name: str = Field( default="main", description="The macro procedure to call; main by default" ) @@ -58,6 +73,16 @@ class MacroPlaybackInput(CompatInput): pause_between_runs: float = Field( default=0.0, ge=0.0, description="Seconds to wait between runs" ) + dialog_timeout: float = Field( + default=30.0, + ge=1.0, + le=600.0, + description=( + "Seconds a dialog the macro opens (MsgBox, form, prompt) may wait " + "before it is answered with Cancel (or its only button) and the " + "run fails as macro_waited_for_user" + ), + ) def model_post_init(self, __context: Any) -> None: """Reject macro files ``ISldWorks::RunMacro2`` cannot run. @@ -69,18 +94,63 @@ def model_post_init(self, __context: Any) -> None: __context (Any): The context value. Raises: - ValueError: A macro path is not a ``.swp`` or ``.swb`` file. + ValueError: A macro path is not a ``.swp`` or ``.swb`` file, VBA + source is given with a file, or the source has characters a + Windows-1252 text file can't hold. """ + if self.vba_source is not None: + if self.macro_path or self.macro_file: + raise ValueError( + "Give vba_source or a macro file (macro_path), not both." + ) + try: + self.vba_source.encode("cp1252") + except UnicodeEncodeError as exc: + raise ValueError( + "vba_source has a character VBA files can't hold " + f"({exc.object[exc.start : exc.end]!r}); use plain text." + ) from exc for path in (self.macro_path, self.macro_file): if path and Path(path).suffix.lower() not in _RUNNABLE_MACRO_SUFFIXES: raise ValueError( - f"execute_macro runs only binary SolidWorks macros " - f"(.swp or .swb), got {path!r}. VBA source (.vb, .bas or " - "text) must be saved as a .swp in the SolidWorks VBA " - "editor first." + f"execute_macro runs only SolidWorks macro files " + f"(.swp or .swb), got {path!r}. Pass VBA source as " + "vba_source instead (when the server allows it), or save " + "it as a .swp in the SolidWorks VBA editor." ) +#: Why VBA source wasn't run, and how to allow it. +VBA_SOURCE_OFF = ( + "Running VBA source is turned off on this server, so nothing was written " + "or run. VBA can do anything you can on this computer; to allow it, start " + "the server with SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1. Or save the macro as " + "a .swp in SolidWorks and pass macro_path." +) + + +def _write_source(source: str, config: Any) -> Path: + """Write VBA source to a new ``.swb`` file, when the server allows it. + + Args: + source: The macro's VBA text. + config: The server configuration (``allow_vba_source``). + + Returns: + Path: The written file, under ``/solidworks_mcp/macros``. + + Raises: + ToolOperationError: Running VBA source isn't allowed. + """ + if not getattr(config, "allow_vba_source", False): + raise ToolOperationError(VBA_SOURCE_OFF) + folder = Path(tempfile.gettempdir()) / "solidworks_mcp" / "macros" + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"vba-{uuid.uuid4().hex[:12]}.swb" + path.write_text(source, encoding="cp1252") + return path + + async def register_macro_recording_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: Any ) -> int: @@ -102,21 +172,28 @@ async def register_macro_recording_tools( @mcp.tool() async def execute_macro(input_data: MacroPlaybackInput) -> dict[str, Any]: - """Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, calling its `main` procedure once. - - Use it to run an existing macro file. VBA source (.bas, .vb, plain text, or what - the `generate_vba_*` tools return) is refused as invalid input before SolidWorks - sees it. The macro must not wait for the user (no MsgBox or forms), or the call - hangs. It runs `repeat_count` times, `pause_between_runs` seconds apart, and - stops at the first run that fails. Needs: SolidWorks running and the macro file - on disk. Changes: whatever the macro does; it can't be undone from here. - Returns: `runs_completed` and `data` from the last run, with `macro_path`, - `module_name`, `proc_name` and `errors`. + """Run a SolidWorks macro (.swp, or legacy .swb), or VBA source text, in the running SolidWorks, calling its `main` procedure. + + Use it to run an existing macro file, or VBA you wrote (for example from a + `generate_vba_*` tool) as `vba_source`. VBA source runs only when the user + started the server with SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1; otherwise it is + refused as `vba_source_off`, so ask the user, never set it yourself. The + source is written to a .swb file, and the reply gives `source_file` and the + `vba_source` that ran. The macro must not wait for the user (no MsgBox or + forms): a dialog still open after `dialog_timeout` seconds (30) is answered + with Cancel, or its only button, and the run fails as + `macro_waited_for_user`; a Yes/No prompt is left for the user. It runs + `repeat_count` times, `pause_between_runs` seconds apart, and stops at the + first run that fails. Needs: SolidWorks running and the macro file on disk + (or the setting for source). Changes: whatever the macro does; it can't be + undone from here. Returns: `runs_completed` and `data` from the last run, + with `macro_path`, `module_name`, `proc_name` and `errors`. Args: - input_data: The macro to run. Give `macro_path` (or `macro_file`); - `proc_name` (main), `repeat_count` (1) and `pause_between_runs` (0 s) - have defaults. + input_data: The macro to run. Give `macro_path` (or `macro_file`), or + `vba_source`; `proc_name` (main), `repeat_count` (1), + `pause_between_runs` (0 s) and `dialog_timeout` (30 s) have + defaults. Returns: dict[str, Any]: The run's result. @@ -130,13 +207,16 @@ async def execute_macro(input_data: MacroPlaybackInput) -> dict[str, Any]: "were created.", ) payload = input_data.model_dump() + if input_data.vba_source is not None: + payload["macro_path"] = str(_write_source(input_data.vba_source, config)) total = input_data.repeat_count execution_time = 0.0 result = None for run in range(total): if run and input_data.pause_between_runs: await asyncio.sleep(input_data.pause_between_runs) - result = await adapter.execute_macro(payload) + # require_capability above checked the adapter has it. + result = await adapter.execute_macro(payload) # type: ignore[attr-defined] if not result.is_success: raise ToolOperationError( f"Run {run + 1} of {total} failed after {run} completed: " @@ -146,13 +226,17 @@ async def execute_macro(input_data: MacroPlaybackInput) -> dict[str, Any]: ) execution_time += result.execution_time or 0.0 runs = "1 run" if total == 1 else f"{total} runs" - return { + reply: dict[str, Any] = { "status": "success", "message": f"Macro completed {runs}", "runs_completed": total, "data": result.data if result is not None else None, "execution_time": execution_time, } + if input_data.vba_source is not None: + reply["source_file"] = payload["macro_path"] + reply["vba_source"] = input_data.vba_source + return reply tool_count = 1 # execute_macro return tool_count diff --git a/src/solidworks_mcp/tools/modeling.py b/src/solidworks_mcp/tools/modeling.py index c098ce14..43f44487 100644 --- a/src/solidworks_mcp/tools/modeling.py +++ b/src/solidworks_mcp/tools/modeling.py @@ -1872,7 +1872,8 @@ async def get_dimension(input_data: GetDimensionInput) -> dict[str, Any]: dict[str, Any]: The dimension's value. """ input_data = normalize_input(input_data, GetDimensionInput) - result = await adapter.get_dimension(input_data.name) + # The input's validator fills `name` (from `dimension_name` if need be). + result = await adapter.get_dimension(cast(str, input_data.name)) require_success(result, context="Failed to get dimension") reading = result.data or {} @@ -1911,7 +1912,7 @@ async def set_dimension(input_data: SetDimensionInput) -> dict[str, Any]: """ input_data = normalize_input(input_data, SetDimensionInput) result = await adapter.set_dimension( - input_data.name, input_data.value, input_data.configurations + cast(str, input_data.name), input_data.value, input_data.configurations ) require_success(result, context="Failed to set dimension") diff --git a/src/solidworks_mcp/tools/requirements.py b/src/solidworks_mcp/tools/requirements.py index de601c4b..ac6fc0c6 100644 --- a/src/solidworks_mcp/tools/requirements.py +++ b/src/solidworks_mcp/tools/requirements.py @@ -54,6 +54,7 @@ class Requirement(StrEnum): "search_solidworks_api_help": Requirement.INSTALLED, "lookup_api_method": Requirement.INSTALLED, "lookup_api_interface": Requirement.INSTALLED, + "get_api_enum": Requirement.INSTALLED, "find_related_api_members": Requirement.INSTALLED, "list_hole_sizes": Requirement.INSTALLED, } diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index dee4edcb..b88f53f9 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -194,6 +194,7 @@ def _deprecated(replacement: str | None) -> Support: "discover_solidworks_docs": _STABLE, "find_related_api_members": _STABLE, "lookup_api_interface": _STABLE, + "get_api_enum": _STABLE, "lookup_api_method": _STABLE, "search_solidworks_api_help": _STABLE, # drawing diff --git a/src/solidworks_mcp/tools/tool_hints.py b/src/solidworks_mcp/tools/tool_hints.py index ea84716d..d4467302 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -110,6 +110,7 @@ def _discards(title: str) -> ToolHints: "reset_circuit_breaker": _sets("Reset Circuit Breaker"), "lookup_api_method": _reads("Look Up API Method"), "lookup_api_interface": _reads("Look Up API Interface"), + "get_api_enum": _reads("Get API Enum"), "find_related_api_members": _reads("Find Related API Members"), # drawing "create_drawing_view": _adds("Create Drawing View"), diff --git a/src/solidworks_mcp/tools/type_library.py b/src/solidworks_mcp/tools/type_library.py index 88e49f1c..9134a2de 100644 --- a/src/solidworks_mcp/tools/type_library.py +++ b/src/solidworks_mcp/tools/type_library.py @@ -23,21 +23,25 @@ try: import pythoncom -except ImportError: +except ImportError: # pywin32 is Windows-only pythoncom = None try: import winreg -except ImportError: - winreg = None +except ImportError: # winreg is Windows-only + winreg = None # type: ignore[assignment] SOLIDWORKS_TYPELIB_GUID = "{83A33D31-27C5-11CE-BFD4-00400513BB57}" +#: The constants library (swconst.tlb): every enum, registered at the same +#: version as the main one. +CONSTANTS_TYPELIB_GUID = "{4687F359-55D0-4CD3-B6CF-2EB42C11F989}" # Type library major version 34 is SolidWorks 2026. _YEAR_OFFSET = 1992 # SolidWorks' first release. A lower version key (installs can leave a # "1.0", which would read as 1993) isn't a SolidWorks release. _FIRST_RELEASE_YEAR = 1995 +_TKIND_ENUM = 0 _TKIND_DISPATCH = 4 _INVOKE_FUNC = 1 _INVOKE_PROPERTYGET = 2 @@ -97,7 +101,10 @@ class TypeInfoLike(Protocol): """The part of ``ITypeInfo`` the reader uses.""" def GetTypeAttr(self) -> Any: - """The interface's TYPEATTR; the reader uses ``cFuncs``.""" + """The type's TYPEATTR; the reader uses ``cFuncs`` and ``cVars``.""" + + def GetVarDesc(self, index: int, /) -> Any: + """The VARDESC of the variable at ``index``; an enum member's ``value``.""" def GetFuncDesc(self, index: int, /) -> Any: """The FUNCDESC of the function at ``index``.""" @@ -235,6 +242,32 @@ class ApiInterface(BaseModel): ) +class ApiEnumMember(BaseModel): + """One member of a SolidWorks enum. + + Attributes: + name (str): The member's name, e.g. ``swUnitSystem_IPS``. + value (int): Its integer value. + """ + + name: str = Field(description="Member name, e.g. swUnitSystem_IPS") + value: int = Field(description="Its integer value") + + +class ApiEnum(BaseModel): + """One SolidWorks enum in the index. + + Attributes: + description (str | None): The type library's help string, if any. + members (list[ApiEnumMember]): Its members in declaration order. + """ + + description: str | None = Field(default=None, description="Help string") + members: list[ApiEnumMember] = Field( + description="Members in declaration order, with their values" + ) + + def year_of(major: int) -> int: """The SolidWorks year a type library major version belongs to. @@ -423,6 +456,30 @@ def index_type_library(lib: TypeLibLike) -> dict[str, ApiInterface]: return com_objects +def index_enums(lib: TypeLibLike) -> dict[str, ApiEnum]: + """Index every enum in a type library, with its members' values. + + Args: + lib (TypeLibLike): An ITypeLib (or a fake with the same methods). + + Returns: + dict[str, ApiEnum]: Enum name -> its record. + """ + enums = {} + for position in range(lib.GetTypeInfoCount()): + if lib.GetTypeInfoType(position) != _TKIND_ENUM: + continue + name, description = lib.GetDocumentation(position)[:2] + typeinfo = lib.GetTypeInfo(position) + members = [] + for index in range(typeinfo.GetTypeAttr().cVars): + vardesc = typeinfo.GetVarDesc(index) + member = typeinfo.GetDocumentation(vardesc.memid)[0] + members.append(ApiEnumMember(name=member, value=int(vardesc.value))) + enums[name] = ApiEnum(description=description or None, members=members) + return enums + + def registered_versions(registry: Any) -> list[tuple[int, int]]: """Every registered SolidWorks type library version. @@ -558,3 +615,32 @@ def load_type_library( path=str(com.QueryPathOfRegTypeLib(SOLIDWORKS_TYPELIB_GUID, major, minor)), ) return lib, info + + +def load_constants_library(major: int, minor: int, com: Any = None) -> Any: + """Load SolidWorks' constants type library (swconst.tlb) at a version. + + It is registered beside the main library, at the same version. + + Args: + major (int): The main library's major version. + minor (int): Its minor version. + com (Any): The ``pythoncom`` module; defaults to the real one. + + Returns: + Any: The ITypeLib. + + Raises: + TypeLibraryUnavailable: Not on Windows with pywin32, or the + constants library isn't registered at that version or won't load. + """ + com = com if com is not None else pythoncom + if com is None: + raise TypeLibraryUnavailable(_NEEDS_WINDOWS) + try: + return com.LoadRegTypeLib(CONSTANTS_TYPELIB_GUID, major, minor) + except com.com_error as exc: + raise TypeLibraryUnavailable( + f"SolidWorks {year_of(major)}'s constants type library (swconst.tlb) " + f"couldn't be loaded ({exc}), so the index has no enum values." + ) from exc diff --git a/src/solidworks_mcp/ui/service.py b/src/solidworks_mcp/ui/service.py index ff9bd20f..252e5908 100644 --- a/src/solidworks_mcp/ui/service.py +++ b/src/solidworks_mcp/ui/service.py @@ -81,7 +81,7 @@ # Keep this symbol available for tests that monkeypatch PDF ingestion behavior. try: - from pypdf import PdfReader # type: ignore + from pypdf import PdfReader # type: ignore[import-not-found] # optional except Exception: PdfReader = None diff --git a/src/solidworks_mcp/utils/feature_tree_classifier.py b/src/solidworks_mcp/utils/feature_tree_classifier.py index ecf790f2..dbdb4c0f 100644 --- a/src/solidworks_mcp/utils/feature_tree_classifier.py +++ b/src/solidworks_mcp/utils/feature_tree_classifier.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from typing import Any _SHEET_METAL_TOKENS = ( @@ -314,7 +314,9 @@ def classify_feature_tree_snapshot( } -def build_component_tree(features: list[Mapping[str, Any]] | None) -> dict[str, Any]: +def build_component_tree( + features: Sequence[Mapping[str, Any]] | None, +) -> dict[str, Any]: """Reconstruct a nested component/sub-component tree from a flat ``list_features`` result. diff --git a/src/utils/generate_tool_catalog.py b/src/utils/generate_tool_catalog.py deleted file mode 100644 index 427507d3..00000000 --- a/src/utils/generate_tool_catalog.py +++ /dev/null @@ -1,856 +0,0 @@ -"""Generate a structured tool catalog from all registered MCP tool source files. - -Parses every @mcp.tool() decorated function across the tools/ package, extracts Pydantic -input schemas, docstrings, and example payloads, then writes per-category Markdown docs -pages and a machine-readable JSON index. - -Usage: python src/utils/generate_tool_catalog.py python -src/utils/generate_tool_catalog.py --output-dir docs/user-guide/tool-catalog python -src/utils/generate_tool_catalog.py --json-only -""" - -from __future__ import annotations - -import ast -import json -import sys -import textwrap -from pathlib import Path -from typing import Any - -# --------------------------------------------------------------------------- -# Tool registry — built from AST, not runtime import, so no SolidWorks needed -# --------------------------------------------------------------------------- - -CATEGORY_META: dict[str, dict[str, str]] = { - "modeling": { - "title": "Modeling Tools", - "icon": ":material-cube-outline:", - "description": ( - "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." - ), - "prerequisite": "An active SolidWorks session. Most feature tools require an open Part document.", - }, - "sketching": { - "title": "Sketching Tools", - "icon": ":material-pencil:", - "description": ( - "Build 2-D sketch geometry (lines, circles, arcs, splines, polygons) and " - "apply geometric constraints and driven dimensions. Sketches are the " - "prerequisite for every extrusion, revolve, sweep, and loft feature." - ), - "prerequisite": "An active part document with an active sketch edit session.", - }, - "drawing": { - "title": "Drawing Tools", - "icon": ":material-technical-draw:", - "description": ( - "Create and edit 2-D technical drawings: add projected/section/detail views, " - "place dimensions, notes, and annotations, update title blocks and sheet " - "formats, and run drafting standards checks." - ), - "prerequisite": "An active SolidWorks Drawing (.slddrw) document.", - }, - "drawing_analysis": { - "title": "Drawing Analysis Tools", - "icon": ":material-magnify:", - "description": ( - "Quality-gate your drawings. Analyse dimensions, annotations, view coverage, " - "and GD&T compliance. Generate formal drawing reports and compare drawing " - "revisions. Suitable for automated QA pipelines." - ), - "prerequisite": "An active Drawing document open in SolidWorks.", - }, - "drawing_automation": { - "title": "Drawing Automation Tools", - "icon": ":material-ruler:", - "description": ( - "Put the model's dimensions on a drawing and lay them out so nothing " - "overlaps, add a bill of materials, set the sheet scale, or make a " - "complete A3 drawing of a part or assembly in one call." - ), - "prerequisite": ( - "An active Drawing document with views of a model; " - "generate_drawing_package only needs a saved part or assembly." - ), - }, - "engineering_data": { - "title": "Engineering Data Tools", - "icon": ":material-ruler-square:", - "description": ( - "Read and edit the data drawings, BOMs and analyses are built from: " - "every model dimension by name, measurements between faces, edges " - "and vertices, materials, custom properties, and sheet-metal flat " - "patterns." - ), - "prerequisite": "An active Part (or Assembly, for dimensions and measuring) document.", - }, - "analysis": { - "title": "Analysis Tools", - "icon": ":material-chart-line:", - "description": ( - "Extract engineering properties from models: mass, volume, centre of mass, " - "moments of inertia, interference between solids, geometry curvature and " - "thickness, and material properties. Essential for design validation." - ), - "prerequisite": "An active model (part or assembly) with solid geometry.", - }, - "export": { - "title": "Export Tools", - "icon": ":material-export:", - "description": ( - "Convert SolidWorks models to industry-standard interchange and " - "manufacturing formats: STEP, IGES, STL, PDF, DWG, and raster images. " - "Includes a batch-export tool for processing whole directories." - ), - "prerequisite": "An active document or a valid file path to an existing model.", - }, - "file_management": { - "title": "File Management Tools", - "icon": ":material-folder-open:", - "description": ( - "Open, save, and manage SolidWorks documents. Load parts and assemblies, " - "save-as with new names or paths, manage custom file properties, and " - "convert between file formats." - ), - "prerequisite": "SolidWorks running. File-write operations need writable output paths.", - }, - "automation": { - "title": "Automation Tools", - "icon": ":material-cog:", - "description": ( - "Orchestrate multi-step workflows, run batch file processing, manage design " - "tables, generate VBA code on the fly, and tune SolidWorks performance " - "settings. The glue that connects individual tool calls into repeatable pipelines." - ), - "prerequisite": "Varies by operation. Batch processing requires writable source/output directories.", - }, - "vba_generation": { - "title": "VBA Generation Tools", - "icon": ":material-code-braces:", - "description": ( - "Generate and execute VBA macro code for operations that exceed the COM " - "direct-call parameter limit (typically > 12 params). Covers extrusions, " - "revolves, assembly inserts, mates, drawing views, batch exports, file " - "operations, and macro recording scaffolding." - ), - "prerequisite": "SolidWorks running. Generated VBA macros are executed via the COM runtime.", - }, - "template_management": { - "title": "Template Management Tools", - "icon": ":material-file-document:", - "description": ( - "Create, extract, apply, compare, and library-manage SolidWorks document " - "templates (.prtdot, .asmdot, .drwdot) and sheet formats. Enables " - "standardized document creation across teams and projects." - ), - "prerequisite": "Valid template file paths. Library operations require a configured template library path.", - }, - "macro_recording": { - "title": "Macro Recording Tools", - "icon": ":material-record:", - "description": ( - "Record, replay, analyse, and optimize SolidWorks VBA macros. Create macro " - "libraries for reuse, batch-execute recorded macros, and profile performance " - "hot-spots. Ideal for capturing manual workflows and converting them to " - "automated, repeatable sequences." - ), - "prerequisite": "SolidWorks running. Macro execution requires a valid .swp file path.", - }, - "docs_discovery": { - "title": "Docs Discovery Tools", - "icon": ":material-book-search:", - "description": ( - "Look up SolidWorks API interfaces, methods and properties, with each " - "member's parameters, return type and description, read from the " - "installed SolidWorks type library. The lookup tools build the JSON index " - "themselves the first time they run, and reuse it after that." - ), - "prerequisite": ( - "SolidWorks installed (it need not be running), Windows with pywin32. " - "The server's --year picks which installed release answers." - ), - }, -} - - -# --------------------------------------------------------------------------- -# AST helpers -# --------------------------------------------------------------------------- - - -def _first_paragraph(docstring: str) -> str: - """Return the first paragraph of a docstring, stripped of indentation. - - Args: - docstring (str): The docstring value. - - Returns: - str: The resulting text value. - """ - if not docstring: - return "" - lines = textwrap.dedent(docstring).strip().splitlines() - para: list[str] = [] - for line in lines: - if line.strip() == "" and para: - break - para.append(line.strip()) - return " ".join(para) - - -def _parse_pydantic_model(tree: ast.Module, class_name: str) -> list[dict[str, Any]]: - """Extract field definitions from a Pydantic BaseModel class node. - - Args: - tree (ast.Module): The tree value. - class_name (str): The class name value. - - Returns: - list[dict[str, Any]]: A list containing the resulting items. - """ - fields: list[dict[str, Any]] = [] - for node in ast.walk(tree): - if not isinstance(node, ast.ClassDef) or node.name != class_name: - continue - # Fields of a base class defined in the same module come first, as - # pydantic orders them (e.g. the lookups' shared ApiIndexInput). - for base in node.bases: - if isinstance(base, ast.Name): - fields.extend(_parse_pydantic_model(tree, base.id)) - for stmt in node.body: - if not isinstance(stmt, ast.AnnAssign): - continue - field_name = getattr(stmt.target, "id", None) - if field_name is None or field_name.startswith("_"): - continue - # Type annotation as source text - type_str = ast.unparse(stmt.annotation) - # Default / Field description - description = "" - default_val: Any = "required" - if isinstance(stmt.value, ast.Call): - func = stmt.value.func - if (isinstance(func, ast.Attribute) and func.attr == "Field") or ( - isinstance(func, ast.Name) and func.id == "Field" - ): - for kw in stmt.value.keywords: - if kw.arg == "description": - description = ( - ast.literal_eval(kw.value) - if isinstance(kw.value, ast.Constant) - else ast.unparse(kw.value) - ) - elif kw.arg == "default": - try: - default_val = ast.literal_eval(kw.value) - except Exception: - default_val = ast.unparse(kw.value) - # If first positional arg is a default value - if stmt.value.args: - try: - default_val = ast.literal_eval(stmt.value.args[0]) - except Exception: - default_val = ast.unparse(stmt.value.args[0]) - elif stmt.value is not None: - try: - default_val = ast.literal_eval(stmt.value) - except Exception: - default_val = ast.unparse(stmt.value) - - fields.append( - { - "name": field_name, - "type": _simplify_type(type_str), - "description": description, - "default": default_val, - "required": default_val == "required", - } - ) - return fields - - -def _simplify_type(t: str) -> str: - """Build internal simplify type. - - Args: - t (str): The t value. - - Returns: - str: The resulting text value. - """ - - return ( - t.replace("list[", "List[") - .replace("dict[", "Dict[") - .replace(" | None", "?") - .replace("| None", "?") - ) - - -def _find_tool_input_class(tree: ast.Module, func_name: str) -> str | None: - """Return the Pydantic model class name used as the first parameter of a tool function. - - Args: - tree (ast.Module): The tree value. - func_name (str): The func name value. - - Returns: - str | None: The result produced by the operation. - """ - for node in ast.walk(tree): - if ( - isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == func_name - ): - args = node.args.args - if len(args) >= 1: - annotation = args[0].annotation - # ``Model | None`` (an optional input) names the model first. - if isinstance(annotation, ast.BinOp): - annotation = annotation.left - if isinstance(annotation, ast.Name): - return annotation.id - return None - - -def _get_tool_docstring(tree: ast.Module, func_name: str) -> str: - """Extract docstring from an inner function (possibly nested in register_* fn). - - Args: - tree (ast.Module): The tree value. - func_name (str): The func name value. - - Returns: - str: The resulting text value. - """ - for node in ast.walk(tree): - if ( - isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == func_name - ): - if ( - node.body - and isinstance(node.body[0], ast.Expr) - and isinstance(node.body[0].value, ast.Constant) - ): - return node.body[0].value.value - return "" - - -def _is_tool_func(node: ast.AST) -> bool: - """Build internal is tool func. - - Args: - node (ast.AST): The node value. - - Returns: - bool: True if tool func, otherwise False. - """ - - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - return False - for dec in node.decorator_list: - if isinstance(dec, ast.Attribute) and dec.attr == "tool": - return True - if isinstance(dec, ast.Name) and dec.id == "tool": - return True - if isinstance(dec, ast.Call): - func = dec.func - if (isinstance(func, ast.Attribute) and func.attr == "tool") or ( - isinstance(func, ast.Name) and func.id == "tool" - ): - return True - return False - - -def _extract_tool_name_from_decorator( - node: ast.FunctionDef | ast.AsyncFunctionDef, -) -> str: - """Return explicit name= from @mcp.tool(name=...) or fall back to function name. - - Args: - node (ast.FunctionDef | ast.AsyncFunctionDef): The node value. - - Returns: - str: The resulting text value. - """ - for dec in node.decorator_list: - if isinstance(dec, ast.Call): - for kw in dec.keywords: - if kw.arg == "name": - try: - return ast.literal_eval(kw.value) - except Exception: - pass - return node.name - - -# --------------------------------------------------------------------------- -# Catalog builder -# --------------------------------------------------------------------------- - - -def _make_sample_payload(fields: list[dict[str, Any]]) -> dict[str, Any]: - """Generate a plausible sample call payload from Pydantic field definitions. - - Args: - fields (list[dict[str, Any]]): The fields value. - - Returns: - dict[str, Any]: A dictionary containing the resulting values. - """ - sample: dict[str, Any] = {} - synthetic: dict[str, Any] = { - "file_path": "C:\\Temp\\mcp_demo\\part.sldprt", - "output_path": "C:\\Temp\\mcp_demo\\export.step", - "name": "MCP_Demo_Part", - "plane": "Front", - "sketch_name": "Sketch1", - "depth": 25.0, - "angle": 360.0, - "axis_entity": "Line1", - "x1": -30.0, - "y1": -20.0, - "x2": 30.0, - "y2": 20.0, - "center_x": 0.0, - "center_y": 0.0, - "radius": 15.0, - "source_directory": "C:\\Temp\\mcp_demo", - "output_directory": "C:\\Temp\\mcp_demo\\exports", - "format_type": "step", - "analysis_type": "curvature", - "dimension_name": "D1@Sketch1", - "value": 50.0, - "dimension": "D1@Sketch1", - "units": "mm", - "components": [], - "profiles": ["Sketch1", "Sketch2"], - "points": [ - {"x": 0.0, "y": 0.0}, - {"x": 10.0, "y": 15.0}, - {"x": 20.0, "y": 10.0}, - ], - "entity1": "Line1", - "relation_type": "perpendicular", - "dimension_type": "linear", - "start_x": -30.0, - "start_y": 0.0, - "end_x": 30.0, - "end_y": 0.0, - "diameter": 10.0, - "query": "", - "output_dir": "C:\\Temp\\mcp_demo\\docs-index", - "template": None, - "model_path": None, - } - for f in fields: - if f["required"]: - name = f["name"] - if name in synthetic: - sample[name] = synthetic[name] - elif "path" in name: - sample[name] = "C:\\Temp\\mcp_demo\\file.sldprt" - elif "name" in name: - sample[name] = "MCP_Demo_Part" - elif f["type"].startswith("float") or f["type"].startswith("int"): - sample[name] = 10.0 - elif f["type"].startswith("bool"): - sample[name] = False - elif f["type"].startswith("str"): - sample[name] = "example" - elif f["type"].startswith("List"): - sample[name] = [] - elif f["type"].startswith("Dict"): - sample[name] = {} - else: - sample[name] = None - return sample - - -PREREQUISITES: dict[str, str] = { - "open_model": "SolidWorks running", - "create_part": "SolidWorks running", - "create_assembly": "SolidWorks running", - "create_drawing": "SolidWorks running", - "close_model": "An active open document", - "create_extrusion": "Active part with an active sketch (exit sketch first with exit_sketch)", - "create_revolve": "Active part with an active sketch containing the profile and axis", - "get_dimension": "Active document with named dimensions", - "set_dimension": "Active document with named dimensions", - "create_sketch": "Active part document, no active sketch", - "exit_sketch": "Active sketch edit mode", - "add_line": "Active sketch edit mode", - "add_circle": "Active sketch edit mode", - "add_rectangle": "Active sketch edit mode", - "add_arc": "Active sketch edit mode", - "add_spline": "Active sketch edit mode", - "add_centerline": "Active sketch edit mode", - "add_polygon": "Active sketch edit mode", - "add_ellipse": "Active sketch edit mode", - "add_sketch_constraint": "Active sketch edit mode with named entities", - "add_sketch_dimension": "Active sketch edit mode", - "sketch_linear_pattern": "Active sketch edit mode", - "sketch_circular_pattern": "Active sketch edit mode", - "sketch_mirror": "Active sketch edit mode", - "sketch_offset": "Active sketch edit mode", - "calculate_mass_properties": "Active model with solid geometry", - "get_mass_properties": "Active model with solid geometry", - "check_interference": "Active assembly", - "export_step": "Active or specified model document", - "export_iges": "Active or specified model document", - "export_stl": "Active or specified model document", - "export_pdf": "Active or specified drawing document", - "export_dwg": "Active or specified drawing document", - "export_image": "Active document", - "save_file": "Active open document", - "save_as": "Active open document, writable output path", - "get_file_properties": "Active document", - "load_part": "SolidWorks running, valid .sldprt path", - "load_assembly": "SolidWorks running, valid .sldasm path", - "save_part": "Active Part document", - "save_assembly": "Active Assembly document", - "discover_solidworks_docs": "SolidWorks installed (it need not be running), Windows only", -} - - -def build_catalog(tools_dir: Path) -> list[dict[str, Any]]: - """Parse all tool source files and return a structured catalog. - - Args: - tools_dir (Path): The tools dir value. - - Returns: - list[dict[str, Any]]: A list containing the resulting items. - """ - catalog: list[dict[str, Any]] = [] - - for py_file in sorted(tools_dir.glob("*.py")): - if py_file.name in ("__init__.py", "input_compat.py"): - continue - - category = py_file.stem - try: - with open(py_file, encoding="utf-8") as fh: - source = fh.read() - tree = ast.parse(source) - except Exception as exc: - print(f" [WARN] Could not parse {py_file.name}: {exc}") - continue - - # Walk the entire tree to find @mcp.tool() decorated functions - # (they live inside register_*_tools nested scope) - for node in ast.walk(tree): - if not _is_tool_func(node): - continue - - tool_name = _extract_tool_name_from_decorator(node) - func_name = node.name - docstring = _get_tool_docstring(tree, func_name) - description = _first_paragraph(docstring) - input_class = _find_tool_input_class(tree, func_name) - fields: list[dict[str, Any]] = [] - if input_class: - fields = _parse_pydantic_model(tree, input_class) - sample = _make_sample_payload(fields) - - catalog.append( - { - "tool_name": tool_name, - "func_name": func_name, - "category": category, - "input_class": input_class, - "description": description, - "fields": fields, - "sample_payload": sample, - "prerequisite": PREREQUISITES.get( - func_name, PREREQUISITES.get(tool_name, "SolidWorks running") - ), - } - ) - - return catalog - - -# --------------------------------------------------------------------------- -# Markdown generators -# --------------------------------------------------------------------------- - -_PARAM_TABLE_HEADER = "| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|" - - -def _render_param_row(f: dict[str, Any]) -> str: - """Build internal param row. - - Args: - f (dict[str, Any]): The f value. - - Returns: - str: The resulting text value. - """ - - req = "✅" if f["required"] else "—" - default = "" if f["required"] else str(f["default"]) - return ( - f"| `{f['name']}` | `{f['type']}` | {req} | `{default}` | {f['description']} |" - ) - - -def _render_tool_section(tool: dict[str, Any]) -> str: - """Build internal tool section. - - Args: - tool (dict[str, Any]): The tool value. - - Returns: - str: The resulting text value. - """ - - lines: list[str] = [] - lines.append(f"### `{tool['tool_name']}`\n") - if tool["description"]: - lines.append(tool["description"]) - lines.append("") - lines.append(f"**Prerequisite:** {tool['prerequisite']}\n") - - if tool["fields"]: - lines.append("**Parameters:**\n") - lines.append(_PARAM_TABLE_HEADER) - for f in tool["fields"]: - lines.append(_render_param_row(f)) - lines.append("") - - # Sample call - if tool["sample_payload"] is not None: - sample_json = json.dumps(tool["sample_payload"], indent=2) - lines.append("**Sample call:**\n") - lines.append("```json") - lines.append(sample_json) - lines.append("```\n") - else: - lines.append("**Sample call:** *(no required parameters — call with `{}`)*\n") - - return "\n".join(lines) - - -def generate_category_page( - category: str, - tools: list[dict[str, Any]], - meta: dict[str, str], -) -> str: - """Generate a full Markdown page for one tool category. - - Args: - category (str): The category value. - tools (list[dict[str, Any]]): The tools value. - meta (dict[str, str]): The meta value. - - Returns: - str: The resulting text value. - """ - lines: list[str] = [] - lines.append(f"# {meta['title']}\n") - lines.append(meta["description"]) - lines.append("") - lines.append(f"> **Prerequisite:** {meta['prerequisite']}\n") - lines.append(f"**Total tools in this category: {len(tools)}**\n") - - lines.append("---\n") - - for tool in tools: - lines.append(_render_tool_section(tool)) - lines.append("---\n") - - return "\n".join(lines) - - -def generate_index_page(catalog: list[dict[str, Any]]) -> str: - """Generate the top-level tool catalog index page. - - Args: - catalog (list[dict[str, Any]]): The catalog value. - - Returns: - str: The resulting text value. - """ - from collections import Counter - - counts = Counter(t["category"] for t in catalog) - total = len(catalog) - - lines: list[str] = [ - "# Tool Catalog — All 101 Tools\n", - f"This reference documents all **{total} MCP tools** registered by the SolidWorks MCP server.", - "Each section covers one functional category with parameter tables and copy-paste sample calls.\n", - "## Quick Navigation\n", - "| Category | Count | Description |", - "|----------|-------|-------------|", - ] - - for cat, meta in CATEGORY_META.items(): - count = counts.get(cat, 0) - slug = cat.replace("_", "-") - lines.append( - f"| [{meta['title']}]({slug}.md) | {count} | {meta['description'][:80]}… |" - ) - - lines += [ - "", - "## Standard Response Envelope", - "", - "A successful call returns at least:", - "", - "```json", - "{", - ' "status": "success",', - ' "message": "Human-readable description",', - ' "data": { ... },', - ' "execution_time": 0.123', - "}", - "```", - "", - "Every tool runs inside one error boundary, so a failed call always has the", - "same shape, whatever went wrong:", - "", - "```json", - "{", - ' "status": "error",', - ' "message": "What failed and why",', - ' "error_type": "no_active_document",', - ' "hint": "Open or create a document first (open_model / create_part), or activate one with activate_document, then retry.",', - ' "execution_time": 0.012', - "}", - "```", - "", - "`data` appears on an error only when the adapter returned diagnostics worth", - "keeping (for example `rebuild_model` lists the failing features). `error_type`", - "says what kind of failure it was; `hint` is the next step to take:", - "", - "| `error_type` | Meaning |", - "|---|---|", - "| `invalid_input` | The arguments failed validation; nothing was sent to SolidWorks |", - "| `not_supported` | The active adapter cannot do this (e.g. the mock adapter, or a missing capability) |", - "| `no_active_document` | The tool needs an open document and there is none |", - "| `no_active_sketch` | The tool needs an open sketch and there is none |", - "| `wrong_document_type` | The active document is the wrong kind (e.g. a part where a drawing is needed) |", - "| `not_found` | A named feature, document, view, file, face or edge does not exist |", - "| `solidworks_unavailable` | SolidWorks was closed or crashed (RPC disconnect) |", - "| `circuit_open` | Calls are paused after repeated failures; retry after the breaker timeout |", - "| `com_wrong_thread` | A SolidWorks call ran off the thread that connected (a server bug; restart the server) |", - "| `com_member_not_found` | SolidWorks could not resolve an API member (usually a stale `gen_py` cache) |", - "| `com_type_mismatch` | SolidWorks rejected an argument's COM type (a server bug; report it) |", - "| `operation_failed` | SolidWorks refused or failed the operation; read `message` |", - "| `internal` | An unexpected server error (a bug; report the tool and arguments) |", - "", - "## Calling Tools from an LLM\n", - "Pass parameters as a JSON object. Only **required** fields (marked ✅) must be included.", - "All others default to sensible values.\n", - "```text", - "Goal: calculate mass of the open model", - "", - "Tool: calculate_mass_properties", - "Payload: {}", - "```\n", - "```text", - "Goal: export active part to STEP", - "", - "Tool: export_step", - "Payload:", - '{ "file_path": "C:\\\\Temp\\\\part.step" }', - "```", - ] - - return "\n".join(lines) - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- - - -def main(argv: list[str] | None = None) -> None: - """Handle main. - - Args: - argv (list[str] | None): The argv value. Defaults to None. - - Returns: - None: None. - """ - - args = argv or sys.argv[1:] - output_dir = Path("docs/user-guide/tool-catalog") - json_only = False - json_path = Path("tests/.generated/tool_catalog.json") - - i = 0 - while i < len(args): - if args[i] == "--output-dir" and i + 1 < len(args): - output_dir = Path(args[i + 1]) - i += 2 - elif args[i] == "--json-only": - json_only = True - i += 1 - elif args[i] == "--json-path" and i + 1 < len(args): - json_path = Path(args[i + 1]) - i += 2 - else: - i += 1 - - project_root = Path(__file__).resolve().parents[2] - tools_dir = project_root / "src" / "solidworks_mcp" / "tools" - - print(f"Parsing tool source files in: {tools_dir}") - catalog = build_catalog(tools_dir) - print(f"Found {len(catalog)} tools\n") - - # Always write JSON - json_out_path = project_root / json_path - json_out_path.parent.mkdir(parents=True, exist_ok=True) - with open(json_out_path, "w", encoding="utf-8") as fh: - json.dump(catalog, fh, indent=2) - print(f"JSON catalog -> {json_out_path}") - - if json_only: - return - - # Write Markdown pages - abs_output = project_root / output_dir - abs_output.mkdir(parents=True, exist_ok=True) - - # Group by category - cat_tools: dict[str, list[dict[str, Any]]] = {} - for tool in catalog: - cat_tools.setdefault(tool["category"], []).append(tool) - - # Index page - index_md = generate_index_page(catalog) - (abs_output / "index.md").write_text(index_md, encoding="utf-8") - print(f" wrote index.md ({len(catalog)} tools)") - - # Per-category pages - for category, tools in sorted(cat_tools.items()): - meta = CATEGORY_META.get( - category, - { - "title": category.replace("_", " ").title() + " Tools", - "icon": ":material-tools:", - "description": f"Tools in the {category} category.", - "prerequisite": "SolidWorks running", - }, - ) - slug = category.replace("_", "-") - page_md = generate_category_page(category, tools, meta) - out_file = abs_output / f"{slug}.md" - out_file.write_text(page_md, encoding="utf-8") - print(f" wrote {slug}.md ({len(tools)} tools)") - - print(f"\nCatalog written to: {abs_output}") - print(" Add 'tool-catalog/index.md' to mkdocs.yml nav to publish.") - - -if __name__ == "__main__": - main() diff --git a/tests/conftest.py b/tests/conftest.py index f1046295..9be05b79 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -167,6 +167,7 @@ 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) @pytest.fixture(scope="session") diff --git a/tests/integration/test_all_endpoints_harness.py b/tests/integration/test_all_endpoints_harness.py index 23a8cfac..0348ec2d 100644 --- a/tests/integration/test_all_endpoints_harness.py +++ b/tests/integration/test_all_endpoints_harness.py @@ -28,7 +28,6 @@ REAL_SW_FLAG = "SOLIDWORKS_MCP_RUN_REAL_INTEGRATION" OUTPUT_DIR = Path("tests/.generated/solidworks_integration") -CATALOG_PATH = Path("tests/.generated/tool_catalog.json") MAX_TOOL_RESPONSE_BYTES = 250_000 MAX_SMOKE_TOTAL_RESPONSE_BYTES = 3_000_000 SAMPLE_MODELS_ENV = "SOLIDWORKS_MCP_SAMPLE_MODELS_DIR" @@ -99,14 +98,6 @@ async def output_dir() -> Path: return OUTPUT_DIR -def _load_catalog() -> list[dict[str, Any]]: - """Test helper for load catalog.""" - if not CATALOG_PATH.exists(): - return [] - with open(CATALOG_PATH, encoding="utf-8") as fh: - return json.load(fh) - - async def _find_tool(server: SolidWorksMCPServer, tool_name: str): """Test helper for find tool.""" for tool in await server.mcp.list_tools(): @@ -200,33 +191,6 @@ async def test_tool_count_meets_minimum( "Run the server setup and registration pipeline before this test." ) - @pytest.mark.asyncio - async def test_all_catalog_tools_registered( - self, mock_server: SolidWorksMCPServer - ) -> None: - """Every tool listed in the JSON catalog must be registered in the server.""" - catalog = _load_catalog() - if not catalog: - pytest.skip( - "tool_catalog.json not found – run generate_tool_catalog.py first" - ) - - registered_names = {t.name for t in await mock_server.mcp.list_tools()} - missing: list[str] = [] - for entry in catalog: - name = entry["tool_name"] - # Also check func_name as some tools use a name= override - if ( - name not in registered_names - and entry["func_name"] not in registered_names - ): - missing.append(name) - - assert not missing, ( - f"{len(missing)} catalog tools NOT registered:\n" - + "\n".join(f" - {m}" for m in sorted(missing)) - ) - @pytest.mark.asyncio async def test_no_duplicate_tool_names( self, mock_server: SolidWorksMCPServer @@ -256,62 +220,6 @@ async def test_all_tools_have_callable_attribute( for tool in await mock_server.mcp.list_tools(): assert callable(tool.fn), f"Tool '{tool.name}' func is not callable" - @pytest.mark.asyncio - async def test_catalog_json_structure(self) -> None: - """The generated catalog JSON must have the expected schema.""" - catalog = _load_catalog() - if not catalog: - pytest.skip("tool_catalog.json not found") - - required_keys = { - "tool_name", - "func_name", - "category", - "description", - "fields", - "sample_payload", - } - for entry in catalog: - missing_keys = required_keys - set(entry.keys()) - assert not missing_keys, ( - f"Catalog entry '{entry.get('tool_name', '?')}' missing keys: {missing_keys}" - ) - - @pytest.mark.asyncio - async def test_category_coverage(self, mock_server: SolidWorksMCPServer) -> None: - """All expected tool categories must be represented.""" - catalog = _load_catalog() - if not catalog: - pytest.skip("tool_catalog.json not found") - categories = {e["category"] for e in catalog} - expected = { - "modeling", - "sketching", - "drawing", - "drawing_analysis", - "analysis", - "export", - "file_management", - "automation", - "vba_generation", - "template_management", - "macro_recording", - "docs_discovery", - } - missing_cats = expected - categories - assert not missing_cats, f"Missing tool categories in catalog: {missing_cats}" - - @pytest.mark.asyncio - async def test_tool_catalog_snapshot_written(self, output_dir: Path) -> None: - """Snapshot file must exist and contain tool names for regression detection.""" - snapshot_path = output_dir / "tool_catalog_snapshot.json" - catalog = _load_catalog() - if not catalog: - pytest.skip("tool_catalog.json not found") - names = [e["tool_name"] for e in catalog] - snapshot_path.write_text(json.dumps(names, indent=2), encoding="utf-8") - assert snapshot_path.exists() - def test_sample_path_candidates_include_supported_versions(self) -> None: """Candidate sample roots should include current and fallback SolidWorks years.""" candidates = [str(p).replace("\\", "/") for p in _candidate_sample_roots()] diff --git a/tests/integration/test_no_fabricated_payloads.py b/tests/integration/test_no_fabricated_payloads.py index 230cd6d1..d557b4c6 100644 --- a/tests/integration/test_no_fabricated_payloads.py +++ b/tests/integration/test_no_fabricated_payloads.py @@ -42,6 +42,7 @@ # Same local-index reads as search_solidworks_api_help, narrower queries. "lookup_api_method", "lookup_api_interface", + "get_api_enum", "find_related_api_members", "generate_vba_part_modeling", "generate_vba_assembly_mates", diff --git a/tests/integration/test_tool_catalog.py b/tests/integration/test_tool_catalog.py new file mode 100644 index 00000000..9156aacd --- /dev/null +++ b/tests/integration/test_tool_catalog.py @@ -0,0 +1,273 @@ +"""The tool catalog pages match the registered tools (spec: docs/tool-catalog). + +Each page under ``docs/user-guide/tool-catalog/`` is hand-written. This check +keeps it honest: every tool has one entry on its family's page, the entry's +parameter table lists exactly the tool's inputs, and its sample call is JSON +the tool's input model accepts. +""" + +from __future__ import annotations + +import asyncio +import inspect +import json +import re +import types +import typing +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest +from fastmcp import FastMCP +from pydantic import BaseModel, ValidationError + +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter +from solidworks_mcp.tools import register_tools + +CATALOG = Path(__file__).resolve().parents[2] / "docs" / "user-guide" / "tool-catalog" + +_HEADING = re.compile(r"^### `([a-z0-9_]+)`[^\n]*$", re.M) +_ROW = re.compile(r"^\| `([a-z0-9_]+)` \|", re.M) +_SAMPLE = re.compile(r"\*\*Sample call:\*\*\s*```json\n(.*?)\n```", re.S) + + +@dataclass(frozen=True) +class Entry: + """One tool's catalog entry. + + Attributes: + page: The page's file stem. + parameters: Field names in its parameter table; None when it has no + ``**Parameters:**`` table. + sample: The sample call's JSON text, if any. + """ + + page: str + parameters: frozenset[str] | None + sample: str | None + + +def parse_page(page: str, text: str) -> dict[str, Entry]: + """The entries on one catalog page, by tool name. + + Args: + page: The page's file stem. + text: Its markdown. + + Returns: + Each ``### `name``` entry's parameter names and sample call. + """ + entries = {} + headings = list(_HEADING.finditer(text)) + for i, heading in enumerate(headings): + end = headings[i + 1].start() if i + 1 < len(headings) else len(text) + body = text[heading.end() : end] + body = re.split(r"^## ", body, maxsplit=1, flags=re.M)[0] + parameters = None + if "**Parameters:**" in body: + table = body.split("**Parameters:**", 1)[1] + table = re.split(r"\n\s*\n(?!\|)", table.lstrip("\n"), maxsplit=1)[0] + parameters = frozenset(_ROW.findall(table)) + sample = _SAMPLE.search(body) + entries[heading.group(1)] = Entry( + page, parameters, sample.group(1) if sample else None + ) + return entries + + +#: What a tool takes: its input model, ``dict`` for free-form input whose +#: fields can't be checked, or None for no input. +Inputs = type[BaseModel] | type[dict] | None + + +def input_model(fn: Any) -> Inputs: + """What a tool takes as ``input_data`` (see :data:`Inputs`).""" + hint = typing.get_type_hints(inspect.unwrap(fn)).get("input_data") + if hint is None: + return None + options = typing.get_args(hint) if isinstance(hint, types.UnionType) else (hint,) + models = [o for o in options if isinstance(o, type) and issubclass(o, BaseModel)] + return models[0] if models else dict + + +def catalog_faults( + tools: dict[str, tuple[str, Inputs]], + pages: dict[str, str], +) -> list[str]: + """Every way the catalog pages disagree with the registered tools. + + Args: + tools: Tool name -> (family tag, what it takes). + pages: Page file stem -> its markdown. + + Returns: + One line per fault; empty when the pages match. + """ + entries: dict[str, list[Entry]] = {} + for page, text in pages.items(): + for name, entry in parse_page(page, text).items(): + entries.setdefault(name, []).append(entry) + faults = [ + f"{name}: catalog entry for a tool that isn't registered" + for name in sorted(set(entries) - set(tools)) + ] + for name, (family, model) in sorted(tools.items()): + page = family.replace("_", "-") + found = entries.get(name, []) + if [e.page for e in found] != [page]: + where = ", ".join(e.page for e in found) or "nowhere" + faults.append(f"{name}: needs one entry on {page}.md, found on {where}") + continue + (entry,) = found + fields = set(model.model_fields) if model and model is not dict else set() + listed = set(entry.parameters or ()) + if model is dict: + pass # free-form input: no fields to compare + elif fields and entry.parameters is None: + faults.append(f"{name}: no parameter table") + elif listed != fields: + if fields - listed: + faults.append(f"{name}: table misses {sorted(fields - listed)}") + if listed - fields: + faults.append(f"{name}: table lists {sorted(listed - fields)}") + if entry.sample is None: + faults.append(f"{name}: no sample call") + continue + try: + sample = json.loads(entry.sample) + except ValueError as exc: + faults.append(f"{name}: sample isn't JSON ({exc})") + continue + if model is not None and model is not dict: + try: + model.model_validate(sample) + except ValidationError as exc: + first = exc.errors()[0] + faults.append(f"{name}: sample refused: {first['loc']} {first['msg']}") + return faults + + +@pytest.fixture(scope="module") +def registered() -> dict[str, tuple[str, Inputs]]: + """Every registered tool's family and input model.""" + + async def _tools() -> list[Any]: + mcp = FastMCP("catalog") + await register_tools(mcp, MockSolidWorksAdapter({}), {}) + return list(await mcp.list_tools()) + + found = {} + for tool in asyncio.run(_tools()): + family = next(t for t in tool.tags if ":" not in t) + found[tool.name] = (family, input_model(tool.fn)) + return found + + +def test_the_catalog_matches_the_registered_tools(registered) -> None: + pages = { + p.stem: p.read_text(encoding="utf-8") + for p in CATALOG.glob("*.md") + if p.stem != "index" + } + + assert catalog_faults(registered, pages) == [] + + +class _Box(BaseModel): + """A stand-in tool input.""" + + width: float + label: str = "x" + + +_PAGE = """# Shapes + +### `make_box` + +Make a box. + +**Parameters:** + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `width` | `float` | yes | | Width | +| `label` | `str` | | `"x"` | Label | + +**Sample call:** + +```json +{ "width": 2 } +``` + +--- + +### `list_boxes` + +**Parameters:** none + +**Sample call:** + +```json +{} +``` + +## Notes +""" + + +def test_a_matching_page_has_no_faults() -> None: + tools = {"make_box": ("shapes", _Box), "list_boxes": ("shapes", None)} + + assert catalog_faults(tools, {"shapes": _PAGE}) == [] + + +@pytest.mark.parametrize( + ("page", "fault"), + [ + ( + _PAGE.replace("| `label` |", "| `colour` |"), + "make_box: table misses ['label']", + ), + ( + _PAGE.replace("| `label` |", "| `colour` |"), + "make_box: table lists ['colour']", + ), + ( + _PAGE.replace('{ "width": 2 }', '{ "width": null }'), + "make_box: sample refused", + ), + (_PAGE.replace('{ "width": 2 }', "{ width }"), "make_box: sample isn't JSON"), + ( + _PAGE.replace("**Sample call:**\n\n```json\n{}\n```", ""), + "list_boxes: no sample call", + ), + ( + _PAGE.replace("**Parameters:**\n\n| Parameter", "| Parameter"), + "make_box: no parameter table", + ), + ], + ids=[ + "missing field", + "extra field", + "null sample", + "bad json", + "no sample", + "no table", + ], +) +def test_each_fault_is_named(page: str, fault: str) -> None: + tools = {"make_box": ("shapes", _Box), "list_boxes": ("shapes", None)} + + assert any(f.startswith(fault) for f in catalog_faults(tools, {"shapes": page})) + + +def test_a_missing_and_an_unknown_entry_are_named() -> None: + tools = {"make_box": ("solids", _Box), "list_boxes": ("shapes", None)} + page = _PAGE.replace("### `list_boxes`", "### `old_tool`") + + faults = catalog_faults(tools, {"shapes": page}) + + assert "old_tool: catalog entry for a tool that isn't registered" in faults + assert "list_boxes: needs one entry on shapes.md, found on nowhere" in faults + assert "make_box: needs one entry on solids.md, found on shapes" in faults diff --git a/tests/integration/test_type_ignores.py b/tests/integration/test_type_ignores.py new file mode 100644 index 00000000..26454bbd --- /dev/null +++ b/tests/integration/test_type_ignores.py @@ -0,0 +1,32 @@ +"""Every ``# type: ignore`` in the package names its error code (spec: release/type-checking).""" + +from __future__ import annotations + +import re +from pathlib import Path + +SRC = Path(__file__).resolve().parents[2] / "src" / "solidworks_mcp" + +#: ``# type: ignore`` not followed by ``[code]``. +_BARE = re.compile(r"#\s*type:\s*ignore(?!\[)") + + +def bare_ignores(root: Path) -> list[str]: + """``file:line`` of every bare ``# type: ignore`` under ``root``.""" + found = [] + for path in sorted(root.rglob("*.py")): + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if _BARE.search(line): + found.append(f"{path.relative_to(root)}:{number}") + return found + + +def test_no_bare_type_ignore() -> None: + assert bare_ignores(SRC) == [] + + +def test_a_bare_ignore_is_found(tmp_path: Path) -> None: + (tmp_path / "m.py").write_text( + "x = 1 # type: ignore\ny = 2 # type: ignore[assignment]\n", encoding="utf-8" + ) + assert bare_ignores(tmp_path) == ["m.py:1"] diff --git a/tests/live/test_live_sw_api_lookup.py b/tests/live/test_live_sw_api_lookup.py index 6765644b..5f2d9e00 100644 --- a/tests/live/test_live_sw_api_lookup.py +++ b/tests/live/test_live_sw_api_lookup.py @@ -69,7 +69,7 @@ def _brief(response: dict[str, Any]) -> dict[str, Any]: result = shown.get("result") if isinstance(result, dict): result = dict(result) - for key in ("methods", "properties", "related"): + for key in ("methods", "properties", "related", "members"): if isinstance(result.get(key), list) and len(result[key]) > 6: result[key] = [*result[key][:6], f"... {len(result[key]) - 6} more"] shown["result"] = result @@ -190,6 +190,34 @@ async def test_real_signatures_come_from_the_type_library(agent: _Agent) -> None ] +@pytest.mark.asyncio +async def test_enum_values_come_from_the_constants_library(agent: _Agent) -> None: + """Enum values (#95): the unit systems, by enum and by member name.""" + units = await agent.call( + "swUnitSystem_e: the values set_units needed (IPS is 3, not 4)", + "get_api_enum", + name="swUnitSystem_e", + ) + member = await agent.call( + "A member's name, any case: its enum, with the member marked", + "get_api_enum", + name="swinches", + ) + unknown = await agent.call( + "A made-up enum: no match, and why", + "get_api_enum", + name="swNoSuchThing_e", + ) + + values = {m["name"]: m["value"] for m in units["result"]["members"]} + assert values["swUnitSystem_IPS"] == 3 + assert values["swUnitSystem_MMGS"] == 5 + assert {m["name"]: m["value"] for m in member["result"]["members"]}["swMM"] == 0 + assert member["result"]["enum"] == "swLengthUnit_e" + assert member["result"]["matched_member"] == "swINCHES" + assert unknown["result"]["found"] is False + + @pytest.mark.asyncio async def test_a_made_up_name_and_a_wrong_casing_are_caught(agent: _Agent) -> None: """Demo 3: the two mistakes an agent makes, answered plainly.""" diff --git a/tests/live/test_live_sw_macro_dialog.py b/tests/live/test_live_sw_macro_dialog.py new file mode 100644 index 00000000..07b24e9d --- /dev/null +++ b/tests/live/test_live_sw_macro_dialog.py @@ -0,0 +1,103 @@ +"""A macro that waits for the user fails cleanly instead of hanging (#97). + +1. ``MsgBox "Done"``: after ``dialog_timeout`` (3 s) the box is answered OK + and the run is an error, ``macro_waited_for_user``, naming the box; +2. an OK/Cancel prompt whose OK would add a sketch: the watch answers + Cancel, so no sketch is added; +3. a macro with no dialog still succeeds. + +Run it with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_macro_dialog.py + +Watch SolidWorks: each dialog appears, stays about 3 s, then closes by +itself. Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on +Windows. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from tests.live.evidence import evidence, note +from tests.live.test_live_sw_beta_tools import _feature_names, _tools + +pytestmark = pytest.mark.asyncio + +_SKETCH = """ Part.ClearSelection2 True + Part.Extension.SelectByID2 "Front Plane", "PLANE", 0, 0, 0, False, 0, Nothing, 0 + Part.SketchManager.InsertSketch True + Part.SketchManager.CreatePoint 0, 0, 0 + Part.SketchManager.InsertSketch True +""" + +_HEAD = """Dim swApp As Object +Dim Part As Object +Sub main() + Set swApp = Application.SldWorks + Set Part = swApp.ActiveDoc +""" + + +def _macro(tmp_path: Path, name: str, body: str) -> str: + """Write a legacy text macro (.swb) and return its path.""" + path = tmp_path / f"{name}.swb" + path.write_text(_HEAD + body + "End Sub\n", encoding="ascii") + return str(path) + + +async def test_a_waiting_macro_is_answered_and_fails( + scratch: Any, tmp_path: Path +) -> None: + """MsgBox answered OK; an OK/Cancel prompt answered Cancel; no dialog: success.""" + tools = await _tools(scratch.adapter) + assert (await tools["create_part"]({"name": "macro_dialog"}))["status"] == "success" + note( + "A macro that waits for the user", + "Each dialog stays up 3 s, then the server answers it (OK, or Cancel " + "when there is one) and reports the run as an error instead of hanging.", + seconds=4.0, + ) + + done = await tools["execute_macro"]( + { + "macro_path": _macro(tmp_path, "msgbox", ' MsgBox "Done"\n'), + "dialog_timeout": 3, + } + ) + evidence( + "MsgBox: answered OK after 3 s, the run an error", + {k: done.get(k) for k in ("status", "error_type", "message")}, + ) + + before = await _feature_names(scratch.adapter) + prompt = ( + ' If MsgBox("Add a sketch?", vbOKCancel) = vbOK Then\n' + + _SKETCH.replace("\n ", "\n ").replace(" Part", " Part", 1) + + " End If\n" + ) + asked = await tools["execute_macro"]( + {"macro_path": _macro(tmp_path, "prompt", prompt), "dialog_timeout": 3} + ) + added = [n for n in await _feature_names(scratch.adapter) if n not in before] + evidence( + "OK/Cancel prompt: answered Cancel, so no sketch was added", + {"message": asked.get("message"), "added": added}, + ) + + quiet = await tools["execute_macro"]( + {"macro_path": _macro(tmp_path, "quiet", _SKETCH), "dialog_timeout": 3} + ) + evidence("No dialog: the macro runs as before", quiet.get("message")) + + assert done["status"] == "error" + assert done["error_type"] == "macro_waited_for_user" + assert "'Done' (answered 'OK')" in done["message"] + assert asked["error_type"] == "macro_waited_for_user" + assert "(answered 'Cancel')" in asked["message"] + assert added == [] + assert quiet["status"] == "success", quiet diff --git a/tests/live/test_live_sw_macro_source.py b/tests/live/test_live_sw_macro_source.py new file mode 100644 index 00000000..7bdab77a --- /dev/null +++ b/tests/live/test_live_sw_macro_source.py @@ -0,0 +1,96 @@ +"""VBA source run through execute_macro, when the server allows it (#96). + +1. With ``allow_vba_source`` on: VBA source that sketches a point on the + Front Plane runs, and one new sketch appears; the reply names the .swb + it wrote and repeats the source; +2. with it off (the default): the same call is refused as + ``vba_source_off`` and nothing is added. + +Run it with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_macro_source.py + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastmcp import FastMCP + +from solidworks_mcp.config import SolidWorksMCPConfig +from solidworks_mcp.tools.macro_recording import register_macro_recording_tools +from tests.live.evidence import evidence, note +from tests.live.test_live_sw_beta_tools import _feature_names, _tools + +pytestmark = pytest.mark.asyncio + +SOURCE = """Dim swApp As Object +Dim Part As Object +Sub main() + Set swApp = Application.SldWorks + Set Part = swApp.ActiveDoc + Part.ClearSelection2 True + Part.Extension.SelectByID2 "Front Plane", "PLANE", 0, 0, 0, False, 0, Nothing, 0 + Part.SketchManager.InsertSketch True + Part.SketchManager.CreatePoint 0, 0, 0 + Part.SketchManager.InsertSketch True +End Sub +""" + + +async def _execute_macro(adapter: Any, allow: bool) -> Any: + """execute_macro registered with ``allow_vba_source`` set as given.""" + mcp = FastMCP("macro-source-live") + config = SolidWorksMCPConfig(allow_vba_source=allow) + await register_macro_recording_tools(mcp, adapter, config) + return next(t.fn for t in await mcp.list_tools() if t.name == "execute_macro") + + +async def test_vba_source_runs_only_when_allowed(scratch: Any) -> None: + """Allowed: the source adds a sketch. Not allowed: refused, nothing added.""" + tools = await _tools(scratch.adapter) + assert (await tools["create_part"]({"name": "vba_source"}))["status"] == "success" + note( + "VBA source, run by execute_macro", + "Allowed on this server: the source sketches a point. Then the same " + "call on a server that doesn't allow it, refused on purpose.", + seconds=4.0, + ) + before = await _feature_names(scratch.adapter) + allowed = await (await _execute_macro(scratch.adapter, True))( + {"vba_source": SOURCE} + ) + scratch.written_files.append(allowed.get("source_file", "")) + added = [n for n in await _feature_names(scratch.adapter) if n not in before] + evidence( + "Allowed: the source ran and added a sketch", + { + "status": allowed.get("status"), + "source_file": allowed.get("source_file"), + "added": added, + }, + ) + + after = await _feature_names(scratch.adapter) + refused = await (await _execute_macro(scratch.adapter, False))( + {"vba_source": SOURCE} + ) + unchanged = await _feature_names(scratch.adapter) == after + evidence( + "Not allowed: refused, and nothing changed", + { + "error_type": refused.get("error_type"), + "message": refused.get("message"), + "unchanged": unchanged, + }, + ) + + assert allowed["status"] == "success", allowed + assert allowed["source_file"].endswith(".swb") + assert len(added) == 1 + assert refused["error_type"] == "vba_source_off" + assert unchanged diff --git a/tests/live/test_live_sw_wave3.py b/tests/live/test_live_sw_wave3.py index 45a6c4d1..68fef2e6 100644 --- a/tests/live/test_live_sw_wave3.py +++ b/tests/live/test_live_sw_wave3.py @@ -52,10 +52,25 @@ async def test_save_body_as_part_writes_the_body_file(scratch, tmp_path): scratch.written_files.append(str(target)) result = await adapter.save_body_as_part(body_name, str(target)) + listed = await adapter.list_open_documents() + stray = [ + d["title"] + for d in listed.data or [] + if d["type"] == "Assembly" and not d["path"] + ] + evidence( + "save_body_as_part: the file, and no unsaved assembly left open (#101)", + { + "file_path": (result.data or {}).get("file_path"), + "closed_documents": (result.data or {}).get("closed_documents"), + "unsaved_assemblies_open": stray, + }, + ) assert result.is_success, result.error assert result.data["body"] == body_name assert body_name in result.data["solid_bodies"] assert os.path.exists(target) + assert stray == [] @pytest.mark.asyncio diff --git a/tests/solidworks_mcp/adapters/solidworks/test_dialog_watch.py b/tests/solidworks_mcp/adapters/solidworks/test_dialog_watch.py new file mode 100644 index 00000000..b11c4677 --- /dev/null +++ b/tests/solidworks_mcp/adapters/solidworks/test_dialog_watch.py @@ -0,0 +1,261 @@ +"""The dialog watch that keeps a waiting macro from hanging the server (#97). + +Windows are faked; the real Win32 calls are checked against a fake +``win32gui`` and ``win32process``. +""" + +from __future__ import annotations + +import time +from types import SimpleNamespace +from typing import Any + +import pytest + +from solidworks_mcp.adapters.solidworks.dialog_watch import ( + DialogSeen, + DialogWatch, + Win32Windows, + waited_message, +) + +WM_CLOSE, WM_COMMAND = 0x0010, 0x0111 + + +class FakeWindows: + """Dialogs by hwnd: ``{hwnd: (title, [(child hwnd, class, text)])}``.""" + + def __init__(self, dialogs: dict[int, tuple[str, list[tuple[int, str, str]]]]): + self.open = dict(dialogs) + self.posted: list[tuple[int, int, int, int]] = [] + + def dialogs(self, pid: int) -> list[int]: + assert pid == 42 + return list(self.open) + + def title(self, hwnd: int) -> str: + return self.open[hwnd][0] + + def children(self, hwnd: int) -> list[tuple[int, str, str]]: + return self.open[hwnd][1] + + def control_id(self, hwnd: int) -> int: + return hwnd % 100 + + def post(self, hwnd: int, message: int, wparam: int, lparam: int) -> None: + self.posted.append((hwnd, message, wparam, lparam)) + + +class Clock: + """A clock the test moves by hand.""" + + def __init__(self) -> None: + self.now = 0.0 + + def __call__(self) -> float: + return self.now + + +def _watch(windows: FakeWindows, clock: Clock) -> DialogWatch: + return DialogWatch(42, timeout=5, windows=windows, clock=clock) + + +_MSGBOX = ("SOLIDWORKS", [(201, "Static", "Done"), (102, "Button", "OK")]) + + +def test_a_dialog_is_answered_only_after_the_timeout() -> None: + windows, clock = FakeWindows({1: _MSGBOX}), Clock() + watch = _watch(windows, clock) + + watch.check() + clock.now = 4.9 + watch.check() + assert windows.posted == [] + + clock.now = 5.0 + watch.check() + watch.check() # answered once only + + assert windows.posted == [(1, WM_COMMAND, 2, 102)] + assert watch.seen == [DialogSeen("SOLIDWORKS", "Done", ("OK",), "OK")] + + +def test_cancel_wins_over_ok() -> None: + prompt = ( + "Confirm", + [ + (301, "Static", "Overwrite?"), + (101, "Button", "OK"), + (102, "Button", "&Cancel"), + ], + ) + windows, clock = FakeWindows({1: prompt}), Clock() + watch = _watch(windows, clock) + + watch.check() + clock.now = 6 + watch.check() + + assert windows.posted == [(1, WM_COMMAND, 2, 102)] + assert watch.seen[0].answer == "Cancel" + assert watch.seen[0].buttons == ("OK", "Cancel") + + +def test_yes_and_no_are_left_for_the_user() -> None: + question = ("Save?", [(101, "Button", "&Yes"), (102, "Button", "&No")]) + windows, clock = FakeWindows({1: question}), Clock() + watch = _watch(windows, clock) + + watch.check() + clock.now = 6 + watch.check() + + assert windows.posted == [] + assert watch.seen == [DialogSeen("Save?", "", ("Yes", "No"), None)] + + +def test_a_form_without_buttons_is_closed() -> None: + windows, clock = FakeWindows({1: ("UserForm1", [])}), Clock() + watch = _watch(windows, clock) + + watch.check() + clock.now = 6 + watch.check() + + assert windows.posted == [(1, WM_CLOSE, 0, 0)] + assert watch.seen[0].answer == "closed" + + +def test_a_dialog_open_before_the_macro_is_ignored() -> None: + windows, clock = FakeWindows({1: _MSGBOX}), Clock() + + with _watch(windows, clock) as watch: + clock.now = 60 + watch.check() + + assert windows.posted == [] + assert watch.seen == [] + + +def test_the_thread_answers_a_dialog_while_the_call_runs() -> None: + windows = FakeWindows({}) + watch = DialogWatch(42, timeout=0, windows=windows, poll=0.01) + + with watch: + windows.open[7] = _MSGBOX + deadline = time.monotonic() + 5 + while not watch.seen and time.monotonic() < deadline: + time.sleep(0.01) + + assert watch.seen[0].answer == "OK" + + +def test_a_failing_watch_stops_quietly() -> None: + class Broken(FakeWindows): + def dialogs(self, pid: int) -> list[int]: + if self.posted is not None and getattr(self, "started", False): + raise OSError("EnumWindows failed") + self.started = True + return [] + + watch = DialogWatch(42, timeout=0, windows=Broken({}), poll=0.01) + + with watch: + time.sleep(0.05) + + assert watch.seen == [] + + +@pytest.mark.parametrize( + ("seen", "expected"), + [ + ( + DialogSeen("SOLIDWORKS", "Done", ("OK",), "OK"), + "'SOLIDWORKS': 'Done' (answered 'OK')", + ), + (DialogSeen("UserForm1", "", (), "closed"), "'UserForm1' (closed)"), + ( + DialogSeen("Save?", "", ("Yes", "No"), None), + "'Save?' (left open: it has no Cancel and more than one button)", + ), + ], +) +def test_describe(seen: DialogSeen, expected: str) -> None: + assert seen.describe() == expected + + +def test_the_error_names_the_dialog_and_the_rule() -> None: + message = waited_message([DialogSeen("SOLIDWORKS", "Done", ("OK",), "OK")], 30) + + assert message.startswith( + "The macro waited for the user: after 30 s a dialog was still open, " + "'SOLIDWORKS': 'Done' (answered 'OK')." + ) + assert "must not wait for the user" in message + + +class FakeGui: + """The ``win32gui`` calls ``Win32Windows`` makes.""" + + def __init__(self) -> None: + self.windows: dict[int, dict[str, Any]] = { + 1: {"class": "#32770", "visible": True, "text": "SOLIDWORKS", "pid": 42}, + 2: {"class": "#32770", "visible": False, "text": "hidden", "pid": 42}, + 3: {"class": "Notepad", "visible": True, "text": "notes", "pid": 42}, + 4: {"class": "ThunderDFrame", "visible": True, "text": "Form", "pid": 7}, + 11: {"class": "Static", "text": "Done", "parent": 1}, + 12: {"class": "Button", "text": "OK", "parent": 1, "id": 2}, + } + self.posted: list[tuple[int, int, int, int]] = [] + + def EnumWindows(self, visit: Any, extra: Any) -> None: + for hwnd, w in self.windows.items(): + if "parent" not in w: + visit(hwnd, extra) + + def EnumChildWindows(self, parent: int, visit: Any, extra: Any) -> None: + for hwnd, w in self.windows.items(): + if w.get("parent") == parent: + visit(hwnd, extra) + + def IsWindowVisible(self, hwnd: int) -> bool: + return self.windows[hwnd]["visible"] + + def GetClassName(self, hwnd: int) -> str: + return self.windows[hwnd]["class"] + + def GetWindowText(self, hwnd: int) -> str: + return self.windows[hwnd]["text"] + + def GetDlgCtrlID(self, hwnd: int) -> int: + return self.windows[hwnd]["id"] + + def PostMessage(self, hwnd: int, message: int, wparam: int, lparam: int) -> None: + self.posted.append((hwnd, message, wparam, lparam)) + + +def test_win32_windows_reads_and_posts_through_win32gui() -> None: + gui = FakeGui() + process = SimpleNamespace( + GetWindowThreadProcessId=lambda hwnd: (0, gui.windows[hwnd]["pid"]) + ) + windows = Win32Windows(gui, process) + + assert windows.dialogs(42) == [1] + assert windows.title(1) == "SOLIDWORKS" + assert windows.children(1) == [(11, "Static", "Done"), (12, "Button", "OK")] + assert windows.control_id(12) == 2 + windows.post(1, WM_COMMAND, 2, 12) + assert gui.posted == [(1, WM_COMMAND, 2, 12)] + + +def test_win32_windows_imports_pywin32_by_default(monkeypatch) -> None: + import sys + + gui, process = SimpleNamespace(name="gui"), SimpleNamespace(name="process") + monkeypatch.setitem(sys.modules, "win32gui", gui) + monkeypatch.setitem(sys.modules, "win32process", process) + + windows = Win32Windows() + + assert (windows._gui, windows._process) == (gui, process) diff --git a/tests/solidworks_mcp/adapters/solidworks/test_dimension_layout.py b/tests/solidworks_mcp/adapters/solidworks/test_dimension_layout.py index 59035132..90509f5c 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_dimension_layout.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_dimension_layout.py @@ -482,6 +482,16 @@ def test_the_note_is_planned_inside_near_its_hole(self) -> None: pos.lines = lay._projected_segments(pos, *moves["pos"], OUTLINE) assert lay.find_overlaps([pos, hole], {"View1": OUTLINE}) == [] + def test_a_leader_with_no_lines_is_placed_outside(self) -> None: + pos, hole = self._plate() + hole.lines = [] # no leader to anchor the text inside + moves, unplaced = lay.plan_layout( + [pos, hole], {"View1": OUTLINE}, inside_first={"dia"} + ) + assert not unplaced + box = lay.shift_box(hole.text_box, *moves["dia"]) + assert not lay.box_overlap(box, OUTLINE) + def test_no_room_inside_falls_back_to_outside(self) -> None: pos, hole = self._plate() hole.text_box = (0.0, 0.0, 0.2, 0.012) # wider than the view diff --git a/tests/solidworks_mcp/adapters/solidworks/test_io.py b/tests/solidworks_mcp/adapters/solidworks/test_io.py index f54d0142..588c971e 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_io.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_io.py @@ -4234,10 +4234,70 @@ async def test_save_body_as_part_writes_the_file(tmp_path, monkeypatch) -> None: "file_path": str(target), "feature": None, "solid_bodies": ["Body1"], + "closed_documents": [], } assert target.read_bytes() == b"body" +class _SaveBodiesApp: + """An application whose Save Bodies call opens a new unsaved assembly.""" + + def __init__(self, part) -> None: + self.docs = [ + part, + SimpleNamespace( + GetTitle=lambda: "Assem1", + GetPathName=lambda: "C:/a.SLDASM", + GetType=lambda: 2, + ), + SimpleNamespace( + GetTitle=lambda: "Assem2", GetPathName=lambda: "", GetType=lambda: 2 + ), + ] + self.closed: list[str] = [] + self.activated: list[str] = [] + + def GetDocuments(self): + return list(self.docs) + + def CloseDoc(self, title): + self.closed.append(title) + self.docs = [d for d in self.docs if d.GetTitle() != title] + + def ActivateDoc3(self, title, *_a): + self.activated.append(title) + + +@pytest.mark.asyncio +async def test_save_body_as_part_closes_the_assembly_it_left_open( + tmp_path, monkeypatch +) -> None: + monkeypatch.setattr( + _io_module, "pythoncom", SimpleNamespace(VT_DISPATCH=9, VT_BSTR=8) + ) + monkeypatch.setattr(_io_module, "_byref_int", lambda: 0) + target = tmp_path / "body.sldprt" + part = _part_with([SimpleNamespace(Name="Body1")], writes=target) + part.GetTitle = lambda: "Part1" + part.GetPathName = lambda: "C:/p.SLDPRT" + app = _SaveBodiesApp(part) + saved_assembly, stray = app.docs[1], app.docs[2] + app.docs = [part, saved_assembly] # open before the call + original = part.FeatureManager.CreateSaveBodyFeature + + def _save(*args): + app.docs.append(stray) # Save Bodies opens a new, unsaved assembly + return original(*args) + + part.FeatureManager.CreateSaveBodyFeature = _save + + result = await _DocsHarness(part, app).save_body_as_part("Body1", str(target)) + + assert result.data["closed_documents"] == ["Assem2"] + assert app.closed == ["Assem2"] # not Assem1, which was open and saved + assert app.activated == ["Part1"] + + # ---- export_image: SaveBMP at the requested size -------------------------------- diff --git a/tests/solidworks_mcp/adapters/test_pywin32_adapter_macro_dialog.py b/tests/solidworks_mcp/adapters/test_pywin32_adapter_macro_dialog.py new file mode 100644 index 00000000..9ce969c9 --- /dev/null +++ b/tests/solidworks_mcp/adapters/test_pywin32_adapter_macro_dialog.py @@ -0,0 +1,79 @@ +"""``execute_macro`` runs RunMacro2 inside the dialog watch (#97).""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import pytest + +import solidworks_mcp.adapters.pywin32_adapter as module +from solidworks_mcp.adapters.solidworks.dialog_watch import DialogSeen +from solidworks_mcp.exceptions import SolidWorksMCPError +from tests.solidworks_mcp.adapters.solidworks.test_io import _build_adapter + + +class FakeWatch: + """Stands in for DialogWatch: records how it was made and what it 'saw'.""" + + made: list[tuple[int, float]] = [] + seen_next: list[DialogSeen] = [] + + def __init__(self, pid: int, timeout: float) -> None: + FakeWatch.made.append((pid, timeout)) + self.seen = list(FakeWatch.seen_next) + + def __enter__(self) -> FakeWatch: + return self + + def __exit__(self, *_exc: Any) -> None: + return None + + +@pytest.fixture +def adapter(monkeypatch: pytest.MonkeyPatch) -> Any: + FakeWatch.made, FakeWatch.seen_next = [], [] + monkeypatch.setattr(module, "DialogWatch", FakeWatch) + built = _build_adapter(monkeypatch) + built.swApp = SimpleNamespace( + GetProcessID=lambda: 4242, RunMacro2=lambda *_a: (True, 0) + ) + return built + + +def test_the_macro_runs_inside_a_watch_on_the_solidworks_process(adapter) -> None: + result = adapter._invoke_run_macro2("m.swp", "Module1", "main", 12) + + assert FakeWatch.made == [(4242, 12)] + assert result["errors"] == 0 + + +def test_a_dialog_the_watch_answered_makes_the_run_an_error(adapter) -> None: + FakeWatch.seen_next = [DialogSeen("SOLIDWORKS", "Done", ("OK",), "OK")] + + with pytest.raises(SolidWorksMCPError) as raised: + adapter._invoke_run_macro2("m.swp", "Module1", "main", 5) + + assert str(raised.value).startswith( + "The macro waited for the user: after 5 s a dialog was still open, " + "'SOLIDWORKS': 'Done' (answered 'OK')." + ) + + +def test_without_a_process_id_the_macro_runs_unwatched(adapter) -> None: + adapter.swApp = SimpleNamespace(RunMacro2=lambda *_a: (True, 0)) + + assert adapter._invoke_run_macro2("m.swp", "Module1", "main")["errors"] == 0 + assert FakeWatch.made == [] + + +@pytest.mark.asyncio +async def test_execute_macro_passes_its_dialog_timeout(adapter, tmp_path) -> None: + macro = tmp_path / "m.swp" + macro.write_bytes(b"") + adapter._handle_com_operation = lambda _name, operation: operation() + + await adapter.execute_macro({"macro_path": str(macro), "dialog_timeout": 7}) + await adapter.execute_macro({"macro_path": str(macro)}) + + assert [timeout for _pid, timeout in FakeWatch.made] == [7.0, 30.0] diff --git a/tests/solidworks_mcp/tools/test_docs_discovery.py b/tests/solidworks_mcp/tools/test_docs_discovery.py index 5056c6ce..7dc04acd 100644 --- a/tests/solidworks_mcp/tools/test_docs_discovery.py +++ b/tests/solidworks_mcp/tools/test_docs_discovery.py @@ -25,6 +25,7 @@ ) from solidworks_mcp.server import SolidWorksMCPServer from solidworks_mcp.tools.docs_discovery import ( + INDEX_FORMAT, SolidWorksDocsDiscovery, _discover_vba_references_via_registry, _extract_year, @@ -32,6 +33,7 @@ _find_index_file, _find_related_api_members, _load_index_file, + _lookup_enum, _lookup_interface, _lookup_method, _resolve_solidworks_year, @@ -41,6 +43,7 @@ from solidworks_mcp.tools.tool_boundary import ToolOperationError from solidworks_mcp.tools.type_library import ( SOLIDWORKS_TYPELIB_GUID, + ApiEnum, ApiInterface, TypeLibraryInfo, ) @@ -111,6 +114,21 @@ def _iface(**members: dict) -> dict: ), } +_ENUMS = { + "swUnitSystem_e": { + "description": None, + "members": [ + {"name": "swUnitSystem_CGS", "value": 1}, + {"name": "swUnitSystem_IPS", "value": 3}, + {"name": "swUnitSystem_MMGS", "value": 5}, + ], + }, + "swLengthUnit_e": { + "description": "Length units", + "members": [{"name": "swMM", "value": 0}, {"name": "swINCHES", "value": 3}], + }, +} + _LIBRARY = TypeLibraryInfo( guid=SOLIDWORKS_TYPELIB_GUID, version="34.0", @@ -154,6 +172,14 @@ def _load(year: int | None = None, strict: bool = False) -> tuple: for name, record in _COM_OBJECTS.items() }, ) + monkeypatch.setattr(docs_mod, "load_constants_library", lambda *_a: "constants") + monkeypatch.setattr( + docs_mod, + "index_enums", + lambda _lib: { + name: ApiEnum.model_validate(record) for name, record in _ENUMS.items() + }, + ) monkeypatch.setattr(docs_mod, "_discover_vba_references_via_registry", dict) # No RAG builder: discovery skips the rebuild instead of loading the # embedding model. A test that wants one sets its own. @@ -368,7 +394,7 @@ async def test_search_solidworks_api_help_with_index( index_path.write_text( json.dumps( { - "version": "2.0", + "version": INDEX_FORMAT, "com_objects": { "ISldWorks": { "methods": ["OpenDoc6", "CloseDoc"], @@ -689,7 +715,7 @@ async def test_discover_tool_top_level_exception_path( # #64 — granular API lookups (helpers are pure, no COM / no server) # --------------------------------------------------------------------------- -_LOOKUP_INDEX = {"version": "2.0", "com_objects": _COM_OBJECTS} +_LOOKUP_INDEX = {"version": INDEX_FORMAT, "com_objects": _COM_OBJECTS} def test_lookup_interface_known_returns_all_members(): @@ -801,6 +827,101 @@ async def test_granular_lookup_tools_registered_and_callable( assert isinstance(search["matches"], list) +_ENUM_INDEX = {"version": INDEX_FORMAT, "com_objects": {}, "enums": _ENUMS} + + +def test_an_enum_by_name_lists_its_members_and_values() -> None: + result = _dump(_lookup_enum(_ENUM_INDEX, "swUnitSystem_e")) + + assert result["found"] is True + assert result["enum"] == "swUnitSystem_e" + assert result["matched_member"] is None + assert {m["name"]: m["value"] for m in result["members"]} == { + "swUnitSystem_CGS": 1, + "swUnitSystem_IPS": 3, + "swUnitSystem_MMGS": 5, + } + + +def test_a_member_by_name_gives_its_enum_whatever_the_case() -> None: + result = _dump(_lookup_enum(_ENUM_INDEX, "swunitsystem_ips")) + + assert (result["enum"], result["matched_member"]) == ( + "swUnitSystem_e", + "swUnitSystem_IPS", + ) + assert _dump(_lookup_enum(_ENUM_INDEX, "SWLENGTHUNIT_E"))["description"] == ( + "Length units" + ) + + +def test_an_unknown_enum_name_says_so() -> None: + result = _dump(_lookup_enum(_ENUM_INDEX, "swNoSuch_e")) + + assert result["found"] is False + assert result["note"] == ( + "'swNoSuch_e' is neither an enum nor an enum member in the indexed " + "constants type library." + ) + + +def test_an_index_without_enums_says_why() -> None: + index = {"version": INDEX_FORMAT, "enums": {}, "enums_note": "swconst.tlb is gone."} + + assert ( + _dump(_lookup_enum(index, "swUnitSystem_e"))["note"] == "swconst.tlb is gone." + ) + + +def test_discovery_without_the_constants_library_keeps_the_rest( + fake_type_library: list[tuple], monkeypatch: pytest.MonkeyPatch +) -> None: + import solidworks_mcp.tools.docs_discovery as docs_mod + from solidworks_mcp.tools.type_library import TypeLibraryUnavailable + + def _missing(*_args: object) -> None: + raise TypeLibraryUnavailable("No swconst.tlb.") + + monkeypatch.setattr(docs_mod, "load_constants_library", _missing) + + index = SolidWorksDocsDiscovery().discover_all(include_vba=False) + + assert index["enums"] == {} + assert index["enums_note"] == "No swconst.tlb." + assert "ISldWorks" in index["com_objects"] + + +@pytest.mark.asyncio +async def test_get_api_enum_answers_from_the_built_index( + fake_type_library: list[tuple], mcp_server, mock_config +) -> None: + await register_docs_discovery_tools(mcp_server, object(), mock_config) + tools = {t.name: t.fn for t in await mcp_server.list_tools()} + + found = await tools["get_api_enum"]({"name": "swUnitSystem_IPS"}) + missing = await tools["get_api_enum"]({"name": "swNoSuch_e"}) + + assert found["status"] == "success" + assert found["message"] == "swUnitSystem_e: 3 members" + assert found["index_status"] == "rebuilt" + assert found["result"]["matched_member"] == "swUnitSystem_IPS" + assert missing["message"] == "No enum or enum member of that name" + assert missing["index_status"] == "ready" + + +@pytest.mark.asyncio +async def test_get_api_enum_without_a_type_library_says_why( + mcp_server, mock_config +) -> None: + await register_docs_discovery_tools(mcp_server, object(), mock_config) + tools = {t.name: t.fn for t in await mcp_server.list_tools()} + + result = await tools["get_api_enum"]({"name": "swUnitSystem_e"}) + + assert result["result"]["found"] is False + assert result["result"]["note"] == "No SolidWorks type library in this test." + + # --------------------------------------------------------------------------- # Docs index auto-refresh on staleness (config-gated) # --------------------------------------------------------------------------- @@ -868,7 +989,7 @@ def stale_index(tmp_path): index_file.write_text("{}") old = time.time() - 30 * 86400 os.utime(index_file, (old, old)) - return {"version": "2.0", "com_objects": {}}, index_file + return {"version": INDEX_FORMAT, "com_objects": {}}, index_file _REFRESH_ON = SimpleNamespace(docs_index_auto_refresh=True, docs_index_max_age_days=21) @@ -1204,7 +1325,7 @@ def test_discovery_reads_the_type_library(fake_type_library, tmp_path) -> None: index = discovery.discover_all() assert fake_type_library == [(2025, True)] - assert index["version"] == "2.0" + assert index["version"] == INDEX_FORMAT assert index["type_library"] == _LIBRARY.model_dump() assert index["solidworks_version"] == "34.0" assert index["com_objects"] == _COM_OBJECTS @@ -1310,7 +1431,7 @@ async def test_a_lookup_builds_a_missing_index( assert result["type_library_version"] == "34.0" saved = Path(result["source_index_file"]) assert saved.name == "solidworks_docs_index_2026.json" - assert json.loads(saved.read_text(encoding="utf-8"))["version"] == "2.0" + assert json.loads(saved.read_text(encoding="utf-8"))["version"] == INDEX_FORMAT assert result["result"]["found"] is True diff --git a/tests/solidworks_mcp/tools/test_error_classifier.py b/tests/solidworks_mcp/tools/test_error_classifier.py index 412b851b..7408ffc7 100644 --- a/tests/solidworks_mcp/tools/test_error_classifier.py +++ b/tests/solidworks_mcp/tools/test_error_classifier.py @@ -97,6 +97,11 @@ def classifier() -> ErrorClassifier: "sheet-metal body.", "wrong_document_type", ), + ( + "Failed to run the macro: The macro waited for the user: after 30 s " + "a dialog was still open, 'SOLIDWORKS': 'Done' (answered 'OK').", + "macro_waited_for_user", + ), ( "list_model_dimensions needs an active part or assembly document", "wrong_document_type", diff --git a/tests/solidworks_mcp/tools/test_macro_recording.py b/tests/solidworks_mcp/tools/test_macro_recording.py index 2a4c74fa..f3f2e0f0 100644 --- a/tests/solidworks_mcp/tools/test_macro_recording.py +++ b/tests/solidworks_mcp/tools/test_macro_recording.py @@ -295,3 +295,86 @@ async def test_execute_macro_refuses_removed_inputs_and_bad_counts( assert "open_model" in removed["message"] assert too_many["error_type"] == "invalid_input" mock_adapter.execute_macro.assert_not_awaited() + + +def test_dialog_timeout_defaults_to_30_s_and_is_bounded() -> None: + from pydantic import ValidationError + + assert MacroPlaybackInput(macro_file="m.swp").dialog_timeout == 30.0 + assert MacroPlaybackInput(macro_file="m.swp", dialog_timeout=5).dialog_timeout == 5 + for bad in (0.5, 601): + with pytest.raises(ValidationError): + MacroPlaybackInput(macro_file="m.swp", dialog_timeout=bad) + + +_SOURCE = 'Sub main()\n MsgBox "unused"\nEnd Sub\n' + + +async def _run_source(config, monkeypatch, tmp_path, **inputs): + """Call execute_macro with VBA source; return the reply and the adapter's params.""" + import tempfile + + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + mcp = FastMCP("macro") + adapter = MockSolidWorksAdapter({}) + seen: list[dict] = [] + + async def _execute(params: dict): + seen.append(dict(params)) + return Mock(is_success=True, data={"errors": 0}, execution_time=0.1) + + adapter.execute_macro = _execute + await register_macro_recording_tools(mcp, adapter, config) + tool = next(t for t in await mcp.list_tools() if t.name == "execute_macro") + return await tool.fn(input_data={"vba_source": _SOURCE, **inputs}), seen + + +@pytest.mark.asyncio +async def test_vba_source_runs_from_a_swb_when_allowed(monkeypatch, tmp_path) -> None: + from pathlib import Path + + config = SolidWorksMCPConfig(allow_vba_source=True) + + reply, seen = await _run_source(config, monkeypatch, tmp_path) + + written = Path(reply["source_file"]) + assert reply["status"] == "success" + assert reply["vba_source"] == _SOURCE + assert written.suffix == ".swb" + assert written.parent == tmp_path / "solidworks_mcp" / "macros" + assert written.read_text(encoding="cp1252") == _SOURCE + assert seen[0]["macro_path"] == str(written) + + +@pytest.mark.asyncio +async def test_vba_source_is_refused_when_not_allowed(monkeypatch, tmp_path) -> None: + reply, seen = await _run_source(SolidWorksMCPConfig(), monkeypatch, tmp_path) + + assert reply["status"] == "error" + assert reply["error_type"] == "vba_source_off" + assert "SOLIDWORKS_MCP_ALLOW_VBA_SOURCE=1" in reply["message"] + assert seen == [] + assert not (tmp_path / "solidworks_mcp").exists() + + +def test_the_setting_is_off_by_default_and_read_from_the_environment( + monkeypatch, +) -> None: + assert SolidWorksMCPConfig().allow_vba_source is False + monkeypatch.setenv("SOLIDWORKS_MCP_ALLOW_VBA_SOURCE", "1") + assert SolidWorksMCPConfig.from_env().allow_vba_source is True + + +@pytest.mark.parametrize( + ("inputs", "message"), + [ + ({"vba_source": "x", "macro_path": "m.swp"}, "not both"), + ({"vba_source": "Sub main()\n' \u2713\nEnd Sub"}, "can't hold"), + ], + ids=["two sources", "bad character"], +) +def test_vba_source_input_is_checked(inputs, message) -> None: + from pydantic import ValidationError + + with pytest.raises(ValidationError, match=message): + MacroPlaybackInput(**inputs) diff --git a/tests/solidworks_mcp/tools/test_type_library.py b/tests/solidworks_mcp/tools/test_type_library.py index baff06da..e377eed2 100644 --- a/tests/solidworks_mcp/tools/test_type_library.py +++ b/tests/solidworks_mcp/tools/test_type_library.py @@ -14,11 +14,14 @@ from solidworks_mcp.tools.tool_boundary import ToolOperationError from solidworks_mcp.tools.type_library import ( + CONSTANTS_TYPELIB_GUID, SOLIDWORKS_TYPELIB_GUID, ApiInterface, TypeLibraryUnavailable, choose_version, + index_enums, index_type_library, + load_constants_library, load_type_library, registered_versions, target_version, @@ -383,3 +386,83 @@ def test_imports_without_pywin32_or_winreg(import_without) -> None: ) assert attrs == {"pythoncom": None, "winreg": None} + + +class FakeEnumInfo: + """An enum's ITypeInfo: ``members`` are ``(name, value)`` pairs.""" + + def __init__(self, members: list[tuple[str, int]]) -> None: + self.members = members + + def GetTypeAttr(self) -> SimpleNamespace: + return SimpleNamespace(cFuncs=0, cVars=len(self.members)) + + def GetVarDesc(self, position: int) -> SimpleNamespace: + return SimpleNamespace(memid=100 + position, value=self.members[position][1]) + + def GetDocumentation(self, memid: int) -> tuple[Any, ...]: + return (self.members[memid - 100][0], None, 0, None) + + +class FakeConstantsLib(FakeTypeLib): + """A constants library: entries are ``(name, typekind, info, help string)``.""" + + def __init__(self, entries: list[tuple[str, int, Any, str | None]]) -> None: + super().__init__([(n, k, i) for n, k, i, _ in entries]) + self.help = [h for *_, h in entries] + + def GetDocumentation(self, position: int) -> tuple[Any, ...]: + return (self.entries[position][0], self.help[position], 0, None) + + +def test_index_enums_reads_each_member_and_value() -> None: + lib = FakeConstantsLib( + [ + ( + "swUnitSystem_e", + 0, + FakeEnumInfo([("swUnitSystem_CGS", 1), ("swUnitSystem_IPS", 3)]), + None, + ), + ("swLengthUnit_e", 0, FakeEnumInfo([("swMM", 0)]), "Length units"), + ("IThing", 4, FakeTypeInfo("IThing"), None), + ] + ) + + enums = index_enums(lib) + + assert list(enums) == ["swUnitSystem_e", "swLengthUnit_e"] + assert [(m.name, m.value) for m in enums["swUnitSystem_e"].members] == [ + ("swUnitSystem_CGS", 1), + ("swUnitSystem_IPS", 3), + ] + assert enums["swUnitSystem_e"].description is None + assert enums["swLengthUnit_e"].description == "Length units" + + +def test_load_constants_library_reads_its_own_guid_at_that_version() -> None: + com = FakeCom() + + assert load_constants_library(34, 0, com=com) == "the library" + assert com.loaded == [(CONSTANTS_TYPELIB_GUID, 34, 0)] + + +def test_a_constants_library_that_wont_load_says_so() -> None: + with pytest.raises(TypeLibraryUnavailable) as raised: + load_constants_library(34, 0, com=FakeCom(missing_file=True)) + + assert str(raised.value) == ( + "SolidWorks 2026's constants type library (swconst.tlb) couldn't be " + "loaded (Error loading type library/DLL.), so the index has no enum values." + ) + + +def test_load_constants_library_without_pywin32( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import solidworks_mcp.tools.type_library as module + + monkeypatch.setattr(module, "pythoncom", None) + + with pytest.raises(TypeLibraryUnavailable, match="needs Windows with pywin32"): + load_constants_library(34, 0) diff --git a/uv.lock b/uv.lock index 94ad5824..3697000f 100644 --- a/uv.lock +++ b/uv.lock @@ -3422,10 +3422,13 @@ dev = [ { name = "pytest-mock" }, { name = "pytest-timeout" }, { name = "pytest-xdist" }, + { name = "pyyaml" }, { name = "ruff" }, { name = "sphinx" }, { name = "sphinx-autodoc-typehints" }, { name = "tox" }, + { name = "types-defusedxml" }, + { name = "types-pyyaml" }, ] docs = [ { name = "mike" }, @@ -3459,6 +3462,7 @@ test = [ { name = "pytest-mock" }, { name = "pytest-timeout" }, { name = "pytest-xdist" }, + { name = "pyyaml" }, ] ui = [ { name = "fastapi" }, @@ -3533,6 +3537,8 @@ requires-dist = [ { name = "python-dotenv", specifier = ">=1.0.0" }, { name = "pywin32", marker = "sys_platform == 'win32'", specifier = ">=306" }, { name = "pywin32-ctypes", marker = "sys_platform == 'win32'", specifier = ">=0.2.0" }, + { name = "pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, + { name = "pyyaml", marker = "extra == 'test'", specifier = ">=6.0" }, { name = "rich", specifier = ">=13.0.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" }, { name = "scikit-image", marker = "extra == 'vision'", specifier = ">=0.23.0" }, @@ -3543,6 +3549,8 @@ requires-dist = [ { name = "sqlmodel", specifier = ">=0.0.22" }, { name = "tox", marker = "extra == 'dev'", specifier = ">=4.11.0" }, { name = "typer", specifier = ">=0.12.0" }, + { name = "types-defusedxml", marker = "extra == 'dev'", specifier = ">=0.7" }, + { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "typing-extensions", specifier = ">=4.8.0" }, { name = "urllib3", specifier = ">=2.7.0" }, { name = "uvicorn", specifier = ">=0.24.0" }, @@ -4015,6 +4023,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/3d/cc08d3cb257764101c71c47f18e2f547782d013928edc877f155cb99229d/typer-0.29.0-py3-none-any.whl", hash = "sha256:b3c3de6e06a848274dc7bd56a433499e9cf25fa1d40aa3ba4eccfec4e1624c7b", size = 121058, upload-time = "2026-11-09T18:48:11.665Z" }, ] +[[package]] +name = "types-defusedxml" +version = "0.7.0.20260504" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/d2/4553c8fa9cdebfe1e84b950cf790a4d2376a97fa016e43f7c65323fa6c7d/types_defusedxml-0.7.0.20260504.tar.gz", hash = "sha256:2ab2828a3f97111ba1c16cee273ad4124a831fc9198c41bf8368ff6ea48ad300", size = 10729, upload-time = "2026-05-04T05:22:50.192Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/2d/8a4b5ba1d732b8bc691f0efbb1c6f77cb5f6f473b2afe181d83d910773c5/types_defusedxml-0.7.0.20260504-py3-none-any.whl", hash = "sha256:a959e3a0a43b93e464bd625d91ec9193a2703ddc10443bdd627792485fae0b10", size = 13467, upload-time = "2026-05-04T05:22:49.319Z" }, +] + +[[package]] +name = "types-pyyaml" +version = "6.0.12.20261113" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/8b/ba599d956693dbc98e170f32097128bdea0a17f9d42b0b490fa749c12b1a/types_pyyaml-6.0.12.20261113.tar.gz", hash = "sha256:0828be2580fd94151182364f4d0158e4de62fdbeeb8d4296f7f7d2b6c22bb640", size = 19017, upload-time = "2026-11-13T08:51:21.488Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/2e/36fc0941a40ef066dbc8abac41bbbefb41389f547c779aef832aea6b873d/types_pyyaml-6.0.12.20261113-py3-none-any.whl", hash = "sha256:3600749e613748afdc4327f0b17c3296cf880cdbc7335f320007abd9dd815f67", size = 21321, upload-time = "2026-11-13T08:51:20.417Z" }, +] + [[package]] name = "typing-extensions" version = "4.16.0"
InterfaceMethods calledOfCalled
ISldWorks22330
6.7%ActivateDoc3, CloseDoc, Frame, GetConfigurationNames, GetCurrentLanguage, GetDocuments, GetExecutablePath, GetExportFileData, GetMassProperties, GetMathUtility, GetOpenDocumentByName, GetUserPreferenceStringValue, GetUserPreferenceToggle, NewAssembly, NewDocument, NewDrawing2, NewPart, OpenDoc6, RevisionNumber, RunMacro2, SetUserPreferenceIntegerValue, SetUserPreferenceToggle
ISldWorks23330
7.0%ActivateDoc3, CloseDoc, Frame, GetConfigurationNames, GetCurrentLanguage, GetDocuments, GetExecutablePath, GetExportFileData, GetMassProperties, GetMathUtility, GetOpenDocumentByName, GetProcessID, GetUserPreferenceStringValue, GetUserPreferenceToggle, NewAssembly, NewDocument, NewDrawing2, NewPart, OpenDoc6, RevisionNumber, RunMacro2, SetUserPreferenceIntegerValue, SetUserPreferenceToggle
IModelDoc279758
10.4%AddConfiguration2, AddDiameterDimension2, AddDimension, AddDimension2, AddHorizontalDimension2, AddRadialDimension2, AddRelation, AddVerticalDimension2, ClearSelection2, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, CreatePoint, DeleteConfiguration2, EditDelete, EditRebuild3, EditSketch, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertFeatureShell, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertRib, InsertSketch, InsertSketchForEdgeFlange, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetBendState, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowConfiguration2, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, SketchUseEdge, ViewZoomtofit, ViewZoomtofit2
IModelDocExtension18337
5.3%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetMassProperties, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, SaveAs, SaveAs2, SaveAs3, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
IPartDoc12167
7.2%ExportToDWG2, FeatureByName, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureRevolve2, FirstFeature, GetBodies2, GetMaterialPropertyName2, GetPartBox, InsertMirrorFeature, SetMaterialPropertyName2