diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c6682c4..3925fe14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 height edited later. Give exactly one of `plane` and `face_point`; a point in the air or on a curved face fails with `invalid_input`. +- **A `deprecated` support level** (#174). A deprecated tool still works; + its description and successful results open "Deprecated: use ``.", + it is tagged `level:deprecated`, and it is removed at the next major + release. The progress image leaves deprecated tools out of its count. +- **A verb list for tool names**, in the tool description standard: new + tools start with `create_`, `add_`, `get_`, `list_`, `set_` and the rest; + the names registered before it are listed as exceptions. +- **`get_model_info` reports the file's details**: `size_bytes`, `created` + and `modified`, read from the file on disk (null for a document never + saved). +- **`save_file` takes `overwrite`**, and checks a new `file_path` before + SolidWorks is asked: the folder exists and is writable, the extension + matches the document (.sldprt, .sldasm, .slddrw), and no file is there. + ### Fixed Found building the monitor stand demo (#206): @@ -45,6 +59,54 @@ Found building the monitor stand demo (#206): with no reference plane, and its camera turns to an isometric view after each feature (`--look` in the script). +- **`save_file` keeps a file already at `file_path`** unless `overwrite` + is on, and refuses a path with another document type's extension. Before, + it replaced the file. Saving in place (no `file_path`) is unchanged. + +### Deprecated + +Each still works until 3.0.0; use the tool named instead (#174): + +- `load_part`, `load_assembly`: use `open_model`. +- `save_part`, `save_assembly`: use `save_file` (`pack_and_go_assembly` to + copy an assembly with its referenced parts). +- `calculate_mass_properties`: use `get_mass_properties`. +- `get_file_properties`: use `get_model_info`. +- `add_drawing_view`: use `create_drawing_view`. +- `sketch_tutorial_simple_hole`: no replacement; build the hole with the + sketching and feature tools. + +### Removed + +33 tools that were registered but never implemented: every call returned +`not_supported` (#174). Clients that listed them only ever got an error. +Why each one went, and what does its job now, is in `openspec/queue.md` +("Removed tools"). + +- Analysis: `analyze_geometry`, `get_material_properties`. +- Automation: `automation_start_macro_recording`, + `automation_stop_macro_recording`, `batch_process_files`, + `create_template`, `execute_workflow`, `manage_design_table`, + `optimize_performance`. `manage_design_table` was checked live first: on + SolidWorks 2026 the design table is inserted, but SolidWorks can't open it + in Excel to read it and makes no configurations from it. +- Drawing: `add_annotation`. +- Drawing analysis: `analyze_drawing_annotations`, + `analyze_drawing_comprehensive`, `analyze_drawing_dimensions`, + `analyze_drawing_views`, `check_drawing_compliance`, + `generate_drawing_report`, `validate_drawing_completeness`. +- Export: `batch_export`. +- File management: `batch_file_operations`, `convert_file_format`, + `manage_file_properties`. +- Macros: `analyze_macro`, `batch_execute_macros`, `create_macro_library`, + `optimize_macro`, `start_macro_recording`, `stop_macro_recording`. +- Sketching: `tutorial_simple_hole`. +- Templates: `apply_template`, `batch_apply_template`, `extract_template`, + `list_template_library`, `save_to_template_library`. + +The seven planned tools left are drawing tools; each names the queue item +that builds them (the drawing pack). + ## [2.0.0] - 2026-11-12 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11437e44..d01e2cdf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -78,6 +78,7 @@ When needed (credentials/SolidWorks environment available): ## Adding or Changing a Tool +- Name it with a verb from the [verb list](docs/agents/tool-description-standard.md#tool-names) (`create_`, `add_`, `get_`, `list_`, `set_`, ...). - Write its docstring to the [tool description standard](docs/agents/tool-description-standard.md): what it does, when to use it, what it needs, what it changes (or "Read-only."), and what it returns. - Describe `input_data` specifically in `Args:`, and give every input field a `Field(description=...)`. - Add its title and behaviour hints to `src/solidworks_mcp/tools/tool_hints.py`; registration fails without them. diff --git a/README.md b/README.md index 1c2bb15e..a6c90fff 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ [![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 156 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. +Python MCP server for SolidWorks automation with 123 tools, plus an optional agent/prompt-testing layer for AI-assisted workflows. -[![155 MCP tools by support level, and how much of the core SolidWorks COM API they reach](docs/assets/progress/progress.svg)](https://andrewbartels1.github.io/SolidworksMCP-python/progress/) +[![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.github.io/SolidworksMCP-python/progress/) Generated from the code; click it for every tool, its level and why, filterable by level and family. @@ -33,7 +33,7 @@ Python MCP server for SolidWorks automation with 156 tools, plus an optional age await adapter.create_extrusion(ExtrusionParameters(depth=10)) ``` -- **An MCP tool server on top of it.** The same calls, exposed as 156 MCP tools, so an agent such as Claude Code can build parts, assemblies and drawings from a description. Each tool carries a support level (stable, beta, experimental or planned), so the agent knows how far to trust it. +- **An MCP tool server on top of it.** The same calls, exposed as 123 MCP tools, so an agent such as Claude Code can build parts, assemblies and drawings from a description. Each tool carries a support level (stable, beta, experimental, planned or deprecated), so the agent knows how far to trust it. ## See it work @@ -197,7 +197,7 @@ Each GIF is a live test driving SolidWorks 2026 through the MCP tools, with the - Windows + SolidWorks COM automation for the main CAD lifecycle. - Tested on SolidWorks 2026. Earlier versions may work but are untested. To check yours, run `uvx solidworks-mcp-python selftest` with SolidWorks open, then send the result with the [compatibility report form](https://github.com/andrewbartels1/SolidworksMCP-python/issues/new?template=compatibility.yml). The [compatibility page](https://andrewbartels1.github.io/SolidworksMCP-python/compatibility/) lists the releases checked so far. -- Modeling, sketching, drawing, analysis, export, automation, templates, and macro tools. +- Modeling, sketching, drawing, analysis, export, file and engineering-data tools, plus VBA generation and running macros. - Every tool's support level, and the reason a tool isn't stable yet, is on the [progress page](https://andrewbartels1.github.io/SolidworksMCP-python/progress/). ## Not Yet / Simulated @@ -302,7 +302,7 @@ Add this to `%APPDATA%\Code\User\mcp.json`: } ``` -Run **MCP: List Servers** from the Command Palette and start `solidworks`. Its output should end with `Discovered 156 tools` (the count grows as tools are added). +Run **MCP: List Servers** from the Command Palette and start `solidworks`. Its output should end with `Discovered 123 tools` (the count grows as tools are added). diff --git a/docs/agents/com-api-pitfalls.md b/docs/agents/com-api-pitfalls.md index f7211849..0d894b84 100644 --- a/docs/agents/com-api-pitfalls.md +++ b/docs/agents/com-api-pitfalls.md @@ -1095,7 +1095,7 @@ time to release memory and finish background work between documents. Heavy parts **What to do in a batch loop:** - **Throttle.** Put a real pause (~10 s worked here) between parts — after `close_model`, - before the next `load_part`. Small parts don't need it; you won't know which are heavy + before the next `open_model`. Small parts don't need it; you won't know which are heavy up front, so pace the whole loop. - **Do the heavy files last** and don't retry-storm — if a big part fails its export, record it and move on rather than reopening it immediately. diff --git a/docs/agents/prompting-tutorials.md b/docs/agents/prompting-tutorials.md index 0a579f82..aa10b4c7 100644 --- a/docs/agents/prompting-tutorials.md +++ b/docs/agents/prompting-tutorials.md @@ -400,8 +400,8 @@ Check the mass, volume, and centre of gravity for the currently open model. ```json [ - {"tool": "calculate_mass_properties", "args": {}}, - {"tool": "get_material_properties", "args": {}} + {"tool": "get_mass_properties", "args": {}}, + {"tool": "get_material", "args": {}} ] ``` @@ -444,4 +444,4 @@ You are an expert SolidWorks drafter operating a SolidWorks MCP server. | Revolve fails | No axis / wrong axis name | Add centerline in same sketch, name = `"Line1"` | | Dimension not found | Name mismatch | Check `"D1@FeatureName"` format | | Export writes 0-byte file | No active document | Open or create a part first | -| Mass = 0 | No material assigned | Call `get_material_properties` to check | +| Mass = 0 | No material assigned | Call `get_material` to check, then `set_material` | diff --git a/docs/agents/sample-models-guide.md b/docs/agents/sample-models-guide.md index f2729639..aecb4f14 100644 --- a/docs/agents/sample-models-guide.md +++ b/docs/agents/sample-models-guide.md @@ -45,7 +45,7 @@ flowchart LR | **1 – Simple** | Single sketch + one feature | `create_sketch`, `add_rectangle/circle`, `create_extrusion/revolve` | | **2 – Intermediate** | 2–4 sketches, multiple features, fillets | + `set_dimension`, `add_sketch_constraint`, `create_extrusion` (multi-step) | | **3 – Advanced** | Lofts, sweeps, multi-body, sheet metal | + `generate_vba_part_modeling`, `execute_macro` | -| **4 – Assembly** | Multiple parts mated together | `create_assembly`, `load_part`, `generate_vba_assembly_insert` | +| **4 – Assembly** | Multiple parts mated together | `create_assembly`, `insert_component`, `add_mate` | --- @@ -244,12 +244,12 @@ Create a simple sheet metal bracket: **Files**: 20+ parts in `Sprinkler/` -The sprinkler is the most complex assembly in the sample set. Use `batch_file_operations` to collect all part paths, then `load_assembly`. +The sprinkler is the most complex assembly in the sample set. Open it with `open_model`; `list_components` lists its parts. ``` -1. load_assembly file_path="Sprinkler\Sprinkler.SLDASM" -2. get_file_properties ← read material, revision, descriptions -3. calculate_mass_properties ← total assembly mass +1. open_model file_path="Sprinkler\Sprinkler.SLDASM" +2. get_custom_properties ← read material, revision, descriptions +3. get_mass_properties ← total assembly mass 4. check_interference ← verify no clashes between components 5. export_step file_path="Sprinkler_export.step" ``` diff --git a/docs/agents/tool-description-standard.md b/docs/agents/tool-description-standard.md index ab295a3c..8e0a33a5 100644 --- a/docs/agents/tool-description-standard.md +++ b/docs/agents/tool-description-standard.md @@ -69,8 +69,8 @@ Some tools have no adapter implementation, so every call returns sentence: "Not available yet: no adapter implements it, so every call returns an error with `error_type: "not_supported"`. It is planned for a future release." Then point to the tool to use instead, if there is one, and -phrase what it would change or return as "once available". The list of these -tools is in `openspec/queue.md`. +phrase what it would change or return as "once available". Its support-level +reason names the queue item in `openspec/queue.md` that builds it. ## Support levels @@ -78,18 +78,70 @@ Add one line to `SUPPORT_LEVELS` in `tools/support_levels.py` for every new tool; registration fails without it. A tool is `stable` once a live test calls it and it has no known fault, `beta` when it works on SolidWorks but has a known fault or covers only part of its COM call, `experimental` when -no live test has checked it, and `planned` when nothing implements it (its -description says "Not available yet"). Below stable, give a one-sentence -reason. - -Don't write the level into the docstring: the server opens a beta or -experimental tool's description with "Beta: " or "Experimental: -" from the table, adds the same sentence to its successful results as -`warning`, and tags every tool `level:`. After changing a level, run +no live test has checked it, `planned` when nothing implements it (its +description says "Not available yet"), and `deprecated` when another tool +replaces it. Below stable, give a one-sentence reason. + +A tool is deprecated, not removed, when it works and a client may call it. +Its entry is `_deprecated("")` (or `_deprecated(None)` when +there is none), which records the version; it keeps working until the next +major release, when `tests/integration/test_support_levels.py` fails until +it is removed. Before deprecating a tool, make sure its replacement accepts +everything it did, or that its description names the tool that does the +rest. + +Don't write the level into the docstring: the server opens a beta, +experimental or deprecated tool's description with "Beta: ", +"Experimental: " or "Deprecated: use ``." from the table, adds +the same sentence to its successful results as `warning`, and tags every tool +`level:`. After changing a level, run `python -m solidworks_mcp.progress.generate` so the README image and the [progress page](../progress.md) follow; `tests/integration/test_support_levels.py` and `test_progress_up_to_date.py` check both. +## Tool names + +A tool's name starts with one verb from this list, so an agent can guess a +name and tell two tools apart by name alone. Pick the verb by meaning: + +| Verb | Meaning | +| --- | --- | +| `create_` | makes a new document, or a new feature built from a sketch or acting on the whole body (extrusion, rib, hole, shell) | +| `add_` | adds an entity to an open sketch or a drawing, or treats edges or faces of an existing body (fillet, chamfer, draft, thread) | +| `pattern_`, `mirror_` | repeats existing features | +| `sketch_` | an operation on the open sketch's entities (offset, mirror, pattern, convert) | +| `get_` | reads one thing | +| `list_` | reads a collection | +| `set_` | changes one value | +| `open_`, `save_`, `close_`, `export_` | file operations | +| `check_`, `verify_`, `measure_`, `compare_` | read-only checks | + +`tests/integration/test_tool_descriptions.py` fails on any other name, except +these, which were registered before the list and are kept so that clients +don't break: + + +- `activate_document`, `arrange_dimensions`, `auto_center_marks`, + `auto_dimension_view`, `calculate_mass_properties`, `classify_feature_tree`, + `delete_feature`, `discover_solidworks_docs`, `execute_macro`, `exit_sketch`, + `find_related_api_members` +- `generate_drawing_package`, `generate_vba_assembly_insert`, + `generate_vba_assembly_mates`, `generate_vba_batch_export`, + `generate_vba_code`, `generate_vba_drawing_dimensions`, + `generate_vba_drawing_views`, `generate_vba_extrusion`, + `generate_vba_file_operations`, `generate_vba_macro_recorder`, + `generate_vba_part_modeling`, `generate_vba_revolve` +- `insert_bom_table`, `insert_component`, `insert_model_dimensions`, + `load_assembly`, `load_part`, `lookup_api_interface`, `lookup_api_method`, + `pack_and_go_assembly`, `rebuild_model`, + `rename_feature`, `reset_circuit_breaker` +- `search_solidworks_api_help`, `select_face_edges`, `select_feature`, + `suppress_feature`, `undo`, `update_sheet_format`, `update_title_block` + + +Don't add to the exceptions; name a new tool with a listed verb. When a +deprecated exception is removed, take it off the list too. + ## Behaviour hints Add one line to `TOOL_HINTS` in `tools/tool_hints.py` for every new tool; diff --git a/docs/assets/demos/monitor-stand/test_monitor_stand_from_prompt_to_part.gif b/docs/assets/demos/monitor-stand/test_monitor_stand_from_prompt_to_part.gif new file mode 100644 index 00000000..f1be128b Binary files /dev/null and b/docs/assets/demos/monitor-stand/test_monitor_stand_from_prompt_to_part.gif differ diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index 9b125dbd..7de777ad 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -1,11 +1,12 @@ { "tools": { - "total": 156, + "total": 123, "by_level": { - "stable": 116, + "stable": 108, "beta": 0, "experimental": 0, - "planned": 40 + "planned": 7, + "deprecated": 8 }, "list": [ { @@ -15,13 +16,6 @@ "reason": "", "summary": "Make an already-open document the active one, so the next tools act on it." }, - { - "name": "add_annotation", - "family": "drawing", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Add an annotation (a note, balloon or surface-finish symbol) to the active drawing." - }, { "name": "add_arc", "family": "sketching", @@ -61,14 +55,14 @@ "name": "add_dimension", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Add one dimension between drawing entities at a position on the sheet." }, { "name": "add_drawing_view", "family": "drawing", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `create_drawing_view`.", "summary": "Place one named view of a part or assembly on the active drawing sheet; the same as `create_drawing_view`." }, { @@ -148,55 +142,6 @@ "reason": "", "summary": "Draw a smooth spline through a list of points in the open sketch, in mm." }, - { - "name": "analyze_drawing_annotations", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Check a drawing's notes, symbols and text styles for consistency." - }, - { - "name": "analyze_drawing_comprehensive", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Run every drawing check (dimensions, views, annotations, standards) on a drawing file in one call." - }, - { - "name": "analyze_drawing_dimensions", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Check a drawing's dimensions for consistent precision, tolerance formatting and completeness." - }, - { - "name": "analyze_drawing_views", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Check how a drawing's views are chosen and laid out." - }, - { - "name": "analyze_geometry", - "family": "analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Run a geometry analysis on the active model, such as curvature, draft or wall thickness." - }, - { - "name": "analyze_macro", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Analyse a macro's structure, dependencies and complexity, and suggest optimisations." - }, - { - "name": "apply_template", - "family": "template_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Apply a saved template's properties, dimensions and materials to a model." - }, { "name": "arrange_dimensions", "family": "drawing_automation", @@ -215,77 +160,21 @@ "name": "auto_dimension_view", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Dimension a drawing view automatically with SolidWorks' auto-dimension scheme." }, - { - "name": "automation_start_macro_recording", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Start SolidWorks' macro recorder (the automation family's copy of `start_macro_recording`)." - }, - { - "name": "automation_stop_macro_recording", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Stop a macro recording and save it (the automation family's copy of `stop_macro_recording`)." - }, - { - "name": "batch_apply_template", - "family": "template_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Apply one template to every matching model in a folder." - }, - { - "name": "batch_execute_macros", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Run several macros in sequence against the files in a folder." - }, - { - "name": "batch_export", - "family": "export", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Export every matching SolidWorks file in a folder to one format." - }, - { - "name": "batch_file_operations", - "family": "file_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Copy, move, rename or delete SolidWorks files on disk in one call." - }, - { - "name": "batch_process_files", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Run one operation (rebuild, save as, export or property update) on every matching file in a folder." - }, { "name": "calculate_mass_properties", "family": "analysis", - "level": "stable", - "reason": "", - "summary": "Measure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia." - }, - { - "name": "check_drawing_compliance", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Check a drawing's title block and sheet format against a drafting standard (ISO, ANSI or DIN)." + "level": "deprecated", + "reason": "use `get_mass_properties`.", + "summary": "Measure the active part or assembly's mass properties (the old name of `get_mass_properties`)." }, { "name": "check_drawing_standards", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Check the active drawing against a drafting standard and score it." }, { @@ -330,13 +219,6 @@ "reason": "", "summary": "Compare two template files on disk: whether they are byte-identical, and how their sizes differ." }, - { - "name": "convert_file_format", - "family": "file_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Convert a SolidWorks file on disk to another format without opening it first." - }, { "name": "create_assembly", "family": "modeling", @@ -362,7 +244,7 @@ "name": "create_detail_view", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Magnify a circular area of a drawing view as a detail view." }, { @@ -393,13 +275,6 @@ "reason": "", "summary": "Loft a solid through two or more closed profile sketches, in order (Insert > Boss/Base > Loft)." }, - { - "name": "create_macro_library", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Set up a shared folder of categorised, documented macros." - }, { "name": "create_part", "family": "modeling", @@ -432,7 +307,7 @@ "name": "create_section_view", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Cut a section view along a line across a drawing view." }, { @@ -456,13 +331,6 @@ "reason": "", "summary": "Place a model's three standard views (front, top and side) on the active drawing sheet in one call." }, - { - "name": "create_template", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Create a part, assembly or drawing template file (.prtdot, .asmdot, .drwdot) with standard settings." - }, { "name": "delete_feature", "family": "modeling", @@ -484,13 +352,6 @@ "reason": "", "summary": "Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, calling its `main` procedure once." }, - { - "name": "execute_workflow", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Run a named sequence of tool steps, in order or in parallel, with an error policy." - }, { "name": "exit_sketch", "family": "sketching", @@ -547,13 +408,6 @@ "reason": "", "summary": "Export the active document to STL, like File > Save As with the STL type." }, - { - "name": "extract_template", - "family": "template_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Capture a model's settings (custom properties, dimensions, units) as a reusable template file." - }, { "name": "find_related_api_members", "family": "docs_discovery", @@ -568,13 +422,6 @@ "reason": "", "summary": "Create a complete A3 drawing of a part or assembly in one call, and save it with a PDF." }, - { - "name": "generate_drawing_report", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Write a quality report that combines every drawing check." - }, { "name": "generate_vba_assembly_insert", "family": "vba_generation", @@ -669,8 +516,8 @@ { "name": "get_file_properties", "family": "file_management", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `get_model_info`.", "summary": "Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes." }, { @@ -687,19 +534,12 @@ "reason": "", "summary": "Report the material assigned to the active part." }, - { - "name": "get_material_properties", - "family": "analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Report the physical properties of the active part's material: density, modulus, Poisson's ratio, strength." - }, { "name": "get_model_info", "family": "file_management", "level": "stable", "reason": "", - "summary": "Report the active document's title, path, type, active configuration, unsaved changes, feature count and rebuild status." + "summary": "Report the active document's title, path, type, configuration, unsaved changes, feature count, rebuild status and file details." }, { "name": "get_selected_entities", @@ -778,25 +618,18 @@ "reason": "", "summary": "List every document open in SolidWorks and say which one is active." }, - { - "name": "list_template_library", - "family": "template_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "List the templates in the shared template library." - }, { "name": "load_assembly", "family": "file_management", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `open_model`.", "summary": "Open an assembly (.sldasm) from disk and make it the active document." }, { "name": "load_part", "family": "file_management", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `open_model`.", "summary": "Open a part (.sldprt) from disk and make it the active document." }, { @@ -813,20 +646,6 @@ "reason": "", "summary": "Look up one SolidWorks API method or property: parameters, return type, description." }, - { - "name": "manage_design_table", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Create, read or update a design table (an Excel sheet that drives a model's configurations)." - }, - { - "name": "manage_file_properties", - "family": "file_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Read or change the file-level properties of a SolidWorks file on disk." - }, { "name": "measure_entities", "family": "engineering_data", @@ -848,20 +667,6 @@ "reason": "", "summary": "Open a part, assembly or drawing from disk and make it the active document." }, - { - "name": "optimize_macro", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Suggest improvements to a macro's code for speed and reliability." - }, - { - "name": "optimize_performance", - "family": "automation", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Review SolidWorks' performance settings and apply faster ones." - }, { "name": "pack_and_go_assembly", "family": "file_management", @@ -907,8 +712,8 @@ { "name": "save_assembly", "family": "file_management", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `save_file`.", "summary": "Save the active assembly in place, or as a new .sldasm, optionally copying the parts it uses alongside." }, { @@ -923,22 +728,15 @@ "family": "file_management", "level": "stable", "reason": "", - "summary": "Save the active document, to its own path or to a new path in its own format." + "summary": "Save the active part, assembly or drawing, to its own path or to a new path in its own format." }, { "name": "save_part", "family": "file_management", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "use `save_file`.", "summary": "Save the active part in place, or as a new .sldprt with the target path checked first." }, - { - "name": "save_to_template_library", - "family": "template_management", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Add a template to a shared, categorised template library." - }, { "name": "search_solidworks_api_help", "family": "docs_discovery", @@ -1033,24 +831,10 @@ { "name": "sketch_tutorial_simple_hole", "family": "sketching", - "level": "stable", - "reason": "", + "level": "deprecated", + "reason": "no replacement.", "summary": "Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch." }, - { - "name": "start_macro_recording", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Start SolidWorks' macro recorder, to capture what the user does as a macro." - }, - { - "name": "stop_macro_recording", - "family": "macro_recording", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Stop the macro recorder and save the recorded macro." - }, { "name": "suppress_feature", "family": "modeling", @@ -1058,13 +842,6 @@ "reason": "", "summary": "Suppress or unsuppress a feature of the active model; suppressed features stay in the tree but are not built." }, - { - "name": "tutorial_simple_hole", - "family": "sketching", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Draw a circle on a plane and cut it as a hole, as one worked example." - }, { "name": "undo", "family": "modeling", @@ -1076,23 +853,16 @@ "name": "update_sheet_format", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Change the active drawing's sheet format file and title-block fields." }, { "name": "update_title_block", "family": "drawing", "level": "planned", - "reason": "no adapter implements it yet.", + "reason": "planned in queue item 12 (the drawing pack).", "summary": "Fill in the active drawing's title-block fields (title, drawn by, drawing number and so on)." }, - { - "name": "validate_drawing_completeness", - "family": "drawing_analysis", - "level": "planned", - "reason": "no adapter implements it yet.", - "summary": "Check that a drawing carries everything needed to manufacture the part." - }, { "name": "verify_model", "family": "analysis", diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index 12787b25..e7c1fc11 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -21,25 +21,27 @@ -MCP tools: 156 -74% work on SolidWorks today +MCP tools: 115 +94% work on SolidWorks today - - - - - + + + + + -stable 116 +stable 108 beta 0 experimental 0 -planned 40 +planned 7 + +deprecated 8 Core SolidWorks COM API (12 interfaces) 213 of 2,838 methods · 7.5% diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index 1f4cc1a5..928c908c 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -3,14 +3,13 @@ ToolFamilyLevelWhat it does activate_documentfile_managementstableMake an already-open document the active one, so the next tools act on it. -add_annotationdrawingplanned
no adapter implements it yet.Add an annotation (a note, balloon or surface-finish symbol) to the active drawing. add_arcsketchingstableDraw a circular arc in the open sketch from its centre, start point and end point, in mm. add_centerlinesketchingstableDraw a centreline (construction line) in the open sketch, in mm. add_chamfermodelingstableBevel edges of the active part with a chamfer: `distance` along one face at `angle` (45 by default). add_circlesketchingstableDraw a circle in the open sketch from its centre and radius, in mm. add_datum_tagdrawing_automationstableAdd a datum feature symbol (A, B, C, ...) on an edge of the active drawing. -add_dimensiondrawingplanned
no adapter implements it yet.Add one dimension between drawing entities at a position on the sheet. -add_drawing_viewdrawingstablePlace one named view of a part or assembly on the active drawing sheet; the same as `create_drawing_view`. +add_dimensiondrawingplanned
planned in queue item 12 (the drawing pack).Add one dimension between drawing entities at a position on the sheet. +add_drawing_viewdrawingdeprecated
use `create_drawing_view`.Place one named view of a part or assembly on the active drawing sheet; the same as `create_drawing_view`. add_ellipsesketchingstableDraw an ellipse in the open sketch from its centre and axis lengths, in mm. add_filletmodelingstableRound edges of the active part with a constant-radius fillet. add_gtoldrawing_automationstableAdd a GD&T feature control frame to the active drawing, e.g. position Ø0.2 (M) to A|B|C. @@ -22,55 +21,36 @@ add_sketch_constraintsketchingstableAdd a geometric relation between sketch entities: horizontal, vertical, parallel, perpendicular, tangent, coincident, concentric, equal, symmetric, collinear or fix. add_sketch_dimensionsketchingstableAdd a driving dimension to sketch entities: linear, angular, radial or diameter. add_splinesketchingstableDraw a smooth spline through a list of points in the open sketch, in mm. -analyze_drawing_annotationsdrawing_analysisplanned
no adapter implements it yet.Check a drawing's notes, symbols and text styles for consistency. -analyze_drawing_comprehensivedrawing_analysisplanned
no adapter implements it yet.Run every drawing check (dimensions, views, annotations, standards) on a drawing file in one call. -analyze_drawing_dimensionsdrawing_analysisplanned
no adapter implements it yet.Check a drawing's dimensions for consistent precision, tolerance formatting and completeness. -analyze_drawing_viewsdrawing_analysisplanned
no adapter implements it yet.Check how a drawing's views are chosen and laid out. -analyze_geometryanalysisplanned
no adapter implements it yet.Run a geometry analysis on the active model, such as curvature, draft or wall thickness. -analyze_macromacro_recordingplanned
no adapter implements it yet.Analyse a macro's structure, dependencies and complexity, and suggest optimisations. -apply_templatetemplate_managementplanned
no adapter implements it yet.Apply a saved template's properties, dimensions and materials to a model. arrange_dimensionsdrawing_automationstableMove drawing dimensions out of their views into tidy rows so nothing overlaps, then check the sheet. auto_center_marksdrawingstableInsert centre marks on the holes, slots and (optionally) fillets of one drawing view. -auto_dimension_viewdrawingplanned
no adapter implements it yet.Dimension a drawing view automatically with SolidWorks' auto-dimension scheme. -automation_start_macro_recordingautomationplanned
no adapter implements it yet.Start SolidWorks' macro recorder (the automation family's copy of `start_macro_recording`). -automation_stop_macro_recordingautomationplanned
no adapter implements it yet.Stop a macro recording and save it (the automation family's copy of `stop_macro_recording`). -batch_apply_templatetemplate_managementplanned
no adapter implements it yet.Apply one template to every matching model in a folder. -batch_execute_macrosmacro_recordingplanned
no adapter implements it yet.Run several macros in sequence against the files in a folder. -batch_exportexportplanned
no adapter implements it yet.Export every matching SolidWorks file in a folder to one format. -batch_file_operationsfile_managementplanned
no adapter implements it yet.Copy, move, rename or delete SolidWorks files on disk in one call. -batch_process_filesautomationplanned
no adapter implements it yet.Run one operation (rebuild, save as, export or property update) on every matching file in a folder. -calculate_mass_propertiesanalysisstableMeasure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. -check_drawing_compliancedrawing_analysisplanned
no adapter implements it yet.Check a drawing's title block and sheet format against a drafting standard (ISO, ANSI or DIN). -check_drawing_standardsdrawingplanned
no adapter implements it yet.Check the active drawing against a drafting standard and score it. +auto_dimension_viewdrawingplanned
planned in queue item 12 (the drawing pack).Dimension a drawing view automatically with SolidWorks' auto-dimension scheme. +calculate_mass_propertiesanalysisdeprecated
use `get_mass_properties`.Measure the active part or assembly's mass properties (the old name of `get_mass_properties`). +check_drawing_standardsdrawingplanned
planned in queue item 12 (the drawing pack).Check the active drawing against a drafting standard and score it. check_interferenceanalysisstableFind where the components of the active assembly overlap (Tools > Interference Detection). check_sketch_fully_definedsketchingstableCheck whether a sketch is fully defined, under-defined or over-defined. classify_feature_treefile_managementstableClassify the active model's kind (part, sheet metal, assembly, drawing and so on) from its feature tree, and suggest how to work on it. close_modelmodelingstableClose the active document, saving it first only if asked. compare_drawing_versionsdrawing_analysisstableCompare two drawing files on disk: whether they are byte-identical, and how their sizes differ. compare_templatestemplate_managementstableCompare two template files on disk: whether they are byte-identical, and how their sizes differ. -convert_file_formatfile_managementplanned
no adapter implements it yet.Convert a SolidWorks file on disk to another format without opening it first. create_assemblymodelingstableCreate a new, empty assembly document and make it active, ready for `insert_component`. create_axismodelingstableAdd a reference axis along the model's x, y or z direction, through the origin. create_cut_extrudemodelingstableCut material from the active part with a closed sketch profile: holes, slots, windows. -create_detail_viewdrawingplanned
no adapter implements it yet.Magnify a circular area of a drawing view as a detail view. +create_detail_viewdrawingplanned
planned in queue item 12 (the drawing pack).Magnify a circular area of a drawing view as a detail view. create_drawingmodelingstableCreate a new, empty drawing document and make it active. create_drawing_viewdrawingstablePlace one named view of a part or assembly on the active drawing sheet. create_extrusionmodelingstableExtrude the sketch you just closed into a solid boss, added to the active part. create_loftmodelingstableLoft a solid through two or more closed profile sketches, in order (Insert > Boss/Base > Loft). -create_macro_librarymacro_recordingplanned
no adapter implements it yet.Set up a shared folder of categorised, documented macros. create_partmodelingstableCreate a new, empty part document and make it active, ready for `create_sketch`. create_reference_planemodelingstableAdd a reference plane offset from, at an angle to, or on a plane or flat face. create_reference_pointmodelingstableAdd a reference point on an edge (at a distance or percentage along it) or at the centre of a face. create_revolvemodelingstableRevolve a closed sketch around an axis, adding a solid to the active part. -create_section_viewdrawingplanned
no adapter implements it yet.Cut a section view along a line across a drawing view. +create_section_viewdrawingplanned
planned in queue item 12 (the drawing pack).Cut a section view along a line across a drawing view. create_sketchsketchingstableOpen a new sketch on a plane or a flat face of the active part, ready for lines, circles and other sketch entities. create_sweepmodelingstableSweep a closed profile sketch along a path sketch to make a solid (Insert > Boss/Base > Sweep). create_technical_drawingdrawingstablePlace a model's three standard views (front, top and side) on the active drawing sheet in one call. -create_templateautomationplanned
no adapter implements it yet.Create a part, assembly or drawing template file (.prtdot, .asmdot, .drwdot) with standard settings. 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_workflowautomationplanned
no adapter implements it yet.Run a named sequence of tool steps, in order or in parallel, with an error policy. 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. @@ -79,10 +59,8 @@ export_pdfexportstableExport the active document to PDF, like File > Save As with the PDF type. export_stepexportstableExport the active document to STEP, like File > Save As with the STEP type. export_stlexportstableExport the active document to STL, like File > Save As with the STL type. -extract_templatetemplate_managementplanned
no adapter implements it yet.Capture a model's settings (custom properties, dimensions, units) as a reusable template file. find_related_api_membersdocs_discoverystableFind SolidWorks API members related to an interface or member name. generate_drawing_packagedrawing_automationstableCreate a complete A3 drawing of a part or assembly in one call, and save it with a PDF. -generate_drawing_reportdrawing_analysisplanned
no adapter implements it yet.Write a quality report that combines every drawing check. generate_vba_assembly_insertvba_generationstableWrite a VBA macro that inserts a component into the active assembly at a point. generate_vba_assembly_matesvba_generationstableWrite a VBA macro that adds a concentric, distance, parallel, perpendicular or coincident mate between two selected faces or edges. generate_vba_batch_exportvba_generationstableWrite a VBA macro that opens every matching file in a folder and saves a STEP copy of each to another folder. @@ -96,11 +74,10 @@ generate_vba_revolvevba_generationstableWrite a VBA macro that revolves the selected sketch, with both-direction and thin-wall options. 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_managementstableReport the active document's file details: name, path, size, dates, type, configuration and unsaved changes. +get_file_propertiesfile_managementdeprecated
use `get_model_info`.Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes. get_mass_propertiesanalysisstableMeasure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. get_materialengineering_datastableReport the material assigned to the active part. -get_material_propertiesanalysisplanned
no adapter implements it yet.Report the physical properties of the active part's material: density, modulus, Poisson's ratio, strength. -get_model_infofile_managementstableReport the active document's title, path, type, active configuration, unsaved changes, feature count and rebuild status. +get_model_infofile_managementstableReport the active document's title, path, type, configuration, unsaved changes, feature count, rebuild status and file details. get_selected_entitiesfile_managementstableDescribe the faces, edges and vertices selected in the SolidWorks window right now. insert_bom_tabledrawing_automationstableInsert a bill-of-materials table for an assembly view on the active drawing. insert_componentmodelingstableInsert a part or sub-assembly file into the active assembly at a position in mm. @@ -112,29 +89,23 @@ list_featuresfile_managementstableList the feature tree of the active part or assembly, in order. list_model_dimensionsengineering_datastableList every dimension in the active part or assembly with its full name and value. list_open_documentsfile_managementstableList every document open in SolidWorks and say which one is active. -list_template_librarytemplate_managementplanned
no adapter implements it yet.List the templates in the shared template library. -load_assemblyfile_managementstableOpen an assembly (.sldasm) from disk and make it the active document. -load_partfile_managementstableOpen a part (.sldprt) from disk and make it the active document. +load_assemblyfile_managementdeprecated
use `open_model`.Open an assembly (.sldasm) from disk and make it the active document. +load_partfile_managementdeprecated
use `open_model`.Open a part (.sldprt) from disk and make it the active document. lookup_api_interfacedocs_discoverystableList every method and property of a SolidWorks COM interface. lookup_api_methoddocs_discoverystableLook up one SolidWorks API method or property: parameters, return type, description. -manage_design_tableautomationplanned
no adapter implements it yet.Create, read or update a design table (an Excel sheet that drives a model's configurations). -manage_file_propertiesfile_managementplanned
no adapter implements it yet.Read or change the file-level properties of a SolidWorks file on disk. measure_entitiesengineering_datastableMeasure faces, edges or vertices of the active model with SolidWorks' Measure tool. mirror_featuremodelingstableMirror solid bodies or features of the active part about a plane. open_modelmodelingstableOpen a part, assembly or drawing from disk and make it the active document. -optimize_macromacro_recordingplanned
no adapter implements it yet.Suggest improvements to a macro's code for speed and reliability. -optimize_performanceautomationplanned
no adapter implements it yet.Review SolidWorks' performance settings and apply faster ones. pack_and_go_assemblyfile_managementstableCopy an assembly and every file it uses into one folder that opens on its own. pattern_circularmodelingstableRepeat features of the active part around an axis, e.g. a ring of bosses or ribs. rebuild_modelmodelingstableRebuild the active model and report each feature that fails, with the reason and a fix. rename_featuremodelingstableRename a feature in the active model's feature tree. reset_circuit_breakerserver_adminstableLet calls through again to operations the server paused after repeated failures. save_asfile_managementstableSave the active document under a new path, as a SolidWorks file or in an exchange format such as STEP or IGES. -save_assemblyfile_managementstableSave the active assembly in place, or as a new .sldasm, optionally copying the parts it uses alongside. +save_assemblyfile_managementdeprecated
use `save_file`.Save the active assembly in place, or as a new .sldasm, optionally copying the parts it uses alongside. save_body_as_partfile_managementstableSave one solid body of the active multibody part as a new part file (Insert > Features > Save Bodies). -save_filefile_managementstableSave the active document, to its own path or to a new path in its own format. -save_partfile_managementstableSave the active part in place, or as a new .sldprt with the target path checked first. -save_to_template_librarytemplate_managementplanned
no adapter implements it yet.Add a template to a shared, categorised template library. +save_filefile_managementstableSave the active part, assembly or drawing, to its own path or to a new path in its own format. +save_partfile_managementdeprecated
use `save_file`.Save the active part in place, or as a new .sldprt with the target path checked first. search_solidworks_api_helpdocs_discoverystableSearch SolidWorks API interface and member names by keyword. select_face_edgesmodelingstableSelect every edge of one face of the active part, ready for `add_fillet` or `add_chamfer` with no edge names. select_featuremodelingstableSelect a feature, sketch, plane or component by name in the active document. @@ -148,15 +119,11 @@ sketch_linear_patternsketchingstableRepeat sketch entities in a straight line at a fixed spacing. sketch_mirrorsketchingstableMirror sketch entities about a centreline in the open sketch. sketch_offsetsketchingstableOffset sketch entities by a distance in mm, outward or inward, e.g. for a wall or a clearance. -sketch_tutorial_simple_holesketchingstableDemonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch. -start_macro_recordingmacro_recordingplanned
no adapter implements it yet.Start SolidWorks' macro recorder, to capture what the user does as a macro. -stop_macro_recordingmacro_recordingplanned
no adapter implements it yet.Stop the macro recorder and save the recorded macro. +sketch_tutorial_simple_holesketchingdeprecated
no replacement.Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch. suppress_featuremodelingstableSuppress or unsuppress a feature of the active model; suppressed features stay in the tree but are not built. -tutorial_simple_holesketchingplanned
no adapter implements it yet.Draw a circle on a plane and cut it as a hole, as one worked example. undomodelingstableUndo the last operations in the active model (Edit > Undo). -update_sheet_formatdrawingplanned
no adapter implements it yet.Change the active drawing's sheet format file and title-block fields. -update_title_blockdrawingplanned
no adapter implements it yet.Fill in the active drawing's title-block fields (title, drawn by, drawing number and so on). -validate_drawing_completenessdrawing_analysisplanned
no adapter implements it yet.Check that a drawing carries everything needed to manufacture the part. +update_sheet_formatdrawingplanned
planned in queue item 12 (the drawing pack).Change the active drawing's sheet format file and title-block fields. +update_title_blockdrawingplanned
planned in queue item 12 (the drawing pack).Fill in the active drawing's title-block fields (title, drawn by, drawing number and so on). verify_modelanalysisstableCheck the active part or assembly against what you meant to build, one pass/fail check per expected value. diff --git a/docs/demos.md b/docs/demos.md index 3702a498..b14522ed 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -220,11 +220,11 @@ what it can't decide alone: the back of the stand and where to save. `add_rectangle`, `exit_sketch` and `create_cut_extrude` `ThroughAllBoth`. 4. **Arches**: one `add_fillet` R25 on six edges. -5. **Check and save**: `rebuild_model`, `verify_model`, `save_part`. +5. **Check and save**: `rebuild_model`, `verify_model`, `save_file`. 6. **Pocket** (the follow-up): `list_open_documents` (the stand is still the active part), `create_reference_plane`, then `create_sketch`, `add_rectangle`, `exit_sketch`, `create_cut_extrude` 3 mm, and - `rebuild_model`, `verify_model`, `save_part` again. + `rebuild_model`, `verify_model`, `save_file` again. ??? info "All 28 calls with their arguments" @@ -247,7 +247,7 @@ what it can't decide alone: the back of the stand and where to save. | 15 | `add_fillet` | `{"radius": 25, "edge_names": ["0.056855,0.040,0.075", "-0.056855,0.040,0.075", "0.076855,0.040,0.055", "-0.076855,0.040,0.055", "0.076855,0.040,-0.055", "-0.076855,0.040,-0.055"]}` | | 16 | `rebuild_model` | `{}` | | 17 | `verify_model` | `{"bounding_box_mm": [193.71, 55, 190], "volume_mm3": 840264, "solid_body_count": 1, "feature_count": 4, "relative_tolerance": 0.005}` | - | 18 | `save_part` | `{"file_path": "MonitorStand.SLDPRT"}` | + | 18 | `save_file` | `{"file_path": "MonitorStand.SLDPRT"}` | | 19 | `list_open_documents` | `{}` | | 20 | `create_reference_plane` | `{"reference": "Top Plane", "offset": 55}` | | 21 | `create_sketch` | `{"plane": "Plane1"}` | @@ -256,7 +256,7 @@ what it can't decide alone: the back of the stand and where to save. | 24 | `create_cut_extrude` | `{"sketch_name": "Sketch4", "depth": 3, "end_condition": "Blind"}` | | 25 | `rebuild_model` | `{}` | | 26 | `verify_model` | `{"bounding_box_mm": [193.71, 55, 190], "volume_mm3": 752592.9, "solid_body_count": 1, "relative_tolerance": 0.001}` | - | 27 | `save_part` | `{}` | + | 27 | `save_file` | `{}` | | 28 | `verify_model` | `{"feature_count": 6}` | The fillet's edges are midpoints in metres; the other lengths are mm. diff --git a/docs/getting-started/tutorials/wave3-reference-geometry-and-drawings.md b/docs/getting-started/tutorials/wave3-reference-geometry-and-drawings.md index 944c12e6..d1bfb0dc 100644 --- a/docs/getting-started/tutorials/wave3-reference-geometry-and-drawings.md +++ b/docs/getting-started/tutorials/wave3-reference-geometry-and-drawings.md @@ -170,7 +170,7 @@ through hole. Then save it to C:\Temp\wave3_demo\plate.sldprt. | 6 | `add_sketch_dimension` | `Line_2, linear, 40` | `Dimension_7` | | 7 | `add_sketch_dimension` | `entity1="Circle_5", dimension_type="diameter", value=12` | `Dimension_8` — *"Added diameter dimension of 12.0mm to Circle_5"* | | 8 | `exit_sketch` → `create_extrusion` | `depth=8` | `Boss-Extrude1` | -| 9 | `save_part` | `file_path="C:\Temp\wave3_demo\plate.sldprt"` | saved | +| 9 | `save_file` | `file_path="C:\Temp\wave3_demo\plate.sldprt"` | saved | Putting the rectangle **and** the circle in one profile means a single `create_extrusion` leaves a clean through hole — no cut feature needed. @@ -265,7 +265,7 @@ work — the only files created are under your scratch folder. | `save_body_as_part` | ✅ (also opens a linked assembly) | | `auto_center_marks` — insertion | ✅ (count read-back unreliable on R2026x) | | `add_dimension` / `auto_dimension_view` — **drawing** dimensions | ❌ not wired to COM — sketch dimensions only | -| `create_cut` / `tutorial_simple_hole` | ❌ not wired to COM on this build | +| `create_cut` | ❌ not wired to COM on this build; use `create_cut_extrude` | --- diff --git a/docs/index.md b/docs/index.md index 5d1df192..cd31cb1f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -13,7 +13,7 @@ **AI-Assisted SolidWorks Automation with MCP** -🚀 **152 Tools** | 🤖 **Agent-Ready Workflows** | ⚡ **Automatic COM/VBA Routing** | 🧪 **Schema-Validated Prompt Runs** +🚀 **123 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 -- 152 tools across modeling, sketching, drawing, engineering data, analysis, export, automation, templates, macros, and docs discovery +- 123 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 @@ -190,7 +190,7 @@ Ready to automate your SolidWorks workflows? Check out our comprehensive guides: - [**VS Code MCP Setup**](getting-started/vscode-mcp-setup.md) - Connect VS Code and GitHub Copilot to this server - [**Claude Code MCP Setup**](getting-started/claude-code-setup.md) - Connect Claude Code to this server - [**Architecture Overview**](user-guide/architecture.md) - Understand the system design -- [**Tools Overview**](user-guide/tools-overview.md) - Explore all 109 available tools +- [**Tools Overview**](user-guide/tools-overview.md) - Explore all 123 tools - [**Agent UI Workflows**](agents/agent-ui-workflows.md) - Plan visual decision workflows for hinges, sourcing, and printability - [**Agent Memory and Recovery**](agents/agent-memory-and-recovery.md) - Use local SQLite history to troubleshoot and recover from failure states diff --git a/docs/progress.md b/docs/progress.md index 441e7baa..39f4bd06 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -9,8 +9,8 @@ of date, so it moves with every tool added or fixed. ## Support levels -Every tool has one level. It's in the tool's tags (`level:beta`). A beta or -experimental tool's description opens with it, and its successful results +Every tool has one level. It's in the tool's tags (`level:beta`). A beta, +experimental or deprecated tool's description opens with it, and its successful results carry it as `warning`. | Level | Meaning | @@ -18,7 +18,8 @@ carry it as `warning`. | stable | Checked by a live test on real SolidWorks; every input used; no known fault. | | beta | Works on SolidWorks, but has a known fault or covers only part of its COM call. The reason is shown with it. | | experimental | Implemented, but not yet checked on real SolidWorks. | -| planned | Registered, but nothing implements it yet; every call returns `not_supported`. | +| planned | Registered, but nothing implements it yet; every call returns `not_supported`. The reason names the queue item that builds it. | +| deprecated | Works, but another tool replaces it. Its description and successful results say which; it is removed at the next major release. Not counted in the bar. | A fixed fault, or a new live test, moves a tool up a level: the table is `src/solidworks_mcp/tools/support_levels.py`. diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css index 53007c22..19327143 100644 --- a/docs/stylesheets/extra.css +++ b/docs/stylesheets/extra.css @@ -98,6 +98,7 @@ .level-beta { background: #d29922; } .level-experimental { background: #db6d28; } .level-planned { background: #484f58; } +.level-deprecated { background: #8957e5; } .progress-filters { margin: 0.5em 0 1em; } .progress-filter-group { margin: 0.3em 0; } .progress-chip { diff --git a/docs/user-guide/tool-catalog/analysis.md b/docs/user-guide/tool-catalog/analysis.md index c4deb124..4745f45f 100644 --- a/docs/user-guide/tool-catalog/analysis.md +++ b/docs/user-guide/tool-catalog/analysis.md @@ -1,24 +1,22 @@ # Analysis Tools Use these after a model or assembly already exists. To check a finished build in one -call, use `verify_model`. For individual readings, start with mass properties, then -interference checking, then geometry analysis, then material properties. +call, use `verify_model`. For individual readings, use `get_mass_properties` and +`check_interference`. > **Prerequisite:** An active model or assembly with solid geometry. -**Total tools in this category: 6** +**Total tools in this category: 4** ## Recommended order 1. `verify_model`: one call that checks the model against what you expected -2. `calculate_mass_properties` or `get_mass_properties` +2. `get_mass_properties` 3. `check_interference` -4. `analyze_geometry` -5. `get_material_properties` ## Known limits -- `get_mass_properties` is a compatibility alias for `calculate_mass_properties`. +- `calculate_mass_properties` is deprecated: it returns what `get_mass_properties` returns. - These tools do not create or modify geometry. - In tests and local development, the mock adapter stands in for SolidWorks COM and returns canned success/error payloads so the suite can run without a live SolidWorks @@ -29,6 +27,8 @@ interference checking, then geometry analysis, then material properties. ### `calculate_mass_properties` +> **Deprecated:** use `get_mass_properties`. It keeps working until 3.0.0, when it is removed. + Measure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. **Prerequisite:** Active model with solid geometry @@ -90,43 +90,6 @@ Find where the components of the active assembly overlap (Tools > Interference D --- -### `analyze_geometry` - -Run a geometry analysis on the active model, such as curvature, draft or wall thickness. - -**Prerequisite:** Active model with geometry - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `analysis_type` | `str` | ✅ | `` | Type of analysis (curvature, draft, thickness, etc.) | -| `parameters` | `Dict[str, Any]?` | — | `None` | Analysis-specific parameters | - -**Sample call:** - -```json -{ - "analysis_type": "curvature" -} -``` - ---- - -### `get_material_properties` - -Report the physical properties of the active part's material: density, modulus, Poisson's ratio, strength. - -**Prerequisite:** Active part with assigned material - -**Sample call:** - -```json -{} -``` - ---- - ### `verify_model` Check the active part or assembly against what you meant to build, one pass/fail check per expected value. diff --git a/docs/user-guide/tool-catalog/automation.md b/docs/user-guide/tool-catalog/automation.md index db0430ed..65b1ecd2 100644 --- a/docs/user-guide/tool-catalog/automation.md +++ b/docs/user-guide/tool-catalog/automation.md @@ -1,28 +1,17 @@ # Automation Tools -Use these when the work should be repeatable. Start with VBA generation or macro -recording, then use batch processing, design tables, workflow execution, templates, -and performance tuning as needed. +`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). -> **Prerequisite:** Varies by operation. Batch processing requires writable source and output directories. +> **Prerequisite:** None for `generate_vba_code`; it only writes text. -**Total tools in this category: 8** - -## Recommended order - -1. `generate_vba_code` for complex or repetitive operations -2. `automation_start_macro_recording` and `automation_stop_macro_recording` when capturing a manual workflow -3. `batch_process_files` for many files -4. `manage_design_table` for configuration-driven variants -5. `execute_workflow` for ordered multi-step pipelines -6. `create_template` for reusable part, assembly, or drawing templates -7. `optimize_performance` for tuning the SolidWorks environment +**Total tools in this category: 1** ## Known limits -- Mock mode simulates VBA generation and macro recording. -- Batch processing and workflow execution still depend on the configured adapter. -- These tools are for orchestration, not for direct geometry creation. +- `generate_vba_code` writes macro text; it does not run it. Run a saved `.swp` + with `execute_macro`. +- Mock mode returns the same text as real mode, since nothing calls SolidWorks. --- @@ -50,177 +39,3 @@ Write a VBA macro skeleton for an operation you describe: the SolidWorks connect "parameters": {} } ``` - ---- - -### `automation_start_macro_recording` - -Start SolidWorks' macro recorder (the automation family's copy of `start_macro_recording`). - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `macro_name` | `str?` | — | `None` | Name for the recorded macro | -| `recording_name` | `str?` | — | `None` | Recording name alias | -| `output_file` | `str?` | — | `None` | Output file alias | -| `recording_mode` | `str?` | — | `None` | Recording mode alias | -| `capture_mouse` | `bool` | — | `True` | Capture mouse actions | -| `capture_keyboard` | `bool` | — | `True` | Capture keyboard actions | -| `description` | `str` | — | `` | Description of the macro functionality | -| `auto_start` | `bool` | — | `True` | Automatically start recording | - -**Sample call:** - -```json -{} -``` - ---- - -### `automation_stop_macro_recording` - -Stop a macro recording and save it (the automation family's copy of `stop_macro_recording`). - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- - -### `batch_process_files` - -Run one operation (rebuild, save as, export or property update) on every matching file in a folder. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `source_directory` | `str` | ✅ | `` | Directory containing SolidWorks files | -| `operation_type` | `str?` | — | `None` | Type of operation (rebuild, save_as, export, update_properties) | -| `batch_operation` | `str?` | — | `None` | Batch operation alias | -| `target_format` | `str?` | — | `None` | Target format for export operations | -| `file_pattern` | `str?` | — | `None` | File pattern alias | -| `parallel_processing` | `bool` | — | `False` | Parallel processing alias | -| `operation` | `str?` | — | `None` | Operation alias | -| `recursive` | `bool` | — | `False` | Process subdirectories recursively | -| `filter_patterns` | `List[str]` | — | `['*.sldprt', '*.sldasm']` | File patterns to process | - -**Sample call:** - -```json -{ - "source_directory": "C:\\Temp\\mcp_demo" -} -``` - ---- - -### `manage_design_table` - -Create, read or update a design table (an Excel sheet that drives a model's configurations). - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `table_type` | `str?` | — | `None` | Type of design table (create, update, import) | -| `model_path` | `str?` | — | `None` | Model path alias | -| `table_file` | `str?` | — | `None` | Design table file alias | -| `operation` | `str?` | — | `None` | Operation alias | -| `auto_update` | `bool` | — | `False` | Auto update alias | -| `create_configurations` | `bool` | — | `False` | Create configurations alias | -| `auto_create_configurations` | `bool` | — | `False` | Auto-create alias | -| `excel_file` | `str?` | — | `None` | Excel file path for import/export | -| `parameters` | `List[str]` | — | `[]` | Parameters to include in design table | -| `configurations` | `List[str]` | — | `[]` | Configuration names | - -**Sample call:** - -```json -{} -``` - ---- - -### `execute_workflow` - -Run a named sequence of tool steps, in order or in parallel, with an error policy. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `workflow_name` | `str` | ✅ | `` | Name of the workflow | -| `steps` | `List[Dict[str, Any]]` | ✅ | `` | List of workflow steps | -| `parallel_execution` | `bool` | — | `False` | Execute compatible steps in parallel | -| `error_handling` | `str` | — | `stop` | Error handling strategy (stop, skip, retry) | - -**Sample call:** - -```json -{ - "workflow_name": "MCP_Demo_Part", - "steps": [] -} -``` - ---- - -### `create_template` - -Create a part, assembly or drawing template file (.prtdot, .asmdot, .drwdot) with standard settings. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `template_type` | `str` | ✅ | `` | Type of template (part, assembly, drawing) | -| `template_name` | `str` | ✅ | `` | Name for the template | -| `base_file` | `str?` | — | `None` | Base file to create template from | -| `source_model` | `str?` | — | `None` | Source model alias | -| `output_path` | `str?` | — | `None` | Output path alias | -| `include_custom_properties` | `bool` | — | `False` | Include custom properties alias | -| `include_materials` | `bool` | — | `False` | Include materials alias | -| `include_features` | `List[str]` | ✅ | `` | Include features alias | -| `metadata` | `Dict[str, Any]` | — | `{}` | Template metadata and properties | - -**Sample call:** - -```json -{ - "template_type": "example", - "template_name": "MCP_Demo_Part", - "include_features": [] -} -``` - ---- - -### `optimize_performance` - -Review SolidWorks' performance settings and apply faster ones. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- diff --git a/docs/user-guide/tool-catalog/drawing-analysis.md b/docs/user-guide/tool-catalog/drawing-analysis.md index c3983be9..eeb4d10d 100644 --- a/docs/user-guide/tool-catalog/drawing-analysis.md +++ b/docs/user-guide/tool-catalog/drawing-analysis.md @@ -1,142 +1,11 @@ # Drawing Analysis Tools -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. +Compare two versions of a drawing file on disk. A check of a drawing's contents +(`check_drawing`) is planned in the drawing pack. -> **Prerequisite:** An active Drawing document open in SolidWorks. +> **Prerequisite:** Both drawing files on disk. -**Total tools in this category: 8** - ---- - -### `analyze_drawing_comprehensive` - -Run every drawing check (dimensions, views, annotations, standards) on a drawing file in one call. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `drawing_path` | `str` | ✅ | `` | Path to drawing file (.slddrw) | -| `analysis_type` | `str` | — | `comprehensive` | Analysis type (comprehensive, dimensions, views, annotations) | -| `analysis_depth` | `str` | — | `Basic` | Analysis depth level | -| `standards_check` | `bool` | — | `True` | Check against drafting standards | -| `generate_report` | `bool` | — | `True` | Generate detailed report | - -**Sample call:** - -```json -{ - "drawing_path": "C:\\Temp\\mcp_demo\\file.sldprt" -} -``` - ---- - -### `analyze_drawing_dimensions` - -Check a drawing's dimensions for consistent precision, tolerance formatting and completeness. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `drawing_path` | `str` | ✅ | `` | Path to drawing file | -| `check_precision` | `bool` | — | `True` | Check dimension precision consistency | -| `check_tolerances` | `bool` | — | `True` | Check tolerance formatting | -| `check_completeness` | `bool` | — | `True` | Check dimension completeness | - -**Sample call:** - -```json -{ - "drawing_path": "C:\\Temp\\mcp_demo\\file.sldprt" -} -``` - ---- - -### `analyze_drawing_annotations` - -Check a drawing's notes, symbols and text styles for consistency. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `drawing_path` | `str` | ✅ | `` | Path to drawing file | -| `check_notes` | `bool` | — | `True` | Check note formatting and content | -| `check_symbols` | `bool` | — | `True` | Check symbol usage and placement | -| `check_text_styles` | `bool` | — | `True` | Check text style consistency | -| `check_annotations` | `bool` | — | `True` | Alias used by tests | - -**Sample call:** - -```json -{ - "drawing_path": "C:\\Temp\\mcp_demo\\file.sldprt" -} -``` - ---- - -### `check_drawing_compliance` - -Check a drawing's title block and sheet format against a drafting standard (ISO, ANSI or DIN). - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `drawing_path` | `str` | ✅ | `` | Path to drawing file | -| `standard` | `str` | — | `ISO` | Standard to check against (ISO, ANSI, DIN) | -| `standards_to_check` | `List[str]` | ✅ | `` | Standards list alias | -| `check_title_block` | `bool` | — | `True` | Check title block compliance | -| `check_sheet_format` | `bool` | — | `True` | Check sheet format compliance | - -**Sample call:** - -```json -{ - "drawing_path": "C:\\Temp\\mcp_demo\\file.sldprt", - "standards_to_check": [] -} -``` - ---- - -### `analyze_drawing_views` - -Check how a drawing's views are chosen and laid out. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- - -### `generate_drawing_report` - -Write a quality report that combines every drawing check. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` +**Total tools in this category: 1** --- @@ -154,16 +23,3 @@ Compare two drawing files on disk: whether they are byte-identical, and how thei --- -### `validate_drawing_completeness` - -Check that a drawing carries everything needed to manufacture the part. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- diff --git a/docs/user-guide/tool-catalog/drawing-automation.md b/docs/user-guide/tool-catalog/drawing-automation.md index 3289dc16..58693615 100644 --- a/docs/user-guide/tool-catalog/drawing-automation.md +++ b/docs/user-guide/tool-catalog/drawing-automation.md @@ -4,7 +4,7 @@ Put the model's dimensions on a drawing and lay them out so nothing overlaps, ad > **Prerequisite:** An active Drawing document with views of a model; generate_drawing_package only needs a saved part or assembly. -**Total tools in this category: 5** +**Total tools in this category: 7** --- diff --git a/docs/user-guide/tool-catalog/drawing.md b/docs/user-guide/tool-catalog/drawing.md index 5794db67..6b0df057 100644 --- a/docs/user-guide/tool-catalog/drawing.md +++ b/docs/user-guide/tool-catalog/drawing.md @@ -1,10 +1,12 @@ # Drawing Tools -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. +Create and edit 2-D technical drawings: views, notes and centre marks. Section and +detail views, drawing dimensions, the title block, the sheet format and a drawing +check are planned in the drawing pack; until then they return `not_supported`. > **Prerequisite:** An active SolidWorks Drawing (.slddrw) document. -**Total tools in this category: 14** +**Total tools in this category: 13** --- @@ -241,6 +243,8 @@ Place a model's three standard views (front, top and side) on the active drawing ### `add_drawing_view` +> **Deprecated:** use `create_drawing_view`. It keeps working until 3.0.0, when it is removed. + Place one named view of a part or assembly on the active drawing sheet; the same as `create_drawing_view`. **Prerequisite:** SolidWorks running @@ -267,40 +271,6 @@ Place one named view of a part or assembly on the active drawing sheet; the same --- -### `add_annotation` - -Add an annotation (a note, balloon or surface-finish symbol) to the active drawing. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `drawing_path` | `str?` | — | `None` | Path to drawing file | -| `annotation_type` | `str` | ✅ | `` | Type of annotation (note, balloon, surface_finish, etc.) | -| `text` | `str` | ✅ | `` | Annotation text content | -| `position_x` | `float?` | — | `None` | X position for annotation | -| `position_y` | `float?` | — | `None` | Y position for annotation | -| `position` | `List[float]?` | — | `None` | Annotation position | -| `font_size` | `float` | — | `12.0` | Font size in points | -| `leader_attachment` | `str?` | — | `None` | Entity to attach leader line to | -| `drawn_by` | `str` | — | `` | Drawn by field | -| `checked_by` | `str` | — | `` | Checked by field | -| `approved_by` | `str` | — | `` | Approved by field | -| `drawing_number` | `str` | — | `` | Drawing number | - -**Sample call:** - -```json -{ - "annotation_type": "example", - "text": "example" -} -``` - ---- - ### `update_title_block` Fill in the active drawing's title-block fields (title, drawn by, drawing number and so on). diff --git a/docs/user-guide/tool-catalog/export.md b/docs/user-guide/tool-catalog/export.md index d6b07924..fa247fe1 100644 --- a/docs/user-guide/tool-catalog/export.md +++ b/docs/user-guide/tool-catalog/export.md @@ -1,10 +1,10 @@ # Export Tools -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. +Convert SolidWorks models to industry-standard interchange and manufacturing formats: STEP, IGES, STL, PDF, DWG, and raster images. To export many files, call the export tool once per file. > **Prerequisite:** An active document or a valid file path to an existing model. -**Total tools in this category: 7** +**Total tools in this category: 6** --- @@ -163,32 +163,3 @@ Save a picture of the active model in a standard view, as PNG or JPG, at a chose --- -### `batch_export` - -Export every matching SolidWorks file in a folder to one format. - -**Prerequisite:** Writable source and output directories - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `source_directory` | `str` | ✅ | `` | Directory containing SolidWorks files | -| `output_directory` | `str` | ✅ | `` | Directory for exported files | -| `format_type` | `str?` | — | `None` | Target export format | -| `export_format` | `str?` | — | `None` | Alternative export format | -| `file_pattern` | `str?` | — | `None` | File pattern alias | -| `recursive` | `bool` | — | `False` | Search subdirectories recursively | -| `include_subdirectories` | `bool` | — | `False` | Include subdirectories in search | -| `file_patterns` | `List[str]` | — | `['*.sldprt', '*.sldasm', '*.slddrw']` | File patterns to include | - -**Sample call:** - -```json -{ - "source_directory": "C:\\Temp\\mcp_demo", - "output_directory": "C:\\Temp\\mcp_demo\\exports" -} -``` - ---- diff --git a/docs/user-guide/tool-catalog/file-management.md b/docs/user-guide/tool-catalog/file-management.md index 073feb3d..5495f5b5 100644 --- a/docs/user-guide/tool-catalog/file-management.md +++ b/docs/user-guide/tool-catalog/file-management.md @@ -1,10 +1,14 @@ # File Management Tools -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. +Open, save, switch and inspect SolidWorks documents: `open_model`, `save_file` +and `save_as`, the open documents, the feature tree, configurations, the current +selection and Pack and Go. `load_part`, `load_assembly`, `save_part`, +`save_assembly` and `get_file_properties` are deprecated; each section names its +replacement. > **Prerequisite:** SolidWorks running. File-write operations need writable output paths. -**Total tools in this category: 19** +**Total tools in this category: 16** --- @@ -55,6 +59,8 @@ Save the active document under a new path, as a SolidWorks file or in an exchang ### `get_file_properties` +> **Deprecated:** use `get_model_info`. It keeps working until 3.0.0, when it is removed. + Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes. **Prerequisite:** Active document @@ -140,95 +146,10 @@ List the names of the active model's configurations. --- -### `manage_file_properties` - -Read or change the file-level properties of a SolidWorks file on disk. - -**Prerequisite:** Active document - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `operation` | `str` | ✅ | `` | Operation to perform (copy, move, delete, rename) | -| `source_path` | `str?` | — | `None` | Source file path | -| `file_path` | `str?` | — | `None` | Alternative file path | -| `target_path` | `str?` | — | `None` | Target file path (for copy/move/rename) | -| `properties` | `Dict[str, Any]?` | — | `None` | File properties to set | -| `parameters` | `Dict[str, Any]?` | — | `None` | Operation parameters | -| `include_system` | `bool` | — | `False` | Include system properties | - -**Sample call:** - -```json -{ - "operation": "example" -} -``` - ---- - -### `convert_file_format` - -Convert a SolidWorks file on disk to another format without opening it first. - -**Prerequisite:** Valid source file path - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `source_file` | `str` | ✅ | `` | Source file path | -| `target_file` | `str?` | — | `None` | Target file path | -| `source_format` | `str?` | — | `None` | Source file format | -| `target_format` | `str` | ✅ | `` | Target file format | -| `output_path` | `str?` | — | `None` | Alternative output path | -| `conversion_options` | `Dict[str, Any]?` | — | `None` | Conversion options | -| `quality` | `str` | — | `high` | Conversion quality | -| `units` | `str` | — | `mm` | Units | -| `invalid_format` | `str?` | — | `None` | Invalid format for testing | - -**Sample call:** - -```json -{ - "source_file": "example", - "target_format": "example" -} -``` - ---- - -### `batch_file_operations` - -Copy, move, rename or delete SolidWorks files on disk in one call. - -**Prerequisite:** Writable directories - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `operation` | `str` | ✅ | `` | Operation to perform (copy, move, delete, rename) | -| `source_path` | `str?` | — | `None` | Source file path | -| `file_path` | `str?` | — | `None` | Alternative file path | -| `target_path` | `str?` | — | `None` | Target file path (for copy/move/rename) | -| `properties` | `Dict[str, Any]?` | — | `None` | File properties to set | -| `parameters` | `Dict[str, Any]?` | — | `None` | Operation parameters | -| `include_system` | `bool` | — | `False` | Include system properties | - -**Sample call:** - -```json -{ - "operation": "example" -} -``` - ---- - ### `load_part` +> **Deprecated:** use `open_model`. It keeps working until 3.0.0, when it is removed. + Open a part (.sldprt) from disk and make it the active document. **Prerequisite:** SolidWorks running, valid .sldprt path @@ -251,6 +172,8 @@ Open a part (.sldprt) from disk and make it the active document. ### `load_assembly` +> **Deprecated:** use `open_model`. It keeps working until 3.0.0, when it is removed. + Open an assembly (.sldasm) from disk and make it the active document. **Prerequisite:** SolidWorks running, valid .sldasm path @@ -273,6 +196,8 @@ Open an assembly (.sldasm) from disk and make it the active document. ### `save_part` +> **Deprecated:** use `save_file`. It keeps working until 3.0.0, when it is removed. + Save the active part in place, or as a new .sldprt with the target path checked first. **Prerequisite:** Active Part document @@ -287,6 +212,8 @@ Save the active part in place, or as a new .sldprt with the target path checked ### `save_assembly` +> **Deprecated:** use `save_file`. It keeps working until 3.0.0, when it is removed. + Save the active assembly in place, or as a new .sldasm, optionally copying the parts it uses alongside. **Prerequisite:** Active Assembly document diff --git a/docs/user-guide/tool-catalog/index.md b/docs/user-guide/tool-catalog/index.md index 6bf72231..71b86a46 100644 --- a/docs/user-guide/tool-catalog/index.md +++ b/docs/user-guide/tool-catalog/index.md @@ -1,6 +1,6 @@ -# Tool Catalog — All 152 Tools +# Tool Catalog — All 123 Tools -This reference documents all **152 MCP tools** registered by the SolidWorks MCP server. +This reference documents all **123 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) @@ -9,21 +9,25 @@ Each section covers one functional category with parameter tables and copy-paste | Category | Count | Description | |----------|-------|-------------| -| [Modeling Tools](modeling.md) | 30 | Create and manipulate SolidWorks parts, assemblies, and drawings — sketches, extrusions, revolves, dimensions, feature renaming, chamfers/fillets, and the document unit system. | -| [Sketching Tools](sketching.md) | 19 | Build 2-D sketch geometry (lines, circles, arcs, splines, polygons) and apply geometric constraints and dimensions. | -| [Drawing Tools](drawing.md) | 14 | Create and edit 2-D technical drawings: add projected, section, and detail views, place annotations, and auto-dimension layouts. | -| [Drawing Analysis Tools](drawing-analysis.md) | 8 | Quality-gate your drawings by analyzing dimensions, annotations, view coverage, standards compliance, and completeness. | -| [Drawing Automation Tools](drawing-automation.md) | 5 | Model dimensions laid out without overlaps, BOM tables, sheet scale and complete A3 drawings. | +| [Modeling Tools](modeling.md) | 31 | Parts, assemblies and drawings: extrusions, revolves, sweeps, lofts, cuts, fillets, chamfers, patterns, reference geometry, mates, dimensions, feature renaming and the document unit system. | +| [Sketching Tools](sketching.md) | 18 | 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 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. | -| [Analysis Tools](analysis.md) | 6 | Check a finished part or assembly against expected values, and extract mass, volume, center of mass, inertia, interference and material metadata. | -| [Export Tools](export.md) | 7 | Convert SolidWorks models to industry-standard interchange and manufacturing formats such as STEP, IGES, STL, DWG, PDF, and images. | -| [File Management Tools](file-management.md) | 19 | Open, save, and manage SolidWorks documents; load parts and assemblies, switch the active document, enumerate what's open, inspect model metadata, classify model families, and read the live UI selection. | -| [Automation Tools](automation.md) | 8 | Orchestrate multi-step workflows, run batch file processing, manage design tables, and tune performance settings. | -| [VBA Generation Tools](vba-generation.md) | 10 | Generate and execute VBA macro code for operations that exceed direct COM call complexity or require procedural automation. | -| [Template Management Tools](template-management.md) | 6 | Create, extract, apply, compare, and manage SolidWorks document templates in a reusable library workflow. | -| [Macro Recording Tools](macro-recording.md) | 7 | Record, replay, analyze, and optimize SolidWorks VBA macros, including macro libraries and batch execution workflows. | +| [Analysis Tools](analysis.md) | 4 | Check a finished part or assembly against expected values; mass, volume, centre of mass, inertia and interference. | +| [Export Tools](export.md) | 6 | STEP, IGES, STL, DWG, PDF and images. | +| [File Management Tools](file-management.md) | 16 | Open, save, switch and inspect documents; the feature tree, configurations and the live selection; Pack and Go. | +| [Automation Tools](automation.md) | 1 | A VBA macro skeleton for a described task. | +| [VBA Generation Tools](vba-generation.md) | 10 | VBA macro text for steps the tools don't cover. | +| [Template Management Tools](template-management.md) | 1 | Compare two template files. | +| [Macro Recording Tools](macro-recording.md) | 1 | Run a binary SolidWorks macro (`.swp`). | | [Docs Discovery Tools](docs-discovery.md) | 5 | Look up SolidWorks API interfaces and member signatures, read from the installed SolidWorks type library. | +`reset_circuit_breaker` (server admin) has no page of its own; see the +[progress page](../../progress.md). Eight tools are deprecated: each one's +section opens with "Deprecated" and names its replacement. + ## Standard Response Envelope A successful call returns at least: diff --git a/docs/user-guide/tool-catalog/macro-recording.md b/docs/user-guide/tool-catalog/macro-recording.md index 62e09c6c..db1a8369 100644 --- a/docs/user-guide/tool-catalog/macro-recording.md +++ b/docs/user-guide/tool-catalog/macro-recording.md @@ -1,56 +1,11 @@ # Macro Recording Tools -Record, replay, analyse, and optimise 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. +Run a binary SolidWorks macro (`.swp`). 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. -**Total tools in this category: 7** - ---- - -### `start_macro_recording` - -Start SolidWorks' macro recorder, to capture what the user does as a macro. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `macro_name` | `str?` | — | `None` | Name for the recorded macro | -| `recording_name` | `str?` | — | `None` | Alternative recording name | -| `description` | `str` | — | `` | Description of macro functionality | -| `output_file` | `str` | ✅ | `` | Output file for the recorded macro | -| `recording_mode` | `str` | — | `User actions` | Recording mode | -| `capture_mouse` | `bool` | — | `True` | Capture mouse actions | -| `capture_keyboard` | `bool` | — | `True` | Capture keyboard actions | -| `recording_quality` | `str` | — | `High` | Recording quality level | -| `auto_cleanup` | `bool` | — | `False` | Cleanup temporary files | -| `auto_stop` | `bool` | — | `False` | Auto-stop recording after timeout | -| `timeout_seconds` | `int` | — | `300` | Timeout for auto-stop in seconds | - -**Sample call:** - -```json -{ - "output_file": "example" -} -``` - ---- - -### `stop_macro_recording` - -Stop the macro recorder and save the recorded macro. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` +**Total tools in this category: 1** --- @@ -85,81 +40,3 @@ Run a binary SolidWorks macro (.swp, or legacy .swb) in the running SolidWorks, --- -### `analyze_macro` - -Analyse a macro's structure, dependencies and complexity, and suggest optimisations. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `macro_path` | `str?` | — | `None` | Path to macro file to analyze | -| `macro_file` | `str?` | — | `None` | Alternative macro file path | -| `analysis_type` | `str` | — | `full` | Analysis type (full, dependencies, performance) | -| `analysis_depth` | `str` | — | `Basic` | Analysis depth alias | -| `suggest_optimizations` | `bool` | — | `False` | Suggest optimizations | - -**Sample call:** - -```json -{} -``` - ---- - -### `batch_execute_macros` - -Run several macros in sequence against the files in a folder. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `macro_list` | `List[str]` | ✅ | `` | List of macro file paths | -| `target_directory` | `str?` | — | `None` | Target directory alias | -| `source_directory` | `str?` | — | `None` | Source directory alias | -| `file_pattern` | `str?` | — | `None` | File pattern alias | -| `execution_order` | `str` | — | `sequential` | Execution order (sequential, parallel) | -| `stop_on_error` | `bool` | — | `True` | Stop batch if error occurs | - -**Sample call:** - -```json -{ - "macro_list": [] -} -``` - ---- - -### `optimize_macro` - -Suggest improvements to a macro's code for speed and reliability. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- - -### `create_macro_library` - -Set up a shared folder of categorised, documented macros. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- diff --git a/docs/user-guide/tool-catalog/modeling.md b/docs/user-guide/tool-catalog/modeling.md index ded37e1a..de8fe567 100644 --- a/docs/user-guide/tool-catalog/modeling.md +++ b/docs/user-guide/tool-catalog/modeling.md @@ -4,7 +4,7 @@ Create and manipulate SolidWorks parts, assemblies, and drawings. These are the > **Prerequisite:** An active SolidWorks session. Most feature tools require an open Part document. -**Total tools in this category: 12** +**Total tools in this category: 31** ## Measured change diff --git a/docs/user-guide/tool-catalog/sketching.md b/docs/user-guide/tool-catalog/sketching.md index 4d8d8f0a..6edb8607 100644 --- a/docs/user-guide/tool-catalog/sketching.md +++ b/docs/user-guide/tool-catalog/sketching.md @@ -449,6 +449,8 @@ Offset sketch entities by a distance in mm, outward or inward, e.g. for a wall o ### `sketch_tutorial_simple_hole` +> **Deprecated:** no replacement; build the hole with the sketching and feature tools. It keeps working until 3.0.0, when it is removed. + Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane and close the sketch. **Prerequisite:** SolidWorks running @@ -461,31 +463,3 @@ Demonstrate the sketch steps: draw a 5 mm circle at the origin on the Top plane --- -### `tutorial_simple_hole` - -Draw a circle on a plane and cut it as a hole, as one worked example. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `plane` | `str` | ✅ | `` | Sketch plane for the hole | -| `center_x` | `float` | ✅ | `` | Hole center X coordinate in mm | -| `center_y` | `float` | ✅ | `` | Hole center Y coordinate in mm | -| `diameter` | `float` | ✅ | `` | Hole diameter in mm | -| `depth` | `float?` | — | `None` | Hole depth in mm (None for through hole) | - -**Sample call:** - -```json -{ - "plane": "Front", - "center_x": 0.0, - "center_y": 0.0, - "diameter": 10.0 -} -``` - ---- diff --git a/docs/user-guide/tool-catalog/template-management.md b/docs/user-guide/tool-catalog/template-management.md index fe83fc98..f2126b3b 100644 --- a/docs/user-guide/tool-catalog/template-management.md +++ b/docs/user-guide/tool-catalog/template-management.md @@ -1,94 +1,11 @@ # Template Management Tools -Create, extract, apply, compare, and library-manage SolidWorks document templates (.prtdot, .asmdot, .drwdot) and sheet formats. Enables standardised document creation across teams and projects. +Compare two SolidWorks template files (.prtdot, .asmdot, .drwdot) on disk. To +start a part from a template, give `template` to `create_part`. -> **Prerequisite:** Valid template file paths. Library operations require a configured template library path. +> **Prerequisite:** Both template files on disk. -**Total tools in this category: 6** - ---- - -### `extract_template` - -Capture a model's settings (custom properties, dimensions, units) as a reusable template file. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `source_model` | `str` | ✅ | `` | Path to source model file | -| `template_name` | `str` | ✅ | `` | Name for the extracted template | -| `template_type` | `str` | ✅ | `` | Template type (part, assembly, drawing) | -| `save_path` | `str` | ✅ | `` | Path to save the template file | -| `include_custom_properties` | `bool` | — | `True` | Include custom properties | -| `include_dimensions` | `bool` | — | `True` | Include dimensions | - -**Sample call:** - -```json -{ - "source_model": "example", - "template_name": "MCP_Demo_Part", - "template_type": "example", - "save_path": "C:\\Temp\\mcp_demo\\file.sldprt" -} -``` - ---- - -### `apply_template` - -Apply a saved template's properties, dimensions and materials to a model. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `template_path` | `str` | ✅ | `` | Path to template file | -| `target_model` | `str` | ✅ | `` | Path to target model | -| `overwrite_existing` | `bool` | — | `False` | Overwrite existing properties | -| `apply_dimensions` | `bool` | — | `True` | Apply dimension formatting | -| `apply_materials` | `bool` | — | `True` | Apply material settings | - -**Sample call:** - -```json -{ - "template_path": "C:\\Temp\\mcp_demo\\file.sldprt", - "target_model": "example" -} -``` - ---- - -### `batch_apply_template` - -Apply one template to every matching model in a folder. - -**Prerequisite:** SolidWorks running - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|-----------|------|----------|---------|-------------| -| `template_path` | `str` | ✅ | `` | Path to template file | -| `source_folder` | `str` | ✅ | `` | Folder containing target models | -| `file_pattern` | `str` | — | `*.sldprt` | File pattern to match | -| `recursive` | `bool` | — | `True` | Process subfolders | -| `backup_originals` | `bool` | — | `True` | Create backup copies | - -**Sample call:** - -```json -{ - "template_path": "C:\\Temp\\mcp_demo\\file.sldprt", - "source_folder": "example" -} -``` +**Total tools in this category: 1** --- @@ -122,30 +39,3 @@ Compare two template files on disk: whether they are byte-identical, and how the --- -### `save_to_template_library` - -Add a template to a shared, categorised template library. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- - -### `list_template_library` - -List the templates in the shared template library. - -**Prerequisite:** SolidWorks running - -**Sample call:** - -```json -{} -``` - ---- diff --git a/docs/user-guide/tools-overview.md b/docs/user-guide/tools-overview.md index ec8f964a..0359a840 100644 --- a/docs/user-guide/tools-overview.md +++ b/docs/user-guide/tools-overview.md @@ -1,15 +1,20 @@ # Tools Overview -The SolidWorks MCP Server provides 156 specialized tools for CAD automation. This page is a navigation map, not a tutorial. +The SolidWorks MCP Server provides 123 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 -- Start with the tool catalog page for the task you are solving. -- Use analysis tools after you already have a model or assembly. -- Use automation tools when you want a repeatable sequence, macro, or batch run. -- Treat mock-mode results as simulated outputs from the mock adapter, which is the - test/dev stand-in for SolidWorks COM. It keeps the suite runnable without SolidWorks, - but it does not prove the CAD result is physically correct. +- Every tool has a support level, shown on the [progress page](../progress.md). + Seven are `planned` (registered so the name is kept, but every call returns + `not_supported`) and eight are `deprecated` (they work, but another tool + replaces them; see [below](#deprecated-tools)). +- A tool's name starts with a verb that says what it does: `create_` makes a + document or feature, `add_` adds to a sketch, drawing or body, `get_` and + `list_` read, `set_` changes a value, `check_`, `verify_`, `measure_` and + `compare_` check. The full list is in the + [tool description standard](../agents/tool-description-standard.md#tool-names). +- The mock adapter stands in for SolidWorks in tests. Its results show that a + call is wired up, not that the CAD result is right; check that on SolidWorks. ## Tool Categories @@ -19,588 +24,136 @@ The SolidWorks MCP Server provides 156 specialized tools for CAD automation. Thi --- - Core 3D modeling operations including part creation, features, assemblies, and configurations. + Parts, assemblies and drawings: extrusions, revolves, sweeps, lofts, cuts, fillets, chamfers, patterns, reference geometry, mates, dimensions and the feature tree. - [**31 tools available** :octicons-arrow-right-24:](#modeling-tools) + [**31 tools available** :octicons-arrow-right-24:](tool-catalog/modeling.md) - :material-pencil:{ .lg .middle } **Sketching Tools** --- - Complete 2D sketching toolkit with geometry creation, constraints, and dimensions. + Sketches on a plane or a flat face: lines, arcs, circles, rectangles, polygons, splines, relations, dimensions, offsets, mirrors and patterns. - [**19 tools available** :octicons-arrow-right-24:](#sketching-tools) + [**18 tools available** :octicons-arrow-right-24:](tool-catalog/sketching.md) - :material-technical-draw:{ .lg .middle } **Drawing Tools** --- - Technical drawing creation, view management, dimensions, and annotations. + Drawings from a model: views, notes and centre marks. Section and detail views, dimensions and the title block are planned. - [**14 tools available** :octicons-arrow-right-24:](#drawing-tools) + [**13 tools available** :octicons-arrow-right-24:](tool-catalog/drawing.md) -- :material-chart-line:{ .lg .middle } **Analysis Tools** +- :material-file-cog:{ .lg .middle } **Drawing Automation** --- - Verify a build against expected values, mass properties, interference checking. + Model dimensions laid out without overlaps, datum tags, tolerances, BOM tables, sheet scale and complete drawing packages. - [**6 tools available** :octicons-arrow-right-24:](#analysis-tools) + [**7 tools available** :octicons-arrow-right-24:](tool-catalog/drawing-automation.md) -- :material-export:{ .lg .middle } **Export Tools** +- :material-magnify:{ .lg .middle } **Drawing Analysis** --- - Multi-format export including STEP, IGES, STL, PDF, DWG, and image formats. + Compare two versions of a drawing file. - [**7 tools available** :octicons-arrow-right-24:](#export-tools) + [**1 tool available** :octicons-arrow-right-24:](tool-catalog/drawing-analysis.md) -- :material-code-braces:{ .lg .middle } **VBA Generation** +- :material-database:{ .lg .middle } **Engineering Data** --- - Dynamic VBA code generation for complex operations exceeding COM parameter limits. + Model dimensions by name, measurements, materials, custom properties and sheet-metal flat patterns. - [**10 tools available** :octicons-arrow-right-24:](#vba-generation) + [**8 tools available** :octicons-arrow-right-24:](tool-catalog/engineering-data.md) -- :material-file-document:{ .lg .middle } **Template Management** +- :material-chart-line:{ .lg .middle } **Analysis Tools** --- - Template creation, extraction, application, comparison, and library management. + Check a build against expected values, mass properties and interference. - [**6 tools available** :octicons-arrow-right-24:](#template-management) + [**4 tools available** :octicons-arrow-right-24:](tool-catalog/analysis.md) -- :material-record:{ .lg .middle } **Macro Recording** +- :material-export:{ .lg .middle } **Export Tools** --- - Macro recording, playback, analysis, optimization, and library creation. + STEP, IGES, STL, PDF, DWG and images. - [**7 tools available** :octicons-arrow-right-24:](#macro-recording) + [**6 tools available** :octicons-arrow-right-24:](tool-catalog/export.md) -- :material-magnify:{ .lg .middle } **Drawing Analysis** +- :material-folder-open:{ .lg .middle } **File Management** --- - Quality analysis, dimension checking, compliance verification, and reporting. + Open, save, switch and inspect documents; the feature tree, configurations and the current selection; Pack and Go. - [**8 tools available** :octicons-arrow-right-24:](#drawing-analysis) + [**16 tools available** :octicons-arrow-right-24:](tool-catalog/file-management.md) -- :material-cog:{ .lg .middle } **Automation Tools** +- :material-code-braces:{ .lg .middle } **VBA Generation** --- - Workflow orchestration, batch processing, and automated file operations. + VBA macro text for steps the tools don't cover, written but not run. - [**8 tools available** :octicons-arrow-right-24:](#automation-tools) + [**10 tools available** :octicons-arrow-right-24:](tool-catalog/vba-generation.md) -- :material-folder-cog:{ .lg .middle } **File Management** +- :material-cog-play:{ .lg .middle } **Automation** --- - Document lifecycle, feature-tree inspection, configurations, custom properties, and pack-and-go. + A VBA macro skeleton for a described task. - [**19 tools available** :octicons-arrow-right-24:](tool-catalog/file-management.md) + [**1 tool available** :octicons-arrow-right-24:](tool-catalog/automation.md) -- :material-ruler:{ .lg .middle } **Drawing Automation** +- :material-record:{ .lg .middle } **Macro Recording** --- - Model dimensions laid out so nothing overlaps, BOM tables, sheet scale and a complete A3 drawing in one call. + Run a binary SolidWorks macro (`.swp`). - [**5 tools available** :octicons-arrow-right-24:](tool-catalog/drawing-automation.md) + [**1 tool available** :octicons-arrow-right-24:](tool-catalog/macro-recording.md) -- :material-ruler-square:{ .lg .middle } **Engineering Data** +- :material-file-document:{ .lg .middle } **Template Management** --- - Every model dimension by name, measurements, materials, custom properties and sheet-metal flat patterns. + Compare two template files. - [**8 tools available** :octicons-arrow-right-24:](tool-catalog/engineering-data.md) + [**1 tool available** :octicons-arrow-right-24:](tool-catalog/template-management.md) -- :material-file-search:{ .lg .middle } **Docs Discovery** +- :material-book-search:{ .lg .middle } **Docs Discovery** --- - Indexes installed SolidWorks COM/VBA API references for the active version. - - [**2 tools available** :octicons-arrow-right-24:](tool-catalog/docs-discovery.md) - - - -## Tool Statistics - -| Category | Tool Count | Complexity Level | Primary Use Case | -|----------|------------|------------------|------------------| -| **Modeling** | 31 | High | Part/assembly creation and modification | -| **Sketching** | 19 | Medium | 2D geometry and constraint management | -| **Drawing** | 14 | Medium | Technical documentation creation | -| **Drawing Analysis** | 8 | Medium | Quality assurance and compliance | -| **Drawing Automation** | 7 | Medium | Model dimensions without overlaps, BOMs, sheet scale, A3 drawing packages, GD&T frames and datum tags | -| **Engineering Data** | 8 | Medium | Dimensions, measuring, materials and properties | -| **Analysis** | 6 | High | Engineering validation and analysis | -| **Export** | 7 | Low | File format conversion and sharing | -| **Automation** | 8 | High | Workflow orchestration and batch processing | -| **File Management** | 19 | Low | File operations, session, and organization | -| **VBA Generation** | 10 | Very High | Complex operation automation | -| **Template Management** | 6 | Medium | Standardization and reuse | -| **Macro Recording** | 7 | High | Workflow capture and optimization | -| **Docs Discovery** | 2 | Medium | API and COM discovery workflows | - -**Total: 156 Tools** - -## Tool Design Principles - -### 1. Intelligent Parameter Handling - -Each tool chooses the simplest compatible execution path: - -```python -@mcp.tool() -async def create_extrusion( - sketch_name: str, - depth: float, - direction: str = "Blind", - reverse_direction: bool = False, - # 20+ additional parameters... -) -> dict[str, Any]: - """Create an extrusion feature. - - Automatically routes to VBA generation for complex parameter sets. - """ -``` - -### 2. Comprehensive Error Handling - -Tools return structured errors instead of silent failures: - -- **Parameter Validation**: Pydantic models ensure type safety -- **SolidWorks Integration**: Graceful handling of COM failures -- **Fallback Strategies**: Automatic retry with alternative approaches -- **Detailed Logging**: Complete audit trail of all operations - -### 3. Security-First Design - -Tools respect the configured security level and omit unsafe actions when locked down: - -```python -# Example security enforcement -@security_check(level="elevated") -@mcp.tool() -async def batch_export(...): - # Only available in development/restricted modes - pass - -@security_check(level="safe") -@mcp.tool() -async def calculate_mass_properties(...): - # Available in all security modes - pass -``` - -## Common Patterns - -### Async/Await Support - -All tools are fully asynchronous for optimal performance: - -```python -# Non-blocking tool execution -result = await create_part("MyPart", template="Part Template") -mass_props = await calculate_mass_properties("current") -``` - -### Result Standardization + Look up SolidWorks API interfaces and members in the installed type library. -Consistent return format across all tools: + [**5 tools available** :octicons-arrow-right-24:](tool-catalog/docs-discovery.md) -```python -{ - "status": "success", - "message": "Operation completed successfully", - "data": { - "feature_id": "Extrude1", - "geometry": {...}, - "properties": {...} - }, - "execution_time": 0.234, - "adapter_used": "VBA Generator" -} -``` +- :material-server:{ .lg .middle } **Server Admin** -### Progress Tracking - -Long-running operations provide real-time progress: - -```python -# Tools support progress callbacks -async def progress_callback(progress: float, message: str): - print(f"Progress: {progress:.1%} - {message}") - -result = await batch_process_files( - files=file_list, - on_progress=progress_callback -) -``` - -## Tool Selection Guide - -### By Use Case - -#### Getting Started - -- Simple modeling: `create_part()`, `create_sketch()`, `create_extrusion()` -- Basic analysis: `calculate_mass_properties()`, `check_interference()` -- File operations: `save_document()`, `export_step()` - -#### Intermediate Usage - -- Complex features: `create_sweep()`, `create_loft()`, `create_pattern()` -- Drawing creation: `create_technical_drawing()`, `add_drawing_view()` -- Batch operations: `batch_export()`, `batch_process_files()` - -#### Advanced Automation - -- Workflow orchestration: `execute_workflow()`, `generate_vba_code()` -- Template management: `extract_template()`, `apply_template()` -- Macro optimization: `optimize_macro()`, `analyze_macro()` - -### By Security Level - -#### Development (All Tools) - -Full access to all 109 tools for local development. - -#### Restricted (74 Tools) - -Safe and moderate tools excluding system-level operations: - -- ✅ All modeling and sketching tools -- ✅ Drawing tools and analysis -- ✅ Export and file management -- ❌ System VBA execution -- ❌ Advanced macro recording - -#### Secure (45 Tools) - -Read-only and analysis tools for production environments: - -- ✅ Analysis and measurement tools -- ✅ Read-only property access -- ✅ Export operations -- ❌ Modeling modifications -- ❌ File system write access - -#### Locked (15 Tools) - -Minimal analysis tools for public interfaces: - -- ✅ Mass properties and measurements -- ✅ Basic geometric analysis -- ❌ All modification operations -- ❌ File system access - -## Performance Characteristics - -### Operation Speed - -| Tool Category | Avg Response Time | Complexity Factor | -|---------------|-------------------|-------------------| -| Property Queries | 50-100ms | 1x | -| Simple Geometry | 100-300ms | 2x | -| Complex Features | 300-800ms | 5x | -| Batch Operations | 1-10s | 20x | -| VBA Generation | 200-500ms | 3x | - -### Resource Usage + --- -- **Memory**: 50-200MB per SolidWorks instance -- **CPU**: Varies by operation complexity -- **Disk**: Minimal for operations, substantial for exports -- **Network**: None (local SolidWorks integration) + Reset the circuit breaker after a fault is fixed. ---- + [**1 tool available** :octicons-arrow-right-24:](../progress.md) -## Detailed Tool Categories + -## Modeling Tools {#modeling-tools} +**Total: 123 Tools** -:material-cube-outline: **14 Tools** | 3D modeling and part creation +## Deprecated tools -### Core Tools +These still work, and their results carry a `warning` naming the +replacement. They are removed in 3.0.0. -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `create_part` | Create new part document | Low | New part creation from templates | -| `create_assembly` | Create new assembly document | Low | Multi-part assembly setup | -| `create_extrude` | Create extrusion features | Medium | Basic 3D geometry creation | -| `create_revolve` | Create revolution features | Medium | Rotational geometry | -| `create_sweep` | Create swept features | High | Complex path-based geometry | -| `create_loft` | Create lofted features | High | Advanced surface modeling | -| `create_cut` | Create cut features | Medium | Material removal operations | -| `create_fillet` | Apply fillet/round features | Low | Edge finishing | -| `manage_configurations` | Handle design configurations | High | Design variant management | -| `rename_feature` | Rename a feature on the tree (read-back verified) | Low | Design-variant / cleanup workflows | -| `set_units` | Set the document linear unit system (mm/cm/m/in/ft) | Low | Aligning a model to a target unit system | -| `create_reference_point` | Reference point along an edge or at a face centre | Medium | Driving patterns / mates off construction geometry | - -### Example Usage - -```python -# Create a new part -result = await create_part( - name="Motor Housing", - template="Part Template", - units="millimeters" -) - -# Add an extrusion -extrude = await create_extrude( - sketch_name="Base Profile", - depth=50.0, - direction="Blind" -) -``` - -## Sketching Tools {#sketching-tools} - -:material-pencil: **19 Tools** | 2D geometry and constraints - -### Geometry Creation - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `create_sketch` | Initialize new sketch | Low | Start 2D design | -| `sketch_line` | Draw line segments | Low | Basic geometry | -| `sketch_rectangle` | Draw rectangles | Low | Rectangular profiles | -| `sketch_circle` | Draw circles | Low | Circular features | -| `sketch_arc` | Draw arcs | Medium | Curved geometry | -| `sketch_spline` | Draw splines | Medium | Complex curves | -| `sketch_polygon` | Draw polygons | Low | Multi-sided shapes | - -### Constraints & Dimensions - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `add_dimension` | Add sketch dimensions | Medium | Size control | -| `add_constraint` | Add geometric constraints | Medium | Shape relationships | -| `constraint_coincident` | Coincident constraint | Low | Point alignment | -| `constraint_parallel` | Parallel constraint | Low | Line relationships | -| `constraint_perpendicular` | Perpendicular constraint | Low | Right angles | -| `constraint_tangent` | Tangent constraint | Medium | Smooth transitions | -| `constraint_equal` | Equal constraint | Low | Size matching | -| `constraint_symmetric` | Symmetry constraint | Medium | Balanced geometry | -| `sketch_pattern` | Pattern sketch entities | High | Repeated geometry | - -### Example Usage - -```python -# Create and populate a sketch -sketch = await create_sketch(plane="Front") -await sketch_rectangle( - center_x=0, center_y=0, - width=100, height=50 -) -await add_dimension( - entity="Rectangle", - dimension_type="width", - value=100 -) -``` - -## Drawing Tools {#drawing-tools} - -:material-technical-draw: **13 Tools** | Technical documentation - -### View Management - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `create_drawing` | Create new drawing document | Low | Technical documentation | -| `insert_model_view` | Insert 3D model view | Medium | Show part/assembly | -| `create_section_view` | Create section views | High | Internal details | -| `create_detail_view` | Create detail views | Medium | Magnified areas | -| `arrange_views` | Auto-arrange drawing views | Medium | Layout optimization | - -### Annotations - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `add_dimensions` | Add drawing dimensions | Medium | Size specification | -| `add_annotations` | Add notes and symbols | Low | Documentation | -| `create_title_block` | Manage title blocks | Medium | Drawing standards | -| `auto_center_marks` | Auto-insert centre marks on circular features in a view | Low | Drawing-standards compliance | - -### Example Usage - -```python -# Create drawing with views -drawing = await create_drawing( - template="A3 Landscape", - part_path="Motor Housing.SLDPRT" -) -await insert_model_view( - view_type="Isometric", - scale=0.5 -) -``` - -## Analysis Tools {#analysis-tools} - -:material-chart-line: **6 Tools** | Engineering analysis and validation - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `verify_model` | Check a part or assembly against expected values | Low | Final check of a build | -| `calculate_mass_properties` | Mass, volume, center of mass | Low | Weight analysis | -| `check_interference` | Check part collisions | Medium | Assembly validation | -| `analyze_geometry` | Curvature, draft, thickness | High | Quality assurance | -| `get_material_properties` | Assigned material's properties | Low | Engineering data | - -### Example Usage - -```python -# Analyze part properties -props = await calculate_mass_properties( - entities=["Part1", "Part2"], - include_hidden=False -) -mass = props.data["mass"] -volume = props.data["volume"] -``` - -## Export Tools {#export-tools} - -:material-export: **7 Tools** | File format conversion - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `export_step` | Export to STEP format | Low | CAD data exchange | -| `export_iges` | Export to IGES format | Low | Legacy CAD systems | -| `export_stl` | Export to STL format | Low | 3D printing | -| `export_pdf` | Export drawings to PDF | Medium | Documentation | -| `export_dxf` | Export 2D DXF files | Medium | 2D fabrication | -| `export_images` | Export to image formats | Low | Presentations | -| `batch_export` | Export multiple files | High | Mass conversion | - -### Example Usage - -```python -# Export for 3D printing -await export_stl( - file_path="Motor Housing.stl", - resolution="Fine", - units="Millimeters" -) -``` - -## VBA Generation {#vba-generation} - -:material-code-braces: **10 Tools** | Automatic VBA code generation - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `generate_macro` | Create VBA macro code | High | Complex operations | -| `optimize_macro` | Optimize existing macros | High | Performance tuning | -| `macro_to_api` | Convert macro to API calls | High | Code modernization | -| `validate_syntax` | Check VBA syntax | Medium | Code validation | -| `execute_vba` | Run VBA code safely | High | Custom operations | -| `macro_library` | Manage macro collections | Medium | Code organization | -| `parameter_mapping` | Map API to VBA params | High | Translation layer | -| `error_handling` | Add robust error handling | Medium | Reliability | -| `performance_analysis` | Analyze macro performance | High | Optimization | -| `code_documentation` | Generate macro docs | Low | Documentation | - -## Template Management {#template-management} - -:material-file-document: **6 Tools** | Standardized workflows - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `create_template` | Create document templates | Medium | Standardization | -| `apply_template` | Apply templates to docs | Low | Consistency | -| `extract_template` | Extract template from doc | Medium | Template creation | -| `validate_template` | Check template integrity | Medium | Quality control | -| `template_library` | Manage template collections | High | Organization | -| `compare_templates` | Compare template versions | Medium | Version control | - -## Macro Recording {#macro-recording} - -:material-record: **7 Tools** | Macro automation - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `start_recording` | Begin macro recording | Low | Capture workflows | -| `stop_recording` | End macro recording | Low | Save captured actions | -| `playback_macro` | Execute recorded macro | Medium | Automation replay | -| `edit_macro` | Modify macro code | High | Customization | -| `optimize_recording` | Improve macro efficiency | High | Performance | -| `macro_analysis` | Analyze macro quality | Medium | Code review | -| `create_macro_library` | Build macro collections | High | Organization | -| `share_macros` | Export/import macros | Medium | Collaboration | - -## Drawing Analysis {#drawing-analysis} - -:material-magnify: **8 Tools** | Quality assurance - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `check_dimensions` | Validate drawing dimensions | Medium | Quality control | -| `analyze_tolerances` | Check tolerance stack-up | High | Engineering analysis | -| `verify_standards` | Check drawing standards | Medium | Compliance | -| `detect_errors` | Find drawing issues | High | Error detection | -| `generate_reports` | Create analysis reports | Medium | Documentation | -| `compare_revisions` | Compare drawing versions | High | Version control | -| `validate_symbols` | Check symbol usage | Medium | Standard compliance | -| `measure_complexity` | Analyze drawing complexity | Medium | Metrics | -| `audit_properties` | Check document properties | Low | Metadata validation | -| `compliance_check` | Full compliance validation | High | Certification | - -## Automation Tools {#automation-tools} - -:material-cog: **8 Tools** | Workflow orchestration - -| Tool Name | Description | Complexity | Use Case | -|-----------|-------------|------------|----------| -| `batch_process` | Process multiple files | High | Mass operations | -| `workflow_builder` | Create custom workflows | High | Process automation | -| `schedule_tasks` | Schedule automated tasks | Medium | Background processing | -| `file_operations` | Automated file management | Medium | File organization | -| `data_extraction` | Extract data from models | Medium | Data mining | -| `report_generation` | Create automated reports | High | Documentation | -| `integration_apis` | Connect external systems | High | System integration | -| `monitoring_tools` | Monitor automation health | Medium | System management | - ---- - -## Best Practices - -### Tool Selection - -1. **Use the right tool**: Choose the most specific tool for your task -2. **Consider security**: Select appropriate security level for deployment -3. **Handle errors**: Always check return status and handle failures -4. **Monitor performance**: Track execution times for optimization - -### Batch Operations - -1. **Group similar operations**: Batch similar tasks for efficiency -2. **Manage resources**: Consider SolidWorks memory usage -3. **Implement progress tracking**: Provide user feedback for long operations -4. **Error recovery**: Handle partial failures gracefully - -### Security Considerations - -1. **Least privilege**: Use the lowest security level that meets requirements -2. **Validate inputs**: Always validate user-provided parameters -3. **Audit operations**: Log all operations for compliance -4. **Monitor access**: Track tool usage patterns - ---- - -!!! tip "Getting Started" - Ready to explore? Jump to any tool category above or check out the [Quick Start Guide](../getting-started/quickstart.md) for hands-on examples. - -!!! info "Development Status" - All 109 tools are implemented and ready for use. Documentation and examples are continuously being expanded. +| Deprecated | Use instead | +| --- | --- | +| `load_part`, `load_assembly` | `open_model` | +| `save_part`, `save_assembly` | `save_file` (`pack_and_go_assembly` to copy an assembly with its parts) | +| `calculate_mass_properties` | `get_mass_properties` | +| `get_file_properties` | `get_model_info` | +| `add_drawing_view` | `create_drawing_view` | +| `sketch_tutorial_simple_hole` | the sketching and feature tools | diff --git a/mkdocs.yml b/mkdocs.yml index 0a0b0d2b..844db491 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,6 +1,6 @@ site_name: SolidWorks MCP Server site_url: https://andrewbartels1.github.io/SolidworksMCP-python -site_description: Python MCP server for SolidWorks automation with 152 tools +site_description: Python MCP server for SolidWorks automation with 123 tools strict: true # Repository diff --git a/openspec/changes/configuration-tools/proposal.md b/openspec/changes/configuration-tools/proposal.md index 60cfaad7..029ae49a 100644 --- a/openspec/changes/configuration-tools/proposal.md +++ b/openspec/changes/configuration-tools/proposal.md @@ -61,6 +61,7 @@ without it. CHANGELOG, progress bars. - No issue is filed; this is queue item 13. - **Depends on the honest-tool-list change (queue item 10)**, merged - first: it sets the verb list and runs the design-table probe. If that - probe shows design tables work without trouble, `manage_design_table` - stays planned and is added to this change's tasks before it starts. + first: it sets the verb list and ran the design-table probe. The probe + (2026-11-14) showed design tables don't work through COM on this + install, so `manage_design_table` was removed; this change builds + configurations without Excel. diff --git a/openspec/changes/configuration-tools/tasks.md b/openspec/changes/configuration-tools/tasks.md index 9f5da303..27c8d5ff 100644 --- a/openspec/changes/configuration-tools/tasks.md +++ b/openspec/changes/configuration-tools/tasks.md @@ -1,6 +1,6 @@ ## 0. Before starting -- [ ] 0.1 Confirm the honest-tool-list change is merged; read its design-table finding (its design decision 8). If `manage_design_table` was kept, add its tasks here (insert, read, update rows) before section 1 +- [ ] 0.1 Confirm the honest-tool-list change is merged; read its design-table finding (its design decision 8). If `manage_design_table` was kept, add its tasks here (insert, read, update rows) before section 1 (Known 2026-11-14: design tables don't work through COM here, so `manage_design_table` was removed; build configurations without Excel.) ## 1. Create, activate, delete diff --git a/openspec/changes/honest-tool-list/design.md b/openspec/changes/honest-tool-list/design.md index 1d65e7d2..83d3c921 100644 --- a/openspec/changes/honest-tool-list/design.md +++ b/openspec/changes/honest-tool-list/design.md @@ -97,7 +97,7 @@ Removing tools that never worked is not a break for a working client, so the release is 2.1.0. The CHANGELOG lists the removed names under "Removed" and the deprecated ones under "Deprecated". -### 8. `manage_design_table` is checked before it goes +### 8. `manage_design_table` is checked before it goes (removed) It is in the removal list because a design table needs Excel on the machine, and item 13's configuration tools give agents the same variants @@ -106,6 +106,16 @@ live probe (task 2.0) inserts a design table on a scratch part and reads it back. If it works, the tool stays `planned` for item 13 and the planned count is eight; if not, it is removed and the finding is recorded here. +**Finding (live, 2026-11-14, SolidWorks 2026, Excel installed):** a +two-row spreadsheet (`Default` 20 mm, `Tall` 30 mm on `D1@Boss-Extrude1`) +was written by Excel and inserted with `IModelDoc2.InsertFamilyTableOpen`. +`GetDesignTable` then returns a table, but `IDesignTable.Attach` returns +false, `GetTotalRowCount` and `GetTotalColumnCount` return -2, every cell +reads empty, and no `Tall` configuration is made. The insert call itself +raised in late binding. Design tables don't work through COM here, so the +tool is removed with the rest (33 in all) and the planned count is seven. +Item 13's configuration tools give agents variants without Excel. + ### 9. Items 11 to 14 depend on this change `part-feature-depth`, `drawing-pack`, `configuration-tools` and diff --git a/openspec/changes/honest-tool-list/tasks.md b/openspec/changes/honest-tool-list/tasks.md index 24836a84..56d423bb 100644 --- a/openspec/changes/honest-tool-list/tasks.md +++ b/openspec/changes/honest-tool-list/tasks.md @@ -1,48 +1,48 @@ ## 1. The deprecated level -- [ ] 1.1 `SupportLevel.DEPRECATED` and `Support.since`; `warning()` gives "Deprecated: use ``." or "Deprecated: no replacement."; tests -- [ ] 1.2 `ToolRegistrar`: the description opening and success `warning` for deprecated tools (same path as beta); tests -- [ ] 1.3 Support-level test: a deprecated entry names a registered replacement or "no replacement"; fails when the major version is above `since`'s; every planned reason names a queue item; tests for each rule -- [ ] 1.4 Progress generator: deprecated tools counted on their own, left out of the coverage bars; tests +- [x] 1.1 `SupportLevel.DEPRECATED` and `Support.since`; `warning()` gives "Deprecated: use ``." or "Deprecated: no replacement."; tests +- [x] 1.2 `ToolRegistrar`: the description opening and success `warning` for deprecated tools (same path as beta); tests +- [x] 1.3 Support-level test: a deprecated entry names a registered replacement or "no replacement"; fails when the major version is above `since`'s; every planned reason names a queue item; tests for each rule +- [x] 1.4 Progress generator: deprecated tools counted on their own, left out of the coverage bars; tests ## 2. Remove the 33 planned tools -- [ ] 2.0 Check `manage_design_table` before removing it: does `IModelDoc2.InsertFamilyTableNew` work on the user's machine (it needs Excel), and is there a read path (`IDesignTable`) without Excel? Record the finding in design.md. If design tables work, keep the tool `planned` for queue item 13 (`configuration-tools`) and add it there; otherwise remove it with the rest. Its live probe joins this change's live bundle (7.1), not a separate run -- [ ] 2.1 Analysis, automation, drawing (`add_annotation`) and export: remove the tools, input models, hints, levels and tests -- [ ] 2.2 Drawing analysis (six), file management (three), macros (six), sketching (`tutorial_simple_hole`), templates (five): the same -- [ ] 2.3 Remove every "use ``" sentence from other descriptions; a test that no description names an unregistered tool -- [ ] 2.4 The seven planned drawing tools' reason: "planned in queue item 12 (the drawing pack)." +- [x] 2.0 Check `manage_design_table` before removing it: does `IModelDoc2.InsertFamilyTableNew` work on the user's machine (it needs Excel), and is there a read path (`IDesignTable`) without Excel? Record the finding in design.md. If design tables work, keep the tool `planned` for queue item 13 (`configuration-tools`) and add it there; otherwise remove it with the rest. Its live probe joins this change's live bundle (7.1), not a separate run +- [x] 2.1 Analysis, automation, drawing (`add_annotation`) and export: remove the tools, input models, hints, levels and tests +- [x] 2.2 Drawing analysis (six), file management (three), macros (six), sketching (`tutorial_simple_hole`), templates (five): the same +- [x] 2.3 Remove every "use ``" sentence from other descriptions; a test that no description names an unregistered tool +- [x] 2.4 The seven planned drawing tools' reason: "planned in queue item 12 (the drawing pack)." ## 3. Replacements gain what they replace -- [ ] 3.1 `save_file`: `overwrite` input, `_prepare_save_target` on a new path with the extension from the active document's type; tests for a missing folder, the wrong extension, an existing file, and in place -- [ ] 3.2 `get_model_info`: `size_bytes`, `created`, `modified` from one `os.stat` helper shared with `get_file_properties`; tests for saved and unsaved -- [ ] 3.3 Mock adapter: the model info it returns carries a path that the tests can stat, and an unsaved document has none; tests +- [x] 3.1 `save_file`: `overwrite` input, `_prepare_save_target` on a new path with the extension from the active document's type; tests for a missing folder, the wrong extension, an existing file, and in place +- [x] 3.2 `get_model_info`: `size_bytes`, `created`, `modified` from one `os.stat` helper shared with `get_file_properties`; tests for saved and unsaved +- [x] 3.3 Mock adapter: the model info it returns carries a path that the tests can stat, and an unsaved document has none; tests ## 4. Deprecate the eight stable duplicates -- [ ] 4.1 Levels: `load_part`, `load_assembly` → `open_model`; `save_part`, `save_assembly` → `save_file`; `calculate_mass_properties` → `get_mass_properties`; `get_file_properties` → `get_model_info`; `add_drawing_view` → `create_drawing_view`; `sketch_tutorial_simple_hole` → no replacement; all `since` 2.1.0 -- [ ] 4.2 `save_assembly`'s description names `pack_and_go_assembly` for `include_references` -- [ ] 4.3 Replacements' descriptions drop "for X, use ``" pointers; tests +- [x] 4.1 Levels: `load_part`, `load_assembly` → `open_model`; `save_part`, `save_assembly` → `save_file`; `calculate_mass_properties` → `get_mass_properties`; `get_file_properties` → `get_model_info`; `add_drawing_view` → `create_drawing_view`; `sketch_tutorial_simple_hole` → no replacement; all `since` 2.1.0 +- [x] 4.2 `save_assembly`'s description names `pack_and_go_assembly` for `include_references` +- [x] 4.3 Replacements' descriptions drop "for X, use ``" pointers; tests ## 5. Verb list -- [ ] 5.1 The verb table and its exceptions in `docs/agents/tool-description-standard.md`; CONTRIBUTING.md links it -- [ ] 5.2 The naming check in the description-standard test; a test that an unlisted verb fails +- [x] 5.1 The verb table and its exceptions in `docs/agents/tool-description-standard.md`; CONTRIBUTING.md links it +- [x] 5.2 The naming check in the description-standard test; a test that an unlisted verb fails ## 6. Docs -- [ ] 6.1 Tool catalog pages: removed rows gone, deprecated rows marked -- [ ] 6.2 The agent skill's tool lists and `errors-and-limits.md` -- [ ] 6.3 README counts and progress bars regenerated (`python -m solidworks_mcp.progress.generate`) -- [ ] 6.4 CHANGELOG (2.1.0): Removed (the 33 names), Deprecated (the eight), Changed (`save_file` refuses an existing file without `overwrite`; `get_model_info` adds file details) +- [x] 6.1 Tool catalog pages: removed rows gone, deprecated rows marked +- [x] 6.2 The agent skill's tool lists and `errors-and-limits.md` +- [x] 6.3 README counts and progress bars regenerated (`python -m solidworks_mcp.progress.generate`) +- [x] 6.4 CHANGELOG (2.1.0): Removed (the 33 names), Deprecated (the eight), Changed (`save_file` refuses an existing file without `overwrite`; `get_model_info` adds file details) ## 7. Live bundle (one set, run together, then fixes one by one) -- [ ] 7.1 Live tests: `save_file` to a new path, a missing folder and an existing file; `get_model_info` on a saved and a new part; one deprecated tool's `warning`; the design-table probe (task 2.0): insert one on a scratch part and read it back -- [ ] 7.2 Hand the user the bundle; fix each failure afterwards, one at a time +- [x] 7.1 Live tests: `save_file` to a new path, a missing folder and an existing file; `get_model_info` on a saved and a new part; one deprecated tool's `warning`; the design-table probe (task 2.0): insert one on a scratch part and read it back +- [x] 7.2 Hand the user the bundle; fix each failure afterwards, one at a time ## 8. Finish -- [ ] 8.1 Full mock suite at 100% coverage, ruff, `mkdocs build --strict` +- [x] 8.1 Full mock suite at 100% coverage, ruff, `mkdocs build --strict` - [ ] 8.2 Sign-off, PR (no attribution) closing #174, archive, the queue updated diff --git a/openspec/queue.md b/openspec/queue.md index ca9c2281..1575392a 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -20,49 +20,89 @@ Last updated 2026-11-14. | 7 | Beta tools to stable: fix each beta tool's known fault (the small faults listed below), prove it live, and move it up a level | not filed yet | `beta-tool-faults` (archived) | Done 2026-11-09 (#219, 2.0.0): 23 tools promoted, signed off live | | 8 | Experimental tools to stable: a live test for each of the 10, then promote it or record its fault | not filed yet | `experimental-tools-to-stable` (archived) | Done 2026-11-12 (2.0.0, tagged `v2.0.0`): all 10 promoted, signed off live. Pack and Go now copies the files `GetDependencies2` lists (SolidWorks 2026's own Pack and Go copied only the assembly); `comtypes` dropped | | 9 | Monitor stand demo follow-ups: feature order, `verify_model`'s planes, dimension listing, STL export, `create_sketch` on a face, the demo's camera | #206 | `monitor-stand-follow-ups` (archived) | Done 2026-11-14: all five live tests pass, GIF re-recorded; PR open | -| 10 | An honest tool list: remove the 33 planned tools no item will build, deprecate the stable duplicates for one release, settle a verb list. Replaces the old items "the 40 planned tools" and "duplicate tools" | #174 | `honest-tool-list` | Planned 2026-11-12. Items 11-14 depend on it. It probes `manage_design_table` live before removing it (kept for item 13 if design tables work) | +| 10 | An honest tool list: remove the 33 planned tools no item will build (the design table among them, after its live check), deprecate the stable duplicates for one release, settle a verb list. Replaces the old items "the 40 planned tools" and "duplicate tools" | #174 | `honest-tool-list` | Planned 2026-11-12. Items 11-14 depend on it. It probes `manage_design_table` live before removing it (kept for item 13 if design tables work) | +| 19 | Our own `llms.txt`, and every link checked. A script builds `llms.txt` from the mkdocs nav: each entry's title and summary are copied word for word from the page they link to, and nothing is written by hand. A check follows EVERY link in `llms.txt`, the README and the docs (internal pages, anchors and external URLs), and fails on a dead link, a redirect off this repo, or an `llms.txt` line that doesn't match its page. Security review of the result: only this repo's own pages, no third-party links, no hidden text or instructions. PR #225's file is not used as a starting point; the user is closing that PR | #225 (closed, not merged) | not yet written | Added 2026-11-14 at the user's request. Next after item 10, so the file lists only working tools | | 11 | Part features the peers lead with: Hole Wizard holes, cosmetic threads, a linear feature pattern, shell, draft, rib, and sketch convert-entities | #105 | `part-feature-depth` | Planned 2026-11-12 | | 12 | The drawing pack, where no peer goes: section and detail views, the title block and sheet format, drawing dimensions, and one drawing check | #102, #158 | `drawing-pack` | Planned 2026-11-12. Builds the 7 planned drawing tools item 10 leaves | | 13 | Configurations: create, activate and delete one, and suppress a feature or set a dimension in one configuration only | none | `configuration-tools` | Planned 2026-11-12 | +| 20 | Elastic material properties: `get_material` (or a sibling) also reads the assigned material's elastic modulus, Poisson's ratio, yield and tensile strength, with units, so an agent can size a part without leaving the server. Found by item 10's ledger: `get_material_properties` was removed and only name and density are read today | none | not yet written | Added 2026-11-14 at the user's request. Small; after item 13 | +| 21 | Save the active document as a template (.prtdot, .asmdot, .drwdot), so a part set up once (units, material, properties) can start the next one through `create_part`'s `template`. Found by item 10's ledger: `create_template` and `save_to_template_library` were removed and nothing saves a template today | none | not yet written | Added 2026-11-14 at the user's request. Small; after item 20 | | 14 | Optional toolsets and a discovery mode, to cut the tool list's size | #176 | `tool-discovery-mode` | Planned 2026-11-12. After item 10, which decides the families | | 15 | Sheet metal: base flange, edge flange, sketched bend, flat pattern | #57 | not yet written | After item 11 | | 16 | README: licence-tier tags | #79 (other half) | not yet written | | | 17 | Remove the stale `validate_coverage.py`; decide whether mypy gates CI | #157 | not yet written | | | 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` | -## Tools that can't run yet (items 10 and 12) +## Removed tools (item 10, release 2.1.0) -Each one's description says "Not available yet ... planned for a future -release" (the wording is in `docs/agents/tool-description-standard.md`). -Found while rewriting the descriptions (39), plus `tutorial_simple_hole` -(40 in all). Their support level is `planned`. Item 10 removes 33 of them; -item 12 builds the seven drawing tools that are left (`add_dimension`, +33 tools were registered but never implemented: every call returned +`not_supported`. Item 10 removed them (#174). Each row says why, and whether +the job is done elsewhere or is a real gap that should come back as a queue +item. Re-adding a name needs a working implementation and a live test, not a +placeholder. + +Why, in short: + +- **duplicate**: another working tool already does it; +- **loop**: the agent runs it by calling a working tool once per file; +- **no API**: SolidWorks' type library has no member for it, or the job + isn't defined well enough to build; +- **replaced**: a queue item builds a better-defined tool for it. + +| Tool | Why | Done today by, or comes back as | +| --- | --- | --- | +| `analyze_geometry` | no API (curvature, draft and thickness in one call) | `measure_entities`, `verify_model`; a draft check could come with item 11's `add_draft` | +| `get_material_properties` | duplicate, in part | `get_material` (name, database, density). **Gap:** elastic properties; queue item 20 | +| `automation_start_macro_recording` | no API (no recorder start member) | SolidWorks' own Tools > Macro > Record; `generate_vba_code` | +| `automation_stop_macro_recording` | no API | as above | +| `start_macro_recording` | no API | as above | +| `stop_macro_recording` | no API | as above | +| `batch_process_files` | loop | `open_model`, then the operation, per file | +| `batch_export` | loop | `export_*` per file | +| `batch_file_operations` | loop | `open_model`, `save_as` per file | +| `batch_execute_macros` | loop | `execute_macro` per macro | +| `batch_apply_template` | loop | per file (see templates) | +| `execute_workflow` | loop | the agent's own sequence of calls | +| `manage_design_table` | no API that works here: checked live 2026-11-14 on SolidWorks 2026, `InsertFamilyTableOpen` adds the table but SolidWorks can't open it in Excel (`Attach` false, counts -2) and makes no configurations | configurations, queue item 13 | +| `optimize_performance` | no API (not defined) | none needed | +| `create_template` | no API, as specified | `create_part` / `create_assembly` take `template`. **Gap:** saving a document as a template; queue item 21 | +| `extract_template` | no API, as specified | as above | +| `apply_template` | duplicate | `set_custom_property`, `set_material`, `set_units` | +| `list_template_library` | no API (a folder listing, not SolidWorks) | none needed | +| `save_to_template_library` | no API | as `create_template` | +| `add_annotation` | duplicate | `add_note`, `add_gtol`, `add_datum_tag` | +| `analyze_drawing_annotations` | replaced | item 12's `check_drawing` | +| `analyze_drawing_comprehensive` | replaced | item 12's `check_drawing` | +| `analyze_drawing_dimensions` | replaced | item 12's `check_drawing` | +| `analyze_drawing_views` | replaced | `list_drawing_views`; item 12's `check_drawing` | +| `check_drawing_compliance` | replaced | item 12's `check_drawing` | +| `generate_drawing_report` | replaced | item 12's `check_drawing` | +| `validate_drawing_completeness` | replaced | item 12's `check_drawing` | +| `convert_file_format` | duplicate | `save_as`, `export_*` | +| `manage_file_properties` | duplicate | `get_custom_properties`, `set_custom_property` | +| `analyze_macro` | no API (VBA text review, not SolidWorks) | none needed | +| `optimize_macro` | no API (as above) | none needed | +| `create_macro_library` | no API (a folder of files) | none needed | +| `tutorial_simple_hole` | never worked | the sketching and feature tools; item 11's `create_hole` (Hole Wizard) | + +The two gaps marked above are queued: elastic material properties as item +20, saving a template as item 21. + +Still planned (7): the drawing tools item 12 builds (`add_dimension`, `auto_dimension_view`, `create_section_view`, `create_detail_view`, -`update_title_block`, `update_sheet_format`, and `check_drawing_standards` +`update_title_block`, `update_sheet_format`, `check_drawing_standards` renamed `check_drawing`). -- **Drawing analysis (7):** `analyze_drawing_comprehensive`, - `analyze_drawing_dimensions`, `analyze_drawing_annotations`, - `check_drawing_compliance`, `analyze_drawing_views`, - `generate_drawing_report`, `validate_drawing_completeness`. -- **Drawing (8):** `add_dimension` and `auto_dimension_view` (#102), - `create_section_view`, `create_detail_view`, `update_sheet_format`, - `update_title_block`, `add_annotation`, `check_drawing_standards`. -- **Automation (7):** `automation_start_macro_recording`, - `automation_stop_macro_recording`, `batch_process_files`, - `manage_design_table`, `execute_workflow`, `create_template`, - `optimize_performance`. -- **Macro recording (6):** `start_macro_recording`, - `stop_macro_recording`, `analyze_macro`, `batch_execute_macros`, - `optimize_macro`, `create_macro_library`. -- **Templates (5):** `extract_template`, `apply_template`, - `batch_apply_template`, `save_to_template_library`, - `list_template_library`. -- **File management (3):** `manage_file_properties`, `convert_file_format`, - `batch_file_operations`. -- **Export (1):** `batch_export`. -- **Analysis (2):** `analyze_geometry`, `get_material_properties`. -- **Sketching (1):** `tutorial_simple_hole`: its cut step fails on - SolidWorks (it calls the adapter's `create_cut`, which only the mock has). +Deprecated (8, removed in 3.0.0): `load_part`, `load_assembly` (use +`open_model`); `save_part`, `save_assembly` (use `save_file`); +`calculate_mass_properties` (use `get_mass_properties`); +`get_file_properties` (use `get_model_info`); `add_drawing_view` (use +`create_drawing_view`); `sketch_tutorial_simple_hole` (no replacement). + +How the list is kept honest: the support-level table +(`tools/support_levels.py`) gives every tool one level, and its checks fail +when a planned tool names no queue item, a deprecated tool outlives its +major version, or a stable tool has no live test. The counts are on the +[progress page](../docs/progress.md), regenerated from the code. ## Small faults (item 7) diff --git a/scripts/demo_monitor_stand.py b/scripts/demo_monitor_stand.py index 54e6dccc..9e477fcf 100644 --- a/scripts/demo_monitor_stand.py +++ b/scripts/demo_monitor_stand.py @@ -33,7 +33,7 @@ centre), a rectangle the base's size plus the clearance on each side, and a blind cut down into the top. 7. ``rebuild_model``, then ``verify_model`` against a hand calculation. -8. ``save_part`` and, with ``--stl``, ``export_stl``. +8. ``save_file`` and, with ``--stl``, ``export_stl``. Every sketch is symmetric about the origin, so the Top and Right planes' sketch axes (which run along -Z) cannot mirror anything. @@ -346,7 +346,7 @@ def _show() -> None: failed = [c["name"] for c in verdict.get("checks", []) if c.get("passed") is not True] raise RuntimeError(f"verify_model did not pass: {failed}") - await call("save_part", {"file_path": str(out), "overwrite": replace}) + await call("save_file", {"file_path": str(out), "overwrite": replace}) if stl: await call( "export_stl", diff --git a/src/solidworks_mcp/__init__.py b/src/solidworks_mcp/__init__.py index b1bf0108..2bd1046e 100644 --- a/src/solidworks_mcp/__init__.py +++ b/src/solidworks_mcp/__init__.py @@ -1,7 +1,7 @@ """SolidWorks MCP Server - Python Implementation with FastMCP and PydanticAI. This is a comprehensive Python implementation of the SolidWorks MCP server, providing -156 tools for SolidWorks automation with enhanced security, configurability, and modern +123 tools for SolidWorks automation with enhanced security, configurability, and modern Python architectures. Original TypeScript implementation rights and IP remain with the original author. This diff --git a/src/solidworks_mcp/adapters/intelligent_router.py b/src/solidworks_mcp/adapters/intelligent_router.py index 4961b6af..e1b97165 100644 --- a/src/solidworks_mcp/adapters/intelligent_router.py +++ b/src/solidworks_mcp/adapters/intelligent_router.py @@ -76,16 +76,9 @@ def __init__( # volumes mid-build. # "get_mass_properties", # "calculate_mass_properties", - "get_material_properties", - "analyze_geometry", # "check_interference": changes as components are mated or moved; # a cached answer ignored the changes (#209). # Drawing analysis operations - "analyze_drawing_comprehensive", - "analyze_drawing_dimensions", - "analyze_drawing_views", - "analyze_drawing_annotations", - "check_drawing_compliance", "check_drawing_standards", "compare_drawing_versions", # Classification and indexing diff --git a/src/solidworks_mcp/agents/soc_exporter.py b/src/solidworks_mcp/agents/soc_exporter.py index 113bb94e..e6b04b4b 100644 --- a/src/solidworks_mcp/agents/soc_exporter.py +++ b/src/solidworks_mcp/agents/soc_exporter.py @@ -428,7 +428,6 @@ def emit_unknown(self, tool_name: str, inp: dict[str, Any]) -> None: "get_mass_properties", "get_dimension", "check_sketch_fully_defined", - "analyze_geometry", "check_interference", "calculate_mass_properties", } diff --git a/src/solidworks_mcp/progress/svg.py b/src/solidworks_mcp/progress/svg.py index b81a172f..ec544567 100644 --- a/src/solidworks_mcp/progress/svg.py +++ b/src/solidworks_mcp/progress/svg.py @@ -13,12 +13,14 @@ from ..tools.support_levels import SupportLevel from .com_coverage import CORE_INTERFACES, ComCoverage -#: Fill colour per level; planned is left as the empty track. +#: Fill colour per level; planned is left as the empty track, and +#: deprecated tools are counted in the legend only, outside the bar. LEVEL_COLOURS: dict[SupportLevel, str] = { SupportLevel.STABLE: "#2ea043", SupportLevel.BETA: "#d29922", SupportLevel.EXPERIMENTAL: "#db6d28", SupportLevel.PLANNED: "#484f58", + SupportLevel.DEPRECATED: "#8957e5", } _WIDTH, _HEIGHT = 840, 236 @@ -95,6 +97,9 @@ def _track(y: float, clip: str, fills: list[tuple[float, float, str]]) -> list[s def render(levels: Mapping[SupportLevel, int], coverage: ComCoverage) -> str: """The progress image. + Deprecated tools are left out of the headline count and the bar (each + has a replacement in the bar already) and shown in the legend. + Args: levels: How many tools have each support level. coverage: COM coverage of the core interfaces and the whole API. @@ -102,7 +107,7 @@ def render(levels: Mapping[SupportLevel, int], coverage: ComCoverage) -> str: Returns: str: The SVG document. """ - total = sum(levels.values()) + total = sum(levels.values()) - levels.get(SupportLevel.DEPRECATED, 0) y_tools, y_com = 54, 156 out = [ f' None: "get_mass_properties", # Additional analysis operations "calculate_mass_properties", - "get_material_properties", - "analyze_geometry", "check_interference", # Drawing analysis operations - "analyze_drawing_comprehensive", - "analyze_drawing_dimensions", - "analyze_drawing_views", - "analyze_drawing_annotations", - "check_drawing_compliance", "check_drawing_standards", "compare_drawing_versions", # Modeling operations that benefit from routing @@ -536,15 +529,12 @@ async def list_capabilities() -> dict[str, list[str]]: "add_section_view", "add_detail_view", "add_dimension_to_view", - "add_annotation", "create_drawing_template", ], "analysis": [ "get_mass_properties", "perform_fea_analysis", "check_interference", - "analyze_geometry", - "get_material_properties", ], "export": [ "export_step", @@ -553,7 +543,6 @@ async def list_capabilities() -> dict[str, list[str]]: "export_pdf", "export_dwg", "export_images", - "batch_export", ], "automation": [ "generate_vba_macro", diff --git a/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md b/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md index 00fc4fd0..733d2845 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/SKILL.md @@ -39,7 +39,7 @@ A solid feature always comes from a closed sketch: 6. Then edge treatments: `select_face_edges`, then `add_fillet` or `add_chamfer` with empty `edge_names`. 7. Finish with `verify_model` (see "Check the result"). -8. `set_material`, then `save_part` with a `file_path`. +8. `set_material`, then `save_file` with a `file_path`. Repeat 2-5 for each feature. For holes in a ring or a row, draw every circle in one sketch (`sketch_circular_pattern`, `sketch_linear_pattern`) @@ -61,7 +61,7 @@ Details and the model axes: [references/selection-and-units.md](references/selec - To treat the edges of one face, use `select_face_edges` (by `side`, a `point` in mm, or a `plane`), then `add_fillet` or `add_chamfer` with empty `edge_names`. Do it right before the fillet: anything that rebuilds or - selects in between (including `calculate_mass_properties`) clears the + selects in between (including `get_mass_properties`) clears the selection. - If the user says "this face" or "these edges", call `get_selected_entities` to read what they clicked rather than guessing. diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md b/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md index 9a86f8ed..bd28e16a 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md @@ -35,13 +35,28 @@ it will again. ## Tools that can't run yet -40 tools are registered but nothing implements them (support level +Seven tools are registered but nothing implements them yet (support level `planned`). Their description says "Not available yet"; every call returns -`not_supported`. They are -mostly batch, template, macro-recording and drawing-analysis tools, plus -`tutorial_simple_hole`, `add_dimension`, `create_section_view`, `create_detail_view`, -`update_title_block`, `analyze_geometry`, `get_material_properties` and -`batch_export`. Each description names what to use today. +`not_supported`. All seven are drawing tools coming in the drawing pack: +`add_dimension`, `auto_dimension_view`, `create_section_view`, +`create_detail_view`, `update_title_block`, `update_sheet_format` and +`check_drawing_standards`. Each +description names what to use today. + +## Deprecated tools + +Eight tools still work but are replaced; use the replacement. A deprecated +tool's description and successful result start "Deprecated: use ``.", +and it goes at the next major release. + +| Deprecated | Use | +| --- | --- | +| `load_part`, `load_assembly` | `open_model` | +| `save_part`, `save_assembly` | `save_file` (`pack_and_go_assembly` to copy an assembly with its parts) | +| `calculate_mass_properties` | `get_mass_properties` | +| `get_file_properties` | `get_model_info` | +| `add_drawing_view` | `create_drawing_view` | +| `sketch_tutorial_simple_hole` | the sketching and feature tools; it has no replacement | ## Known faults and how to work around them diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/selection-and-units.md b/src/solidworks_mcp/skills/solidworks-mcp/references/selection-and-units.md index 9c0f005a..1c813b2a 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/selection-and-units.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/selection-and-units.md @@ -19,7 +19,7 @@ the sketch tools. `get_selected_entities` reports in mm (`center_mm`, angle dimension. `set_units` changes what the document shows, not what the tools take. -Mass is in kg, volume in mm³. `calculate_mass_properties` returns moments +Mass is in kg, volume in mm³. `get_mass_properties` returns moments of inertia in kg·mm², about the centre of mass. ## Planes and model axes @@ -53,7 +53,7 @@ In order of reliability: pick a different edge. Selection is fragile: anything that selects or rebuilds in between clears -it, including `calculate_mass_properties`, `rebuild_model`, +it, including `get_mass_properties`, `rebuild_model`, `measure_entities`, and `verify_model` when it checks `mass_kg`. Select immediately before the tool that uses it. `select_feature` selects a feature, sketch, plane or component by name, for diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md index b40385f8..11090719 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/workflows.md @@ -24,7 +24,7 @@ step. Values are examples; sizes are millimetres. `solid_body_count: 1`, `feature_count: 3`, and a `volume_mm3` with a `relative_tolerance` wide enough for the fillets. 10. `set_material` (find the exact name with `list_available_materials`), - then `save_part` with a `file_path` ending in `.sldprt`. + then `save_file` with a `file_path` ending in `.sldprt`. ## Sketching somewhere other than the three planes @@ -82,7 +82,7 @@ To turn a feature off without deleting it, `suppress_feature`. After ## An assembly -1. Save each part first (`save_part`): `insert_component` takes a file path. +1. Save each part first (`save_file`): `insert_component` takes a file path. 2. `create_assembly`, then `insert_component` for each part, with a position in mm. 3. `list_components` for the instance names (e.g. "plate-1"). @@ -96,7 +96,7 @@ To turn a feature off without deleting it, `suppress_feature`. After mates move in the main assembly (a crank that turns), `flexible: true`. 5. `check_interference`, then `verify_model` with `component_count`, `mate_count` and `no_interference: true`. -6. `save_assembly`, or `pack_and_go_assembly` for a self-contained folder. +6. `save_file`, or `pack_and_go_assembly` for a self-contained folder. ## A drawing diff --git a/src/solidworks_mcp/tools/analysis.py b/src/solidworks_mcp/tools/analysis.py index f91db70c..f22fd18a 100644 --- a/src/solidworks_mcp/tools/analysis.py +++ b/src/solidworks_mcp/tools/analysis.py @@ -1,8 +1,7 @@ """Analysis tools for SolidWorks MCP Server. Use these after a model or assembly already exists. Recommended order: -calculate_mass_properties or get_mass_properties, then check_interference, then -analyze_geometry, then get_material_properties. These tools are for validation and +get_mass_properties, then check_interference. These tools are for validation and inspection, not for creating geometry. verify_model checks the finished model against expected values in one call. """ @@ -65,22 +64,6 @@ class InterferenceCheckInput(CompatInput): ) -class GeometryAnalysisInput(BaseModel): - """Input schema for geometry analysis. - - Attributes: - analysis_type (str): The analysis type value. - parameters (dict[str, Any] | None): The parameters value. - """ - - analysis_type: str = Field( - description="Type of analysis (curvature, draft, thickness, etc.)" - ) - parameters: dict[str, Any] | None = Field( - default=None, description="Analysis-specific parameters" - ) - - class VerifyModelInput(BaseModel): """Expectations for ``verify_model``; every field is optional. @@ -317,25 +300,14 @@ async def register_analysis_tools( mcp = with_tool_boundary(mcp) tool_count = 0 - @mcp.tool() - async def calculate_mass_properties( - input_data: MassPropertiesInput, - ) -> dict[str, Any]: - """Measure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. - - Use it to check weight or balance. To compare a model with the values you - expect, use `verify_model`; `get_mass_properties` does the same as this tool. - Mass depends on the assigned material (`set_material`). Needs: an open part or - assembly. Read-only. It rebuilds first. Returns: `mass_properties` with `volume` - (mm³), `surface_area` (mm²), `mass` (kg), `center_of_mass` (mm), - `moments_of_inertia` (kg·mm², about the centre of mass) and - `principal_axes`. + async def _measure_mass() -> dict[str, Any]: + """The active model's mass properties, as both mass tools return them. - Args: - input_data: Nothing: it always measures the active model. + A plain function, not a tool, so ``get_mass_properties`` doesn't carry + the deprecated ``calculate_mass_properties``'s warning. Returns: - dict[str, Any]: The mass properties. + dict[str, Any]: The success reply. """ result = await adapter.get_mass_properties() @@ -373,8 +345,8 @@ async def get_mass_properties( ) -> dict[str, Any]: """Measure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. - The same as `calculate_mass_properties`, which it calls. To compare a model with - the values you expect, use `verify_model`. Mass depends on the assigned material + Use it to check weight or balance. To compare a model with the values you + expect, use `verify_model`. Mass depends on the assigned material (`set_material`). Needs: an open part or assembly. Read-only. It rebuilds first. Returns: `mass_properties` with `volume` (mm³), `surface_area` (mm²), `mass` (kg), `center_of_mass` (mm), `moments_of_inertia` (kg·mm², about the centre @@ -386,7 +358,26 @@ async def get_mass_properties( Returns: dict[str, Any]: The mass properties. """ - return await calculate_mass_properties(input_data or MassPropertiesInput()) + return await _measure_mass() + + @mcp.tool() + async def calculate_mass_properties( + input_data: MassPropertiesInput, + ) -> dict[str, Any]: + """Measure the active part or assembly's mass properties (the old name of `get_mass_properties`). + + It returns exactly what `get_mass_properties` returns; use that instead. Needs: + an open part or assembly. Read-only. It rebuilds first. Returns: + `mass_properties` with `volume` (mm³), `surface_area` (mm²), `mass` (kg), + `center_of_mass` (mm), `moments_of_inertia` (kg·mm²) and `principal_axes`. + + Args: + input_data: Nothing: it always measures the active model. + + Returns: + dict[str, Any]: The mass properties. + """ + return await _measure_mass() @mcp.tool() async def check_interference(input_data: InterferenceCheckInput) -> dict[str, Any]: @@ -425,62 +416,6 @@ async def check_interference(input_data: InterferenceCheckInput) -> dict[str, An "execution_time": result.execution_time, } - @mcp.tool() - async def analyze_geometry(input_data: GeometryAnalysisInput) -> dict[str, Any]: - """Run a geometry analysis on the active model, such as curvature, draft or wall thickness. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. For distances - and angles today, use `measure_entities`; for size and volume, use - `verify_model` or `calculate_mass_properties`. Read-only. Returns: once - available, the analysis under `data`. - - Args: - input_data: The analysis. `analysis_type` (e.g. curvature, draft, - thickness) is required; `parameters` has a default. - - Returns: - dict[str, Any]: The analysis, or a `not_supported` error. - """ - require_capability( - adapter, - "analyze_geometry", - f"Active adapter does not support analyze_geometry; no " - f"{input_data.analysis_type} analysis was performed.", - ) - result = await adapter.analyze_geometry(input_data.model_dump()) - require_success(result, "Failed to analyze geometry") - return { - "status": "success", - "message": f"Geometry analysis ({input_data.analysis_type}) completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def get_material_properties() -> dict[str, Any]: - """Report the physical properties of the active part's material: density, modulus, Poisson's ratio, strength. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. For the - material's name today, use `get_material`; for the materials you can assign, use - `list_available_materials`. Read-only. Returns: once available, the properties - under `data`. - """ - require_capability( - adapter, - "get_material_properties", - "Active adapter does not support get_material_properties", - ) - result = await adapter.get_material_properties() - require_success(result, "Failed to get material properties") - return { - "status": "success", - "message": "Material properties retrieved successfully", - "data": result.data, - "execution_time": result.execution_time, - } - @mcp.tool() async def verify_model( input_data: VerifyModelInput | dict[str, Any] | None = None, @@ -643,5 +578,5 @@ async def verify_model( # - vibration_analysis # - stress_concentration_analysis - tool_count = 4 # Keep legacy reported count expected by tests + tool_count = 4 return tool_count diff --git a/src/solidworks_mcp/tools/automation.py b/src/solidworks_mcp/tools/automation.py index d11bae5b..f4bee81e 100644 --- a/src/solidworks_mcp/tools/automation.py +++ b/src/solidworks_mcp/tools/automation.py @@ -1,10 +1,7 @@ """Automation tools for SolidWorks MCP Server. -Use these when the workflow is already defined and you need repeatable execution. -Recommended order: generate_vba_code for complex steps, record or stop a macro when a -manual flow should be captured, batch_process_files for many files, manage_design_table -for configuration-driven variants, execute_workflow for scripted pipelines, -create_template for reusable standards, and optimize_performance for tuning. +``generate_vba_code`` writes a VBA macro skeleton for a step the tools don't +cover. """ import re @@ -16,9 +13,6 @@ from ..adapters.base import SolidWorksAdapter from .input_compat import CompatInput from .tool_boundary import ( - UnsupportedOperationError, - require_capability, - require_success, with_tool_boundary, ) @@ -83,205 +77,6 @@ def model_post_init(self, __context: Any) -> None: VBAGenerationInput = GenerateVBAInput -class RecordMacroInput(CompatInput): - """Input schema for macro recording. - - Attributes: - auto_start (bool): The auto start value. - capture_keyboard (bool): The capture keyboard value. - capture_mouse (bool): The capture mouse value. - description (str): The description value. - macro_name (str | None): The macro name value. - output_file (str | None): The output file value. - recording_mode (str | None): The recording mode value. - recording_name (str | None): The recording name value. - """ - - macro_name: str | None = Field( - default=None, description="Name for the recorded macro" - ) - recording_name: str | None = Field(default=None, description="Recording name alias") - output_file: str | None = Field(default=None, description="Output file alias") - recording_mode: str | None = Field(default=None, description="Recording mode alias") - capture_mouse: bool = Field(default=True, description="Capture mouse actions") - capture_keyboard: bool = Field(default=True, description="Capture keyboard actions") - description: str = Field( - default="", description="Description of the macro functionality" - ) - auto_start: bool = Field(default=True, description="Automatically start recording") - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the record macro input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.macro_name is None: - self.macro_name = self.recording_name or "Recorded Macro" - - -class BatchProcessInput(CompatInput): - """Input schema for batch processing. - - Attributes: - batch_operation (str | None): The batch operation value. - file_pattern (str | None): The file pattern value. - filter_patterns (list[str]): The filter patterns value. - operation (str | None): The operation value. - operation_type (str | None): The operation type value. - parallel_processing (bool): The parallel processing value. - recursive (bool): The recursive value. - source_directory (str): The source directory value. - target_format (str | None): The target format value. - """ - - source_directory: str = Field(description="Directory containing SolidWorks files") - operation_type: str | None = Field( - default=None, - description="Type of operation (rebuild, save_as, export, update_properties)", - ) - batch_operation: str | None = Field( - default=None, description="Batch operation alias" - ) - target_format: str | None = Field( - default=None, description="Target format for export operations" - ) - file_pattern: str | None = Field(default=None, description="File pattern alias") - parallel_processing: bool = Field( - default=False, description="Parallel processing alias" - ) - operation: str | None = Field(default=None, description="Operation alias") - recursive: bool = Field( - default=False, description="Process subdirectories recursively" - ) - filter_patterns: list[str] = Field( - default=["*.sldprt", "*.sldasm"], description="File patterns to process" - ) - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the batch process input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.operation_type is None: - self.operation_type = self.batch_operation or self.operation or "export" - - -class DesignTableInput(CompatInput): - """Input schema for design table operations. - - Attributes: - auto_create_configurations (bool): The auto create configurations value. - auto_update (bool): The auto update value. - configurations (list[str]): The configurations value. - create_configurations (bool): The create configurations value. - excel_file (str | None): The excel file value. - model_path (str | None): The model path value. - operation (str | None): The operation value. - parameters (list[str]): The parameters value. - table_file (str | None): The table file value. - table_type (str | None): The table type value. - """ - - table_type: str | None = Field( - default=None, description="Type of design table (create, update, import)" - ) - model_path: str | None = Field(default=None, description="Model path alias") - table_file: str | None = Field(default=None, description="Design table file alias") - operation: str | None = Field(default=None, description="Operation alias") - auto_update: bool = Field(default=False, description="Auto update alias") - create_configurations: bool = Field( - default=False, description="Create configurations alias" - ) - auto_create_configurations: bool = Field( - default=False, description="Auto-create alias" - ) - excel_file: str | None = Field( - default=None, description="Excel file path for import/export" - ) - parameters: list[str] = Field( - default=[], description="Parameters to include in design table" - ) - configurations: list[str] = Field(default=[], description="Configuration names") - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the design table input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.table_type is None: - self.table_type = self.operation or "create" - if self.create_configurations: - self.auto_create_configurations = True - - -class WorkflowInput(CompatInput): - """Input schema for workflow automation. - - Attributes: - error_handling (str): The error handling value. - parallel_execution (bool): The parallel execution value. - steps (list[dict[str, Any]]): The steps value. - workflow_name (str): The workflow name value. - """ - - workflow_name: str = Field(description="Name of the workflow") - steps: list[dict[str, Any]] = Field(description="List of workflow steps") - parallel_execution: bool = Field( - default=False, description="Execute compatible steps in parallel" - ) - error_handling: str = Field( - default="stop", description="Error handling strategy (stop, skip, retry)" - ) - - -class TemplateInput(CompatInput): - """Input schema for template operations. - - Attributes: - base_file (str | None): The base file value. - include_custom_properties (bool): The include custom properties value. - include_features (list[str]): The include features value. - include_materials (bool): The include materials value. - metadata (dict[str, Any]): The metadata value. - output_path (str | None): The output path value. - source_model (str | None): The source model value. - template_name (str): The template name value. - template_type (str): The template type value. - """ - - template_type: str = Field(description="Type of template (part, assembly, drawing)") - template_name: str = Field(description="Name for the template") - base_file: str | None = Field( - default=None, description="Base file to create template from" - ) - source_model: str | None = Field(default=None, description="Source model alias") - output_path: str | None = Field(default=None, description="Output path alias") - include_custom_properties: bool = Field( - default=False, description="Include custom properties alias" - ) - include_materials: bool = Field( - default=False, description="Include materials alias" - ) - include_features: list[str] = Field( - default_factory=list, description="Include features alias" - ) - metadata: dict[str, Any] = Field( - default={}, description="Template metadata and properties" - ) - - #: ``swDocumentTypes_e``: the value ``IModelDoc2.GetType`` returns for each #: document type a macro can be written for. _VBA_DOC_TYPES = {"Part": 1, "Assembly": 2, "Drawing": 3} @@ -438,236 +233,5 @@ async def generate_vba_code(input_data: GenerateVBAInput) -> dict[str, Any]: }, } - @mcp.tool(name="automation_start_macro_recording") - async def start_macro_recording(input_data: RecordMacroInput) -> dict[str, Any]: - """Start SolidWorks' macro recorder (the automation family's copy of `start_macro_recording`). - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Recording is - done in SolidWorks today (Tools > Macro > Record). Changes: once available, - starts a recording session. Returns: once available, the session details under - `data`. - - Args: - input_data: The recording. Nothing is required: `macro_name`, - `output_file`, `recording_mode` and the capture switches have - defaults. - - Returns: - dict[str, Any]: The session, or a `not_supported` error. - """ - require_capability( - adapter, - "start_macro_recording", - "Active adapter does not support start_macro_recording; " - f"no recording of {input_data.macro_name} was started.", - ) - result = await adapter.start_macro_recording(input_data.model_dump()) - require_success(result, "Failed to start macro recording") - return { - "status": "success", - "message": f"Started recording macro: {input_data.macro_name}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool(name="automation_stop_macro_recording") - async def stop_macro_recording(input_data: dict[str, Any]) -> dict[str, Any]: - """Stop a macro recording and save it (the automation family's copy of `stop_macro_recording`). - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Recording is - done in SolidWorks today (Tools > Macro > Stop). Changes: once available, ends - the session and writes the macro file. Returns: once available, the saved - macro's details. - - Args: - input_data: A mapping; nothing in it is used yet. - - Returns: - dict[str, Any]: A `not_supported` error. - """ - raise UnsupportedOperationError( - "No adapter capability exists for stopping a macro " - "recording; this tool never started a real recording " - "session, so there is nothing to stop or save." - ) - - @mcp.tool() - async def batch_process_files(input_data: BatchProcessInput) -> dict[str, Any]: - """Run one operation (rebuild, save as, export or property update) on every matching file in a folder. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To export - several files today, open each with `open_model` and use `export_step`. - Changes: once available, opens, changes and saves each file. Returns: once available, a per-file result under `data`. - - Args: - input_data: The batch. `source_directory` is required; `operation_type`, - `file_pattern`, `target_format` and `recursive` have defaults. - - Returns: - dict[str, Any]: The results, or a `not_supported` error. - """ - require_capability( - adapter, - "batch_process_files", - "Active adapter does not support batch_process_files; no " - f"files in {input_data.source_directory} were processed.", - ) - result = await adapter.batch_process_files(input_data.model_dump()) - require_success(result, "Batch processing failed") - return { - "status": "success", - "message": f"Batch {input_data.operation_type} completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def manage_design_table(input_data: DesignTableInput) -> dict[str, Any]: - """Create, read or update a design table (an Excel sheet that drives a model's configurations). - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To list a - model's configurations today, use `list_configurations`. Changes: once - available, inserts or edits the design table and its configurations. Returns: - once available, the table's state under `data`. - - Args: - input_data: The design table. Nothing is required: give `model_path`, - `operation` and `excel_file`; `parameters`, `configurations` and the - auto-update switches have defaults. - - Returns: - dict[str, Any]: The result, or a `not_supported` error. - """ - require_capability( - adapter, - "manage_design_table", - "Active adapter does not support manage_design_table; no " - f"{input_data.table_type} operation was performed.", - ) - result = await adapter.manage_design_table(input_data.model_dump()) - require_success(result, "Design table management failed") - return { - "status": "success", - "message": f"Design table {input_data.table_type} completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def execute_workflow(input_data: WorkflowInput) -> dict[str, Any]: - """Run a named sequence of tool steps, in order or in parallel, with an error policy. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Call the - tools one at a time instead. Changes: once available, whatever the steps change. - Returns: once available, each step's result under `data`. - - Args: - input_data: The workflow. `workflow_name` and `steps` (a list of step - mappings) are required; `parallel_execution` and `error_handling` - have defaults. - - Returns: - dict[str, Any]: The step results, or a `not_supported` error. - """ - require_capability( - adapter, - "execute_workflow", - "Active adapter does not support execute_workflow; " - f"workflow '{input_data.workflow_name}' was not run.", - ) - result = await adapter.execute_workflow(input_data.model_dump()) - require_success(result, "Workflow execution failed") - return { - "status": "success", - "message": f"Workflow '{input_data.workflow_name}' completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def create_template(input_data: TemplateInput) -> dict[str, Any]: - """Create a part, assembly or drawing template file (.prtdot, .asmdot, .drwdot) with standard settings. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To capture an - existing model's settings, `extract_template` is also not available yet. - Changes: once available, writes the template file. Returns: once available, the - template's path and settings under `data`. - - Args: - input_data: The template. `template_type` and `template_name` are - required; `source_model`, `output_path` and the include switches have - defaults. - - Returns: - dict[str, Any]: The template, or a `not_supported` error. - """ - require_capability( - adapter, - "create_template", - "Active adapter does not support create_template; no " - f"{input_data.template_type} template " - f"'{input_data.template_name}' was created.", - ) - result = await adapter.create_template(input_data.model_dump()) - require_success(result, "Template creation failed") - return { - "status": "success", - "message": f"Created {input_data.template_type} template: {input_data.template_name}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def optimize_performance(input_data: dict[str, Any]) -> dict[str, Any]: - """Review SolidWorks' performance settings and apply faster ones. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Changes: once - available, SolidWorks system options. Returns: once available, the settings - changed under `data`. - - Args: - input_data: A mapping of optimisation options; none is required. - - Returns: - dict[str, Any]: The changes, or a `not_supported` error. - """ - require_capability( - adapter, - "optimize_performance", - "Active adapter does not support optimize_performance; " - "no settings were analyzed or changed.", - ) - result = await adapter.optimize_performance(input_data) - require_success(result, "Performance optimization failed") - return { - "status": "success", - "message": "Performance optimization completed", - "data": result.data, - "execution_time": result.execution_time, - } - - tool_count = 8 # Number of tools registered + tool_count = 1 # generate_vba_code return tool_count - - -class PerformanceOptimizationInput(CompatInput): - """Input schema for performance optimization. - - Attributes: - optimization_type (str): The optimization type value. - parameters (dict[str, Any]): The parameters value. - target_metric (str): The target metric value. - """ - - optimization_type: str = Field(description="Type of optimization to perform") - target_metric: str = Field(default="speed", description="Target performance metric") - parameters: dict[str, Any] = Field( - default={}, description="Optimization parameters" - ) diff --git a/src/solidworks_mcp/tools/drawing.py b/src/solidworks_mcp/tools/drawing.py index 71d5eb55..78135952 100644 --- a/src/solidworks_mcp/tools/drawing.py +++ b/src/solidworks_mcp/tools/drawing.py @@ -293,63 +293,6 @@ def model_post_init(self, __context: Any) -> None: self.position_y = float(self.position[1]) -class AnnotationInput(CompatInput): - """Input schema for annotation operations. - - Attributes: - annotation_type (str): The annotation type value. - approved_by (str): The approved by value. - checked_by (str): The checked by value. - drawing_number (str): The drawing number value. - drawing_path (str | None): The drawing path value. - drawn_by (str): The drawn by value. - font_size (float): The font size value. - leader_attachment (str | None): The leader attachment value. - position (list[float] | None): The position value. - position_x (float | None): The position x value. - position_y (float | None): The position y value. - text (str): The text value. - """ - - drawing_path: str | None = Field(default=None, description="Path to drawing file") - annotation_type: str = Field( - description="Type of annotation (note, balloon, surface_finish, etc.)" - ) - text: str = Field(description="Annotation text content") - position_x: float | None = Field( - default=None, description="X position for annotation" - ) - position_y: float | None = Field( - default=None, description="Y position for annotation" - ) - position: list[float] | None = Field( - default=None, description="Annotation position" - ) - font_size: float = Field(default=12.0, description="Font size in points") - leader_attachment: str | None = Field( - default=None, description="Entity to attach leader line to" - ) - drawn_by: str = Field(default="", description="Drawn by field") - checked_by: str = Field(default="", description="Checked by field") - approved_by: str = Field(default="", description="Approved by field") - drawing_number: str = Field(default="", description="Drawing number") - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the annotation input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.position is not None and len(self.position) >= 2: - if self.position_x is None: - self.position_x = float(self.position[0]) - if self.position_y is None: - self.position_y = float(self.position[1]) - - async def register_drawing_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: dict[str, Any] ) -> int: @@ -384,7 +327,7 @@ async def create_drawing_view(input_data: CreateDrawingViewInput) -> dict[str, A Use it to add views one at a time; for the three standard views in one call, use `create_technical_drawing`, and for a whole drawing from a model, use - `generate_drawing_package`. `add_drawing_view` does the same as this tool. + `generate_drawing_package`. Needs: an open, active drawing and the model file on disk. Changes: adds a view to the sheet. Returns: `data` with the view's `name`, `orientation`, `position`, `scale` and the view counts before and after. @@ -684,37 +627,6 @@ async def add_drawing_view(input_data: DrawingViewInput) -> dict[str, Any]: "execution_time": result.execution_time, } - @mcp.tool() - async def add_annotation(input_data: AnnotationInput) -> dict[str, Any]: - """Add an annotation (a note, balloon or surface-finish symbol) to the active drawing. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. For a text - note today, use `add_note`; for GD&T, use `add_gtol` and `add_datum_tag`. - Changes: once available, adds the annotation. Returns: once available, the - annotation under `data`. - - Args: - input_data: The annotation. `annotation_type` and `text` are required; - the position and font fields have defaults. - - Returns: - dict[str, Any]: The annotation, or a `not_supported` error. - """ - require_capability( - adapter, - "add_annotation", - "Active adapter does not support add_annotation; no annotation was added.", - ) - result = await adapter.add_annotation(input_data.model_dump()) - require_success(result, "Failed to add annotation") - return { - "status": "success", - "message": "Annotation added successfully", - "data": result.data, - "execution_time": result.execution_time, - } - @mcp.tool() async def update_title_block(input_data: dict[str, Any]) -> dict[str, Any]: """Fill in the active drawing's title-block fields (title, drawn by, drawing number and so on). @@ -816,5 +728,5 @@ async def auto_center_marks( "execution_time": result.execution_time, } - tool_count = 14 # Number of tools registered + tool_count = 13 # Number of tools registered return tool_count diff --git a/src/solidworks_mcp/tools/drawing_analysis.py b/src/solidworks_mcp/tools/drawing_analysis.py index f5f99ccf..f9e35ccb 100644 --- a/src/solidworks_mcp/tools/drawing_analysis.py +++ b/src/solidworks_mcp/tools/drawing_analysis.py @@ -1,7 +1,8 @@ """Advanced Drawing Analysis tools for SolidWorks MCP Server. -Provides advanced analysis capabilities for drawing documents including dimension -analysis, view analysis, annotation checking, and compliance verification. +Provides ``compare_drawing_versions``, which compares two drawing files on disk. +The drawing check that reads a drawing's contents is planned in queue item 12 +(``check_drawing``). """ from typing import Any @@ -14,111 +15,13 @@ from .input_compat import CompatInput from .tool_boundary import ( ToolOperationError, - UnsupportedOperationError, normalize_input, - require_capability, - require_success, with_tool_boundary, ) # Input schemas for drawing analysis -class DrawingAnalysisInput(CompatInput): - """Input schema for drawing analysis operations. - - Attributes: - analysis_depth (str): The analysis depth value. - analysis_type (str): The analysis type value. - drawing_path (str): The drawing path value. - generate_report (bool): The generate report value. - standards_check (bool): The standards check value. - """ - - drawing_path: str = Field(description="Path to drawing file (.slddrw)") - analysis_type: str = Field( - default="comprehensive", - description="Analysis type (comprehensive, dimensions, views, annotations)", - ) - analysis_depth: str = Field(default="Basic", description="Analysis depth level") - standards_check: bool = Field( - default=True, description="Check against drafting standards" - ) - generate_report: bool = Field(default=True, description="Generate detailed report") - - -class DimensionAnalysisInput(CompatInput): - """Input schema for dimension analysis. - - Attributes: - check_completeness (bool): The check completeness value. - check_precision (bool): The check precision value. - check_tolerances (bool): The check tolerances value. - drawing_path (str): The drawing path value. - """ - - drawing_path: str = Field(description="Path to drawing file") - check_precision: bool = Field( - default=True, description="Check dimension precision consistency" - ) - check_tolerances: bool = Field( - default=True, description="Check tolerance formatting" - ) - check_completeness: bool = Field( - default=True, description="Check dimension completeness" - ) - - -class AnnotationAnalysisInput(CompatInput): - """Input schema for annotation analysis. - - Attributes: - check_annotations (bool): The check annotations value. - check_notes (bool): The check notes value. - check_symbols (bool): The check symbols value. - check_text_styles (bool): The check text styles value. - drawing_path (str): The drawing path value. - """ - - drawing_path: str = Field(description="Path to drawing file") - check_notes: bool = Field( - default=True, description="Check note formatting and content" - ) - check_symbols: bool = Field( - default=True, description="Check symbol usage and placement" - ) - check_text_styles: bool = Field( - default=True, description="Check text style consistency" - ) - check_annotations: bool = Field(default=True, description="Alias used by tests") - - -class ComplianceCheckInput(CompatInput): - """Input schema for standards compliance checking. - - Attributes: - check_sheet_format (bool): The check sheet format value. - check_title_block (bool): The check title block value. - drawing_path (str): The drawing path value. - standard (str): The standard value. - standards_to_check (list[str]): The standards to check value. - """ - - drawing_path: str = Field(description="Path to drawing file") - standard: str = Field( - default="ISO", description="Standard to check against (ISO, ANSI, DIN)" - ) - standards_to_check: list[str] = Field( - default_factory=lambda: ["ISO"], description="Standards list alias" - ) - check_title_block: bool = Field( - default=True, description="Check title block compliance" - ) - check_sheet_format: bool = Field( - default=True, description="Check sheet format compliance" - ) - - class DrawingVersionsInput(CompatInput): """Input schema for comparing two saved versions of a drawing. @@ -154,206 +57,6 @@ async def register_drawing_analysis_tools( mcp = with_tool_boundary(mcp) tool_count = 0 - @mcp.tool() - async def analyze_drawing_comprehensive( - input_data: DrawingAnalysisInput, - ) -> dict[str, Any]: - """Run every drawing check (dimensions, views, annotations, standards) on a drawing file in one call. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To see what a - drawing holds today, use `list_drawing_views`. Read-only. Returns: once - available, the combined findings under `data`. - - Args: - input_data: The drawing to check. `drawing_path` (.slddrw) is required; - `analysis_type`, `analysis_depth`, `standards_check` and - `generate_report` have defaults. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - require_capability( - adapter, - "analyze_drawing_comprehensive", - "Active adapter does not support " - "analyze_drawing_comprehensive; no analysis of " - f"{input_data.drawing_path} was performed.", - ) - result = await adapter.analyze_drawing_comprehensive(input_data.model_dump()) - require_success(result, "Failed to analyze drawing") - return { - "status": "success", - "message": "Comprehensive drawing analysis completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def analyze_drawing_dimensions( - input_data: DimensionAnalysisInput, - ) -> dict[str, Any]: - """Check a drawing's dimensions for consistent precision, tolerance formatting and completeness. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To bring the - model's dimensions into a drawing, use `insert_model_dimensions`. Read-only. - Returns: once available, the dimension findings under `data`. - - Args: - input_data: The drawing to check. `drawing_path` is required; the - `check_precision`, `check_tolerances` and `check_completeness` - switches default to on. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - require_capability( - adapter, - "analyze_drawing_dimensions", - "Active adapter does not support analyze_drawing_dimensions; " - f"no analysis of {input_data.drawing_path} was performed.", - ) - result = await adapter.analyze_drawing_dimensions(input_data.model_dump()) - require_success(result, "Failed to analyze dimensions") - return { - "status": "success", - "message": "Dimension analysis completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def analyze_drawing_annotations( - input_data: AnnotationAnalysisInput, - ) -> dict[str, Any]: - """Check a drawing's notes, symbols and text styles for consistency. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. - Returns: once available, the annotation findings under `data`. - - Args: - input_data: The drawing to check. `drawing_path` is required; the - `check_notes`, `check_symbols`, `check_text_styles` and - `check_annotations` switches default to on. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - require_capability( - adapter, - "analyze_drawing_annotations", - "Active adapter does not support analyze_drawing_annotations; " - f"no analysis of {input_data.drawing_path} was performed.", - ) - result = await adapter.analyze_drawing_annotations(input_data.model_dump()) - require_success(result, "Failed to analyze annotations") - return { - "status": "success", - "message": "Annotation analysis completed", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def check_drawing_compliance( - input_data: ComplianceCheckInput, - ) -> dict[str, Any]: - """Check a drawing's title block and sheet format against a drafting standard (ISO, ANSI or DIN). - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. For the same - check on the active drawing, `check_drawing_standards` is also not available - yet. Read-only. Returns: once available, the compliance findings under `data`. - - Args: - input_data: The drawing and standard. `drawing_path` is required; - `standard` defaults to "ISO", and `check_title_block` and - `check_sheet_format` default to on. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - require_capability( - adapter, - "check_drawing_compliance", - "Active adapter does not support check_drawing_compliance; " - f"no {input_data.standard} compliance check was performed.", - ) - result = await adapter.check_drawing_compliance(input_data.model_dump()) - require_success(result, "Compliance check failed") - return { - "status": "success", - "message": f"Standards compliance check completed for {input_data.standard}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def analyze_drawing_views(input_data: dict[str, Any]) -> dict[str, Any]: - """Check how a drawing's views are chosen and laid out. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To list the - views on the active drawing today, use `list_drawing_views`. Read-only. Returns: - once available, the view findings under `data`. - - Args: - input_data: A mapping with the `drawing_path` of the drawing to check. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - if hasattr(adapter, "analyze_drawing_views"): - result = await adapter.analyze_drawing_views(input_data) - require_success(result, "Failed to analyze drawing views") - return { - "status": "success", - "message": "Drawing view analysis completed", - "data": result.data, - "execution_time": result.execution_time, - } - - drawing_path = input_data.get("drawing_path", "") - - raise UnsupportedOperationError( - "Active adapter does not support analyze_drawing_views; " - f"no analysis of {drawing_path} was performed." - ) - - @mcp.tool() - async def generate_drawing_report(input_data: dict[str, Any]) -> dict[str, Any]: - """Write a quality report that combines every drawing check. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. - Returns: once available, the report under `data`. - - Args: - input_data: A mapping with the `drawing_path` of the drawing to report - on. - - Returns: - dict[str, Any]: The report, or a `not_supported` error. - """ - if hasattr(adapter, "generate_drawing_report"): - result = await adapter.generate_drawing_report(input_data) - require_success(result, "Failed to generate drawing report") - return { - "status": "success", - "message": "Drawing quality report generated successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - drawing_path = input_data.get("drawing_path", "") - - raise UnsupportedOperationError( - "Active adapter does not support generate_drawing_report; " - f"no report for {drawing_path} was generated." - ) - @mcp.tool() async def compare_drawing_versions( input_data: DrawingVersionsInput, @@ -418,39 +121,5 @@ async def compare_drawing_versions( ), } - @mcp.tool() - async def validate_drawing_completeness( - input_data: dict[str, Any], - ) -> dict[str, Any]: - """Check that a drawing carries everything needed to manufacture the part. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. - Returns: once available, the missing items under `data`. - - Args: - input_data: A mapping with the `drawing_path` of the drawing to check. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - drawing_path = input_data.get("drawing_path", "") - - require_capability( - adapter, - "validate_drawing_completeness", - "Active adapter does not support " - "validate_drawing_completeness; no validation of " - f"{drawing_path} was performed.", - ) - result = await adapter.validate_drawing_completeness(input_data) - require_success(result, "Failed to validate completeness") - return { - "status": "success", - "message": "Drawing completeness validation completed", - "data": result.data, - "execution_time": result.execution_time, - } - - tool_count = 8 # Legacy count expected by tests + tool_count = 1 # compare_drawing_versions return tool_count diff --git a/src/solidworks_mcp/tools/engineering_data.py b/src/solidworks_mcp/tools/engineering_data.py index 7cd1e1e0..46829d6f 100644 --- a/src/solidworks_mcp/tools/engineering_data.py +++ b/src/solidworks_mcp/tools/engineering_data.py @@ -267,7 +267,7 @@ async def get_material( ) -> dict[str, Any]: """Report the material assigned to the active part. - Use it before `calculate_mass_properties` or `verify_model` with a mass: without + Use it before `get_mass_properties` or `verify_model` with a mass: without a material SolidWorks uses a default density. Needs: an open, active part (any other document is `wrong_document_type`). Read-only. Returns: `data` with `material` (null when none is assigned), `database` and `density_kg_m3` (from diff --git a/src/solidworks_mcp/tools/export.py b/src/solidworks_mcp/tools/export.py index 40e1cd6f..077e7cc8 100644 --- a/src/solidworks_mcp/tools/export.py +++ b/src/solidworks_mcp/tools/export.py @@ -14,7 +14,6 @@ from .tool_boundary import ( UnsupportedOperationError, normalize_input, - require_capability, require_success, with_tool_boundary, ) @@ -100,55 +99,6 @@ def model_post_init(self, __context: Any) -> None: self.height = int(height) -class BatchExportInput(CompatInput): - """Input schema for batch export operations. - - Attributes: - export_format (str | None): The export format value. - file_pattern (str | None): The file pattern value. - file_patterns (list[str]): The file patterns value. - format_type (str | None): The format type value. - include_subdirectories (bool): The include subdirectories value. - output_directory (str): The output directory value. - recursive (bool): The recursive value. - source_directory (str): The source directory value. - """ - - source_directory: str = Field(description="Directory containing SolidWorks files") - output_directory: str = Field(description="Directory for exported files") - format_type: str | None = Field(default=None, description="Target export format") - export_format: str | None = Field( - default=None, description="Alternative export format" - ) - file_pattern: str | None = Field(default=None, description="File pattern alias") - recursive: bool = Field( - default=False, description="Search subdirectories recursively" - ) - include_subdirectories: bool = Field( - default=False, description="Include subdirectories in search" - ) - file_patterns: list[str] = Field( - default=["*.sldprt", "*.sldasm", "*.slddrw"], - description="File patterns to include", - ) - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the batch export input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.format_type is None: - self.format_type = self.export_format - if self.file_pattern: - self.file_patterns = [self.file_pattern] - if self.include_subdirectories: - self.recursive = True - - def _file_input(input_data: Any, format_type: str) -> Any: """Fill ``format_type`` with the tool's own format when it was left out. @@ -469,37 +419,5 @@ async def export_image(input_data: ExportImageInput) -> dict[str, Any]: "export_file; no image was exported." ) - @mcp.tool() - async def batch_export(input_data: BatchExportInput) -> dict[str, Any]: - """Export every matching SolidWorks file in a folder to one format. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Today, open - each file with `open_model` and use an `export_*` tool. Changes: once available, - writes one exported file per source file. Returns: once available, a per-file - result under `data`. - - Args: - input_data: The batch. `source_directory` and `output_directory` are - required; `format_type`, `file_pattern` and `recursive` have - defaults. - - Returns: - dict[str, Any]: The results, or a `not_supported` error. - """ - require_capability( - adapter, - "batch_export", - "Active adapter does not support batch_export; no files were exported.", - ) - result = await adapter.batch_export(input_data.model_dump()) - require_success(result, "Batch export failed") - return { - "status": "success", - "message": f"Batch export completed to {input_data.format_type} format", - "data": result.data, - "execution_time": result.execution_time, - } - - tool_count = 7 # Number of tools registered + tool_count = 6 # Number of tools registered return tool_count diff --git a/src/solidworks_mcp/tools/file_management.py b/src/solidworks_mcp/tools/file_management.py index ef454cce..89176324 100644 --- a/src/solidworks_mcp/tools/file_management.py +++ b/src/solidworks_mcp/tools/file_management.py @@ -34,13 +34,47 @@ class SaveFileInput(CompatInput): """Input schema for saving a file. Attributes: - file_path (str | None): The file path value. + file_path (str | None): A new path to save to; None saves in place. + overwrite (bool): Whether a file already at ``file_path`` may be replaced. """ file_path: str | None = Field( default=None, - description="Optional output path. If omitted, saves the current active document.", + description=( + "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 = Field( + default=False, + description="Replace a file already at file_path. Off by default.", + ) + + +#: The file extension each document type saves to. +_DOC_EXTENSIONS = {"Part": ".sldprt", "Assembly": ".sldasm", "Drawing": ".slddrw"} + + +def file_details(raw_path: str) -> dict[str, Any]: + """The size and times of the file at ``raw_path``, read from the disk. + + Args: + raw_path: The document's path; empty for a document never saved. + + Returns: + dict[str, Any]: ``size_bytes``, ``created`` and ``modified`` (Unix + timestamps); each None when no file is there. + """ + path = Path(raw_path) if raw_path else None + if path is None or not path.is_file(): + return {"size_bytes": None, "created": None, "modified": None} + stat = path.stat() + return { + "size_bytes": stat.st_size, + "created": stat.st_ctime, + "modified": stat.st_mtime, + } class SaveAsInput(CompatInput): @@ -59,66 +93,6 @@ class SaveAsInput(CompatInput): overwrite: bool = Field(default=False, description="Overwrite existing file") -class FileOperationInput(CompatInput): - """Input schema for file operations. - - Attributes: - file_path (str | None): The file path value. - include_system (bool): The include system value. - operation (str): The operation value. - parameters (dict[str, Any] | None): The parameters value. - properties (dict[str, Any] | None): The properties value. - source_path (str | None): The source path value. - target_path (str | None): The target path value. - """ - - operation: str = Field( - description="Operation to perform (copy, move, delete, rename)" - ) - source_path: str | None = Field(default=None, description="Source file path") - file_path: str | None = Field(default=None, description="Alternative file path") - target_path: str | None = Field( - default=None, description="Target file path (for copy/move/rename)" - ) - properties: dict[str, Any] | None = Field( - default=None, description="File properties to set" - ) - parameters: dict[str, Any] | None = Field( - default=None, description="Operation parameters" - ) - include_system: bool = Field(default=False, description="Include system properties") - - -class FormatConversionInput(CompatInput): - """Input schema for format conversion. - - Attributes: - conversion_options (dict[str, Any] | None): The conversion options value. - invalid_format (str | None): The invalid format value. - output_path (str | None): The output path value. - quality (str): The quality value. - source_file (str): The source file value. - source_format (str | None): The source format value. - target_file (str | None): The target file value. - target_format (str): The target format value. - units (str): The units value. - """ - - source_file: str = Field(description="Source file path") - target_file: str | None = Field(default=None, description="Target file path") - source_format: str | None = Field(default=None, description="Source file format") - target_format: str = Field(description="Target file format") - output_path: str | None = Field(default=None, description="Alternative output path") - conversion_options: dict[str, Any] | None = Field( - default=None, description="Conversion options" - ) - quality: str = Field(default="high", description="Conversion quality") - units: str = Field(default="mm", description="Units") - invalid_format: str | None = Field( - default=None, description="Invalid format for testing" - ) - - class LoadPartInput(CompatInput): """Input schema for loading a part file. @@ -367,6 +341,7 @@ def _prepare_save_target( *, required_extension: str, overwrite: bool, + refuse_wrong_extension: bool = False, ) -> str: """Normalize and validate a save target before adapter/COM calls. @@ -380,6 +355,8 @@ def _prepare_save_target( required_extension (str): Required extension for the target document type (for example, ``.sldprt`` or ``.sldasm``). overwrite (bool): Whether saving is allowed to replace an existing file. + refuse_wrong_extension (bool): Refuse a path with another extension + instead of changing it to ``required_extension``. Returns: str: The normalized save path. @@ -424,6 +401,11 @@ def _prepare_save_target( target = Path(file_path) if target.suffix.lower() != required_extension.lower(): + if refuse_wrong_extension: + raise InvalidInputError( + f"file_path must end in {required_extension} for the active " + f"document; got {target.name!r}. Nothing was saved." + ) # Normalize extension so save_part/save_assembly always use their canonical type. target = target.with_suffix(required_extension) @@ -451,6 +433,41 @@ def _prepare_save_target( return str(target) + async def _checked_new_path(raw_path: str, *, overwrite: bool) -> str: + """Check a new save path against the active document's type. + + Args: + raw_path: The path the caller gave. + overwrite: Whether a file already there may be replaced. + + Returns: + str: The path to save to. + + Raises: + ToolOperationError: If the active document's type can't be read. + InvalidInputError: If the path fails a check (see + ``_prepare_save_target``). + """ + info = await adapter.get_model_info() + doc_type = ( + info.data.get("type") + if info.is_success and isinstance(info.data, dict) + else None + ) + extension = _DOC_EXTENSIONS.get(str(doc_type)) + if extension is None: + raise ToolOperationError( + "Could not tell the active document's type " + f"({info.error or doc_type!r}), so file_path was not checked and " + "nothing was saved." + ) + return _prepare_save_target( + raw_path, + required_extension=extension, + overwrite=overwrite, + refuse_wrong_extension=True, + ) + def _get_attr_or_call(obj: Any, name: str, default: Any = None) -> Any: """Read COM values that may be exposed as either properties or methods.""" candidate = getattr(obj, name, None) @@ -557,18 +574,20 @@ def _copy_active_assembly_with_references( @mcp.tool() async def save_file(input_data: SaveFileInput) -> dict[str, Any]: - """Save the active document, to its own path or to a new path in its own format. + """Save the active part, assembly or drawing, to its own path or to a new path in its own format. - Use it after changes you want to keep. For a part or an assembly with checks on - the target path (folder exists, no accidental overwrite), use `save_part` or - `save_assembly`; to write another format, use `save_as` or an `export_*` tool. + Use it after changes you want to keep. A new `file_path` is checked before + SolidWorks is asked: its folder must exist and be writable, it must end in + the document's extension (.sldprt, .sldasm, .slddrw), and a file already there + is kept unless `overwrite` is on. To write another format, use `save_as` or an + `export_*` tool; to copy an assembly with its parts, `pack_and_go_assembly`. Needs: an open, active document, already saved once unless you give a path. - Changes: writes the file; a different file at `file_path` is replaced. Returns: - `data` from the save (usually empty). + Changes: writes the file. Returns: `file_path` (when given) and `data` from + the save. Args: input_data: The save. Nothing is required: give `file_path` to save to a - new path, or omit it to save in place. + new path, or omit it to save in place; `overwrite` is off. Returns: dict[str, Any]: The save result. @@ -579,11 +598,15 @@ async def save_file(input_data: SaveFileInput) -> dict[str, Any]: "save_file", "Active adapter does not support save_file; the file was not saved.", ) - result = await adapter.save_file(input_data.file_path) + target = input_data.file_path + if target is not None: + target = await _checked_new_path(target, overwrite=input_data.overwrite) + result = await adapter.save_file(target) require_success(result, "Failed to save file") return { "status": "success", "message": "File saved successfully", + **({"file_path": target} if target is not None else {}), "data": result.data, "execution_time": result.execution_time, } @@ -686,15 +709,14 @@ async def get_file_properties() -> dict[str, Any]: "feature_count": model_info.get("feature_count"), } - if file_path is not None and file_path.is_file(): - stat = file_path.stat() - properties.update( - { - "file_size_bytes": stat.st_size, - "created_date": stat.st_ctime, - "modified_date": stat.st_mtime, - } - ) + details = file_details(raw_path) + properties.update( + { + "file_size_bytes": details["size_bytes"], + "created_date": details["created"], + "modified_date": details["modified"], + } + ) return { "status": "success", @@ -704,23 +726,26 @@ async def get_file_properties() -> dict[str, Any]: @mcp.tool() async def get_model_info() -> dict[str, Any]: - """Report the active document's title, path, type, active configuration, unsaved changes, feature count and rebuild status. + """Report the active document's title, path, type, configuration, unsaved changes, feature count, rebuild status and file details. Use it first in a session, to see which document is active (it follows a switch - made in the SolidWorks window). For file size and dates, use - `get_file_properties`; for every open document, use `list_open_documents`. - Needs: an open document. Read-only. Returns: `model_info` with `title`, `path`, - `type`, `configuration`, `is_dirty`, `feature_count` and `rebuild_status` (0 - rebuilt, 1 needs a rebuild). + made in the SolidWorks window). For every open document, use + `list_open_documents`; for custom properties, `get_custom_properties`. Needs: an + open document. Read-only. Returns: `model_info` with `title`, `path`, `type`, + `configuration`, `is_dirty`, `feature_count`, `rebuild_status` (0 rebuilt, 1 + needs a rebuild), and the file's `size_bytes`, `created` and `modified` (Unix + timestamps; null for a document never saved). """ require_capability( adapter, "get_model_info", "Active adapter does not support get_model_info" ) result = await adapter.get_model_info() require_success(result, "Failed to get model info") + info = dict(result.data or {}) + info.update(file_details(str(info.get("path") or ""))) return { "status": "success", - "model_info": result.data, + "model_info": info, "execution_time": result.execution_time, } @@ -876,106 +901,6 @@ async def list_configurations() -> dict[str, Any]: "execution_time": result.execution_time, } - @mcp.tool() - async def manage_file_properties(input_data: FileOperationInput) -> dict[str, Any]: - """Read or change the file-level properties of a SolidWorks file on disk. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To read or - set custom properties on the active model today, use `get_custom_properties` and - `set_custom_property`. Changes: once available, the file's properties. Returns: - once available, the properties under `data`. - - Args: - input_data: The operation. `operation` is required; `file_path` or - `source_path`, `properties` and `include_system` have defaults. - - Returns: - dict[str, Any]: The properties, or a `not_supported` error. - """ - input_data = _coerce_input(FileOperationInput, input_data) - require_capability( - adapter, - "manage_file_properties", - "Active adapter does not support manage_file_properties; " - f"no {input_data.operation} operation was performed.", - ) - result = await adapter.manage_file_properties(input_data.model_dump()) - require_success(result, "Failed to manage file properties") - return { - "status": "success", - "message": "File properties managed successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def convert_file_format(input_data: FormatConversionInput) -> dict[str, Any]: - """Convert a SolidWorks file on disk to another format without opening it first. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Today, open - the file with `open_model` and use `save_as` or an `export_*` tool such as - `export_step`. Changes: once available, writes the converted file. Returns: once - available, the converted file under `data`. - - Args: - input_data: The conversion. `source_file` and `target_format` are - required; `target_file`, `quality` and `units` have defaults. - - Returns: - dict[str, Any]: The conversion, or a `not_supported` error. - """ - input_data = _coerce_input(FormatConversionInput, input_data) - require_capability( - adapter, - "convert_file_format", - "Active adapter does not support convert_file_format; " - f"{input_data.source_file} was not converted.", - ) - result = await adapter.convert_file_format(input_data.model_dump()) - require_success(result, "Failed to convert file format") - return { - "status": "success", - "message": "File converted successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def batch_file_operations(input_data: FileOperationInput) -> dict[str, Any]: - """Copy, move, rename or delete SolidWorks files on disk in one call. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To copy an - assembly with every part it uses, use `pack_and_go_assembly`. Changes: once - available, copies, moves, renames or deletes files. Returns: once available, a - per-file result under `data`. - - Args: - input_data: The operation. `operation` (copy, move, delete or rename) is - required; `source_path`, `target_path` and `parameters` have - defaults. - - Returns: - dict[str, Any]: The results, or a `not_supported` error. - """ - input_data = _coerce_input(FileOperationInput, input_data) - require_capability( - adapter, - "batch_file_operations", - "Active adapter does not support batch_file_operations; " - f"no {input_data.operation} batch operation was performed.", - ) - result = await adapter.batch_file_operations(input_data.model_dump()) - require_success(result, "Failed to run batch file operations") - return { - "status": "success", - "message": "Batch file operations completed successfully", - "data": result.data, - "execution_time": result.execution_time, - } - @mcp.tool() async def load_part(input_data: LoadPartInput) -> dict[str, Any]: """Open a part (.sldprt) from disk and make it the active document. @@ -1066,8 +991,7 @@ async def save_part(input_data: SavePartInput | None = None) -> dict[str, Any]: Before writing to a new path it checks the folder exists and is writable, changes the extension to .sldprt, and refuses an existing file unless - `overwrite` is on. For an assembly, use `save_assembly`; for other formats, use - `save_as` or an `export_*` tool. Needs: an open, active part. Changes: writes + `overwrite` is on. For other formats, use `save_as` or an `export_*` tool. Needs: an open, active part. Changes: writes the part file. Returns: `file_path` when saved to a new path. Args: @@ -1118,8 +1042,8 @@ async def save_assembly( changes the extension to .sldasm, and refuses an existing file unless `overwrite` is on. With `include_references`, it instead copies the assembly file as last saved, and the files it references, into the new folder; unsaved - changes are left out and references are not updated. For a self-contained copy, - use `pack_and_go_assembly`. Needs: an open, active assembly, saved once for + changes are left out and references are not updated. To copy an assembly with + its referenced parts, use `pack_and_go_assembly`. Needs: an open, active assembly, saved once for `include_references`. Changes: writes the assembly file (and copies). Returns: `file_path`, plus `copied_files` and `missing_source_files` when copying references. @@ -1353,5 +1277,5 @@ async def save_body_as_part( "execution_time": result.execution_time, } - tool_count = 19 # Total number of registered tools in this module + tool_count = 16 # Total number of registered tools in this module return tool_count diff --git a/src/solidworks_mcp/tools/macro_recording.py b/src/solidworks_mcp/tools/macro_recording.py index 14bbcb7e..89b72fec 100644 --- a/src/solidworks_mcp/tools/macro_recording.py +++ b/src/solidworks_mcp/tools/macro_recording.py @@ -1,7 +1,6 @@ """Macro Recording and Playback tools for SolidWorks MCP Server. -Provides tools for recording, managing, and executing SolidWorks macros for automation -and workflow optimization. +Provides ``execute_macro``, which runs a binary SolidWorks macro (``.swp``). """ import asyncio @@ -15,10 +14,8 @@ from .input_compat import CompatInput from .tool_boundary import ( ToolOperationError, - UnsupportedOperationError, normalize_input, require_capability, - require_success, with_tool_boundary, ) @@ -28,60 +25,6 @@ _RUNNABLE_MACRO_SUFFIXES = frozenset({".swp", ".swb"}) -class MacroRecordingInput(CompatInput): - """Input schema for macro recording operations. - - Attributes: - auto_cleanup (bool): The auto cleanup value. - auto_stop (bool): The auto stop value. - capture_keyboard (bool): The capture keyboard value. - capture_mouse (bool): The capture mouse value. - description (str): The description value. - macro_name (str | None): The macro name value. - output_file (str): The output file value. - recording_mode (str): The recording mode value. - recording_name (str | None): The recording name value. - recording_quality (str): The recording quality value. - timeout_seconds (int): The timeout seconds value. - """ - - macro_name: str | None = Field( - default=None, description="Name for the recorded macro" - ) - recording_name: str | None = Field( - default=None, description="Alternative recording name" - ) - description: str = Field( - default="", description="Description of macro functionality" - ) - output_file: str = Field(description="Output file for the recorded macro") - recording_mode: str = Field(default="User actions", description="Recording mode") - capture_mouse: bool = Field(default=True, description="Capture mouse actions") - capture_keyboard: bool = Field(default=True, description="Capture keyboard actions") - recording_quality: str = Field( - default="High", description="Recording quality level" - ) - auto_cleanup: bool = Field(default=False, description="Cleanup temporary files") - auto_stop: bool = Field( - default=False, description="Auto-stop recording after timeout" - ) - timeout_seconds: int = Field( - default=300, description="Timeout for auto-stop in seconds" - ) - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the macro recording input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - """ - if self.macro_name is None: - self.macro_name = self.recording_name or "Recorded Macro" - - class MacroPlaybackInput(CompatInput): """Input schema for macro playback. @@ -138,58 +81,6 @@ def model_post_init(self, __context: Any) -> None: ) -class MacroAnalysisInput(CompatInput): - """Input schema for macro analysis. - - Attributes: - analysis_depth (str): The analysis depth value. - analysis_type (str): The analysis type value. - macro_file (str | None): The macro file value. - macro_path (str | None): The macro path value. - suggest_optimizations (bool): The suggest optimizations value. - """ - - macro_path: str | None = Field( - default=None, description="Path to macro file to analyze" - ) - macro_file: str | None = Field( - default=None, description="Alternative macro file path" - ) - analysis_type: str = Field( - default="full", description="Analysis type (full, dependencies, performance)" - ) - analysis_depth: str = Field(default="Basic", description="Analysis depth alias") - suggest_optimizations: bool = Field( - default=False, description="Suggest optimizations" - ) - - -class MacroBatchInput(CompatInput): - """Input schema for batch macro operations. - - Attributes: - execution_order (str): The execution order value. - file_pattern (str | None): The file pattern value. - macro_list (list[str]): The macro list value. - source_directory (str | None): The source directory value. - stop_on_error (bool): The stop on error value. - target_directory (str | None): The target directory value. - """ - - macro_list: list[str] = Field(description="List of macro file paths") - target_directory: str | None = Field( - default=None, description="Target directory alias" - ) - source_directory: str | None = Field( - default=None, description="Source directory alias" - ) - file_pattern: str | None = Field(default=None, description="File pattern alias") - execution_order: str = Field( - default="sequential", description="Execution order (sequential, parallel)" - ) - stop_on_error: bool = Field(default=True, description="Stop batch if error occurs") - - async def register_macro_recording_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: Any ) -> int: @@ -209,71 +100,6 @@ async def register_macro_recording_tools( mcp = with_tool_boundary(mcp) tool_count = 0 - @mcp.tool() - async def start_macro_recording(input_data: MacroRecordingInput) -> dict[str, Any]: - """Start SolidWorks' macro recorder, to capture what the user does as a macro. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Recording is - done in SolidWorks today (Tools > Macro > Record). Changes: once available, - starts a recording session. Returns: once available, the session details under - `data`. - - Args: - input_data: The recording. `output_file` (where the macro is saved) is - required; `macro_name`, `recording_mode`, the capture switches and - `timeout_seconds` have defaults. - - Returns: - dict[str, Any]: The session, or a `not_supported` error. - """ - require_capability( - adapter, - "start_macro_recording", - "Active adapter does not support start_macro_recording; " - f"no recording of {input_data.macro_name} was started.", - ) - result = await adapter.start_macro_recording(input_data.model_dump()) - require_success(result, "Failed to start recording") - return { - "status": "success", - "message": f"Macro recording started: {input_data.macro_name}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def stop_macro_recording(input_data: dict[str, Any]) -> dict[str, Any]: - """Stop the macro recorder and save the recorded macro. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Recording is - done in SolidWorks today (Tools > Macro > Stop). Changes: once available, ends - the session and writes the macro file. Returns: once available, the saved - macro's details under `data`. - - Args: - input_data: A mapping; nothing in it is used yet. - - Returns: - dict[str, Any]: The saved macro, or a `not_supported` error. - """ - require_capability( - adapter, - "stop_macro_recording", - "No adapter capability exists for stopping a macro " - "recording; this tool never started a real recording " - "session, so there is no macro code to save.", - ) - result = await adapter.stop_macro_recording(input_data) - require_success(result, "Failed to stop recording") - return { - "status": "success", - "message": "Macro recording completed and saved", - "data": result.data, - "execution_time": result.execution_time, - } - @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. @@ -328,140 +154,5 @@ async def execute_macro(input_data: MacroPlaybackInput) -> dict[str, Any]: "execution_time": execution_time, } - @mcp.tool() - async def analyze_macro(input_data: MacroAnalysisInput) -> dict[str, Any]: - """Analyse a macro's structure, dependencies and complexity, and suggest optimisations. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. - Returns: once available, the findings under `data`. - - Args: - input_data: The macro. Give `macro_path` (or `macro_file`); - `analysis_type`, `analysis_depth` and `suggest_optimizations` have - defaults. - - Returns: - dict[str, Any]: The findings, or a `not_supported` error. - """ - require_capability( - adapter, - "analyze_macro", - "Active adapter does not support analyze_macro; " - f"{input_data.macro_path} was not analyzed.", - ) - result = await adapter.analyze_macro(input_data.model_dump()) - require_success(result, "Failed to analyze macro") - return { - "status": "success", - "message": f"Macro analysis completed for {input_data.macro_path}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def batch_execute_macros(input_data: MacroBatchInput) -> dict[str, Any]: - """Run several macros in sequence against the files in a folder. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To run one - macro, use `execute_macro`. Changes: once available, whatever the macros do. - Returns: once available, each run's result under `data`. - - Args: - input_data: The batch. `macro_list` (macro file paths) is required; - `target_directory`, `file_pattern`, `execution_order` and - `stop_on_error` have defaults. - - Returns: - dict[str, Any]: The results, or a `not_supported` error. - """ - payload = input_data.model_dump() - - if hasattr(adapter, "batch_execute_macros"): - result = await adapter.batch_execute_macros(payload) - require_success(result, "Failed batch execution") - return { - "status": "success", - "message": "Batch macro execution completed successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - macro_list = payload.get("macro_list", []) - - raise UnsupportedOperationError( - "Active adapter does not support batch_execute_macros; " - f"none of the {len(macro_list)} macro(s) were run." - ) - - @mcp.tool() - async def optimize_macro(input_data: dict[str, Any]) -> dict[str, Any]: - """Suggest improvements to a macro's code for speed and reliability. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. It - would suggest changes, not make them. Returns: once available, the suggestions - under `data`. - - Args: - input_data: A mapping with the macro's `macro_path` (or `macro_file`). - - Returns: - dict[str, Any]: The suggestions, or a `not_supported` error. - """ - payload = dict(input_data) - - if hasattr(adapter, "optimize_macro"): - result = await adapter.optimize_macro(payload) - require_success(result, "Failed to optimize macro") - return { - "status": "success", - "message": "Macro optimization completed successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - macro_path = payload.get("macro_path") or payload.get("macro_file", "") - - raise UnsupportedOperationError( - "Active adapter does not support optimize_macro; " - f"{macro_path} was not analyzed or changed." - ) - - @mcp.tool() - async def create_macro_library(input_data: dict[str, Any]) -> dict[str, Any]: - """Set up a shared folder of categorised, documented macros. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Changes: once - available, creates the library folder and its index. Returns: once available, - the library's contents under `data`. - - Args: - input_data: A mapping with the `library_path` to create. - - Returns: - dict[str, Any]: The library, or a `not_supported` error. - """ - payload = dict(input_data) - - if hasattr(adapter, "create_macro_library"): - result = await adapter.create_macro_library(payload) - require_success(result, "Failed to create library") - return { - "status": "success", - "message": "Macro library created successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - library_path = payload.get("library_path", "") - - raise UnsupportedOperationError( - "Active adapter does not support create_macro_library; " - f"no library was created at {library_path or '(unspecified path)'}." - ) - - tool_count = 8 # Macro recording and management tools + 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 45940e56..de63fd36 100644 --- a/src/solidworks_mcp/tools/modeling.py +++ b/src/solidworks_mcp/tools/modeling.py @@ -1168,7 +1168,7 @@ async def create_part(input_data: CreatePartInput) -> dict[str, Any]: Uses `template` (a .prtdot) or the default part template, then sets `units` if given, and assigns `material` if given. The part is not saved until - `save_part`. Needs: SolidWorks running. Changes: opens a new part document. + `save_file`. Needs: SolidWorks running. Changes: opens a new part document. Returns: `part` with `name`, `units`, `template` and `material` (the one assigned, or null), plus a `warning` when the material couldn't be assigned; the part is created either way. @@ -1223,7 +1223,7 @@ async def create_assembly(input_data: CreateAssemblyInput) -> dict[str, Any]: """Create a new, empty assembly document and make it active, ready for `insert_component`. Uses `template` (an .asmdot) or the default assembly template. It is not saved - until `save_assembly`. Needs: SolidWorks running. Changes: opens a new assembly + until `save_file`. Needs: SolidWorks running. Changes: opens a new assembly document. Returns: `assembly` with `name` and `template`. Then call `insert_component` for each part. diff --git a/src/solidworks_mcp/tools/sketching.py b/src/solidworks_mcp/tools/sketching.py index 2d2f3b6b..97c82ae9 100644 --- a/src/solidworks_mcp/tools/sketching.py +++ b/src/solidworks_mcp/tools/sketching.py @@ -281,43 +281,6 @@ class AddRelationInput(BaseModel): ) -class TutorialSimpleHoleInput(CompatInput): - """Input schema for creating a simple hole (tutorial example). - - Attributes: - center_x (float): The center x value. - center_y (float): The center y value. - depth (float | None): The depth value. - diameter (float): The diameter value. - plane (str): The plane value. - """ - - plane: str = Field(description="Sketch plane for the hole") - center_x: float = Field(description="Hole center X coordinate in mm") - center_y: float = Field(description="Hole center Y coordinate in mm") - diameter: float = Field(description="Hole diameter in mm") - depth: float | None = Field( - default=None, description="Hole depth in mm (None for through hole)" - ) - - def model_post_init(self, __context: Any) -> None: - """Provide model post init support for the tutorial simple hole input. - - Args: - __context (Any): The context value. - - Returns: - None: None. - - Raises: - ValueError: Depth must be positive. - """ - if self.diameter <= 0: - raise ValueError("diameter must be positive") - if self.depth is not None and self.depth <= 0: - raise ValueError("depth must be positive") - - class CheckSketchDefinitionInput(CompatInput): """Input schema for checking sketch definition status. @@ -1132,62 +1095,5 @@ async def sketch_tutorial_simple_hole() -> dict[str, Any]: }, } - @mcp.tool() - async def tutorial_simple_hole( - input_data: TutorialSimpleHoleInput, - ) -> dict[str, Any]: - """Draw a circle on a plane and cut it as a hole, as one worked example. - - Not available yet on real SolidWorks: its cut step has no COM implementation, - so the call draws and closes the sketch, then fails. It is planned for a future - release. Use `create_sketch`, `add_circle`, `exit_sketch` and - `create_cut_extrude` instead. Needs: an open part with a solid body. - Changes: adds a sketch (and, with the mock adapter, a cut). Returns: `tutorial` - with `plane`, `diameter`, `depth` and `steps`. - - Args: - input_data: The hole. `plane`, `center_x`, `center_y` and `diameter` - (mm) are required; `depth` defaults to the diameter. - - Returns: - dict[str, Any]: The steps run. - """ - steps: list[dict[str, Any]] = [] - - sketch_result = await adapter.create_sketch(input_data.plane) - require_success(sketch_result, context="Failed to create sketch") - steps.append({"step": "Create sketch", "status": "success"}) - - circle_result = await adapter.add_sketch_circle( - input_data.center_x, - input_data.center_y, - input_data.diameter / 2, - False, - ) - require_success(circle_result, context="Failed to add circle") - steps.append({"step": "Add circle", "status": "success"}) - - exit_result = await adapter.exit_sketch() - require_success(exit_result, context="Failed to exit sketch") - steps.append({"step": "Exit sketch", "status": "success"}) - - cut_depth = ( - input_data.depth if input_data.depth is not None else input_data.diameter - ) - cut_result = await adapter.create_cut("HoleSketch", cut_depth) - require_success(cut_result, context="Failed to create cut extrude") - steps.append({"step": "Create cut extrude", "status": "success"}) - - return { - "status": "success", - "message": "Completed simple hole tutorial", - "tutorial": { - "plane": input_data.plane, - "diameter": input_data.diameter, - "depth": input_data.depth, - "steps": steps, - }, - } - tool_count = 6 # Legacy count expected by tests return tool_count diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index 478d9850..242c682d 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -8,26 +8,33 @@ of its COM call; - **experimental**: implemented, never checked on real SolidWorks; - **planned**: registered, but no adapter implements it yet (its - description says "Not available yet"). + description says "Not available yet"); its reason names the queue item + that builds it; +- **deprecated**: works, but another tool replaces it; it keeps working + until the next major release after ``since``, when it is removed. -``ToolRegistrar`` adds the level to each tool's tags and, for a beta or -experimental tool, a ``warning`` to its successful results. Fixing a fault +``ToolRegistrar`` adds the level to each tool's tags and, for a beta, +experimental or deprecated tool, a ``warning`` to its successful results and +the same sentence at the start of its description. Fixing a fault in the queue's small-faults list moves its tool up a level here. """ from __future__ import annotations +import re +from collections.abc import Mapping, Set from dataclasses import dataclass from enum import StrEnum class SupportLevel(StrEnum): - """The four support levels, most trusted first.""" + """The five support levels: four by trust, then the replaced tools.""" STABLE = "stable" BETA = "beta" EXPERIMENTAL = "experimental" PLANNED = "planned" + DEPRECATED = "deprecated" @dataclass(frozen=True) @@ -36,62 +43,156 @@ class Support: Attributes: level: The tool's support level. - reason: One line on the gap; empty only for a stable tool. + reason: One line on the gap; empty only for a stable tool. A + deprecated tool's reason is ``"use ``."`` or + ``"no replacement."``. + since: The version a deprecated tool was deprecated in; empty for + every other level. """ level: SupportLevel reason: str = "" + since: str = "" def __post_init__(self) -> None: - """Require a reason for every level below stable. + """Require a reason below stable, and a version for a deprecated tool. Raises: - ValueError: If a level below stable has no reason, or a stable - tool has one. + ValueError: If a level below stable has no reason, a stable tool + has one, or ``since`` is given for any level but deprecated + (or missing for a deprecated tool). """ if (self.level is SupportLevel.STABLE) == bool(self.reason): raise ValueError( "a reason is required below stable, and only there: " f"{self.level.value!r} with reason {self.reason!r}" ) + if (self.level is SupportLevel.DEPRECATED) != bool(self.since): + raise ValueError( + "a deprecated tool needs `since`, and only it: " + f"{self.level.value!r} with since {self.since!r}" + ) def warning(self) -> str | None: - """The sentence a successful beta or experimental result carries. + """The sentence a successful beta, experimental or deprecated result carries. Returns: - str | None: ``"Beta: "`` or ``"Experimental: "``; - None for stable and planned tools (a planned tool never succeeds). + str | None: ``"Beta: "``, ``"Experimental: "`` or + ``"Deprecated: "``; None for stable and planned tools (a + planned tool never succeeds). """ - if self.level in (SupportLevel.BETA, SupportLevel.EXPERIMENTAL): + if self.level in ( + SupportLevel.BETA, + SupportLevel.EXPERIMENTAL, + SupportLevel.DEPRECATED, + ): return f"{self.level.value.capitalize()}: {self.reason}" return None + def replacement(self) -> str | None: + """The tool a deprecated tool's reason names. + + Returns: + str | None: The name in backticks in ``"use ``."``; None for + ``"no replacement."`` and for every other level. + """ + if self.level is not SupportLevel.DEPRECATED: + return None + match = re.fullmatch(r"use `(\w+)`\.", self.reason) + return match.group(1) if match else None + + +def _major(version: str) -> int: + """The major number of a ``X.Y.Z`` version.""" + return int(version.split(".", 1)[0]) + + +def deprecation_problems( + levels: Mapping[str, Support], registered: Set[str], version: str +) -> list[str]: + """What is wrong with the table's deprecated entries. + + A deprecated tool names a registered replacement (or says there is + none), and is gone once the package's major version passes the one it + was deprecated in. + + Args: + levels: The support table. + registered: The names of the registered tools. + version: The package version, ``X.Y.Z``. + + Returns: + list[str]: One line per problem; empty when there is none. + """ + problems = [] + for name, support in sorted(levels.items()): + if support.level is not SupportLevel.DEPRECATED: + continue + replacement = support.replacement() + if replacement is None and support.reason != "no replacement.": + problems.append( + f"{name}: the reason must be 'use ``.' or 'no replacement.'" + ) + elif replacement is not None and replacement not in registered: + problems.append(f"{name}: its replacement {replacement!r} is not a tool") + if name in registered and _major(version) > _major(support.since): + problems.append( + f"{name}: deprecated in {support.since}, so remove it before {version}" + ) + return problems + + +def planned_problems(levels: Mapping[str, Support]) -> list[str]: + """Planned tools whose reason does not name the queue item that builds them. + + Args: + levels: The support table. + + Returns: + list[str]: One line per problem; empty when there is none. + """ + return [ + f"{name}: a planned tool's reason names its queue item" + for name, support in sorted(levels.items()) + if support.level is SupportLevel.PLANNED + and not re.search(r"\bqueue item \d+\b", support.reason) + ] + #: Tool families that never call SolidWorks; their tools are stable on unit #: tests alone. OFFLINE_FAMILIES = frozenset({"docs_discovery", "server_admin", "vba_generation"}) +#: The release the eight duplicates of issue #174 were deprecated in. +_DEPRECATED_IN = "2.1.0" + _STABLE = Support(SupportLevel.STABLE) -_PLANNED = Support(SupportLevel.PLANNED, "no adapter implements it yet.") +_PLANNED_DRAWING = Support( + SupportLevel.PLANNED, "planned in queue item 12 (the drawing pack)." +) + + +def _deprecated(replacement: str | None) -> Support: + """A tool deprecated in 2.1.0 in favour of ``replacement`` (or none). + + Args: + replacement: The registered tool that replaces it, or None. + + Returns: + Support: The deprecated entry. + """ + reason = f"use `{replacement}`." if replacement else "no replacement." + return Support(SupportLevel.DEPRECATED, reason, since=_DEPRECATED_IN) SUPPORT_LEVELS: dict[str, Support] = { # analysis - "analyze_geometry": _PLANNED, - "calculate_mass_properties": _STABLE, + "calculate_mass_properties": _deprecated("get_mass_properties"), "check_interference": _STABLE, "get_mass_properties": _STABLE, - "get_material_properties": _PLANNED, "verify_model": _STABLE, # automation - "automation_start_macro_recording": _PLANNED, - "automation_stop_macro_recording": _PLANNED, - "batch_process_files": _PLANNED, - "create_template": _PLANNED, - "execute_workflow": _PLANNED, "generate_vba_code": _STABLE, - "manage_design_table": _PLANNED, - "optimize_performance": _PLANNED, # docs_discovery "discover_solidworks_docs": _STABLE, "find_related_api_members": _STABLE, @@ -99,29 +200,21 @@ def warning(self) -> str | None: "lookup_api_method": _STABLE, "search_solidworks_api_help": _STABLE, # drawing - "add_annotation": _PLANNED, - "add_dimension": _PLANNED, - "add_drawing_view": _STABLE, + "add_dimension": _PLANNED_DRAWING, + "add_drawing_view": _deprecated("create_drawing_view"), "add_note": _STABLE, "auto_center_marks": _STABLE, - "auto_dimension_view": _PLANNED, - "check_drawing_standards": _PLANNED, - "create_detail_view": _PLANNED, + "auto_dimension_view": _PLANNED_DRAWING, + "check_drawing_standards": _PLANNED_DRAWING, + "create_detail_view": _PLANNED_DRAWING, "create_drawing_view": _STABLE, - "create_section_view": _PLANNED, + "create_section_view": _PLANNED_DRAWING, "create_technical_drawing": _STABLE, "list_drawing_views": _STABLE, - "update_sheet_format": _PLANNED, - "update_title_block": _PLANNED, + "update_sheet_format": _PLANNED_DRAWING, + "update_title_block": _PLANNED_DRAWING, # drawing_analysis - "analyze_drawing_annotations": _PLANNED, - "analyze_drawing_comprehensive": _PLANNED, - "analyze_drawing_dimensions": _PLANNED, - "analyze_drawing_views": _PLANNED, - "check_drawing_compliance": _PLANNED, "compare_drawing_versions": _STABLE, - "generate_drawing_report": _PLANNED, - "validate_drawing_completeness": _PLANNED, # drawing_automation "add_datum_tag": _STABLE, "add_gtol": _STABLE, @@ -140,7 +233,6 @@ def warning(self) -> str | None: "set_custom_property": _STABLE, "set_material": _STABLE, # export - "batch_export": _PLANNED, "export_dwg": _STABLE, "export_iges": _STABLE, "export_image": _STABLE, @@ -149,32 +241,23 @@ def warning(self) -> str | None: "export_stl": _STABLE, # file_management "activate_document": _STABLE, - "batch_file_operations": _PLANNED, "classify_feature_tree": _STABLE, - "convert_file_format": _PLANNED, - "get_file_properties": _STABLE, + "get_file_properties": _deprecated("get_model_info"), "get_model_info": _STABLE, "get_selected_entities": _STABLE, "list_configurations": _STABLE, "list_features": _STABLE, "list_open_documents": _STABLE, - "load_assembly": _STABLE, - "load_part": _STABLE, - "manage_file_properties": _PLANNED, + "load_assembly": _deprecated("open_model"), + "load_part": _deprecated("open_model"), "pack_and_go_assembly": _STABLE, "save_as": _STABLE, - "save_assembly": _STABLE, + "save_assembly": _deprecated("save_file"), "save_body_as_part": _STABLE, "save_file": _STABLE, - "save_part": _STABLE, + "save_part": _deprecated("save_file"), # macro_recording - "analyze_macro": _PLANNED, - "batch_execute_macros": _PLANNED, - "create_macro_library": _PLANNED, "execute_macro": _STABLE, - "optimize_macro": _PLANNED, - "start_macro_recording": _PLANNED, - "stop_macro_recording": _PLANNED, # modeling "add_chamfer": _STABLE, "add_fillet": _STABLE, @@ -227,15 +310,9 @@ def warning(self) -> str | None: "sketch_linear_pattern": _STABLE, "sketch_mirror": _STABLE, "sketch_offset": _STABLE, - "sketch_tutorial_simple_hole": _STABLE, - "tutorial_simple_hole": _PLANNED, # its cut step fails on real SolidWorks + "sketch_tutorial_simple_hole": _deprecated(None), # template_management - "apply_template": _PLANNED, - "batch_apply_template": _PLANNED, "compare_templates": _STABLE, - "extract_template": _PLANNED, - "list_template_library": _PLANNED, - "save_to_template_library": _PLANNED, # vba_generation "generate_vba_assembly_insert": _STABLE, "generate_vba_assembly_mates": _STABLE, diff --git a/src/solidworks_mcp/tools/template_management.py b/src/solidworks_mcp/tools/template_management.py index b23a48f0..fc51b09c 100644 --- a/src/solidworks_mcp/tools/template_management.py +++ b/src/solidworks_mcp/tools/template_management.py @@ -1,90 +1,24 @@ """Template Management tools for SolidWorks MCP Server. -Provides tools for managing SolidWorks templates including extraction, application, -comparison, and library management. +Provides ``compare_templates``, which compares two template files on disk. """ from typing import Any from fastmcp import FastMCP -from pydantic import BaseModel, Field +from pydantic import Field from ..adapters.base import SolidWorksAdapter from .file_facts import file_fact_snapshot from .input_compat import CompatInput from .tool_boundary import ( ToolOperationError, - UnsupportedOperationError, - require_capability, - require_success, with_tool_boundary, ) # Input schemas for template management -class TemplateExtractionInput(BaseModel): - """Input schema for extracting template from model. - - Attributes: - include_custom_properties (bool): The include custom properties value. - include_dimensions (bool): The include dimensions value. - save_path (str): The save path value. - source_model (str): The source model value. - template_name (str): The template name value. - template_type (str): The template type value. - """ - - source_model: str = Field(description="Path to source model file") - template_name: str = Field(description="Name for the extracted template") - template_type: str = Field(description="Template type (part, assembly, drawing)") - save_path: str = Field(description="Path to save the template file") - include_custom_properties: bool = Field( - default=True, description="Include custom properties" - ) - include_dimensions: bool = Field(default=True, description="Include dimensions") - - -class TemplateApplicationInput(BaseModel): - """Input schema for applying template to model. - - Attributes: - apply_dimensions (bool): The apply dimensions value. - apply_materials (bool): The apply materials value. - overwrite_existing (bool): The overwrite existing value. - target_model (str): The target model value. - template_path (str): The template path value. - """ - - template_path: str = Field(description="Path to template file") - target_model: str = Field(description="Path to target model") - overwrite_existing: bool = Field( - default=False, description="Overwrite existing properties" - ) - apply_dimensions: bool = Field( - default=True, description="Apply dimension formatting" - ) - apply_materials: bool = Field(default=True, description="Apply material settings") - - -class TemplateBatchInput(BaseModel): - """Input schema for batch template operations. - - Attributes: - backup_originals (bool): The backup originals value. - file_pattern (str): The file pattern value. - recursive (bool): The recursive value. - source_folder (str): The source folder value. - template_path (str): The template path value. - """ - - template_path: str = Field(description="Path to template file") - source_folder: str = Field(description="Folder containing target models") - file_pattern: str = Field(default="*.sldprt", description="File pattern to match") - recursive: bool = Field(default=True, description="Process subfolders") - backup_originals: bool = Field(default=True, description="Create backup copies") - - class TemplateComparisonInput(CompatInput): """Input schema for comparing templates. @@ -119,103 +53,6 @@ async def register_template_management_tools( mcp = with_tool_boundary(mcp) tool_count = 0 - @mcp.tool() - async def extract_template(input_data: TemplateExtractionInput) -> dict[str, Any]: - """Capture a model's settings (custom properties, dimensions, units) as a reusable template file. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Changes: once - available, writes the template to `save_path`, replacing any file there. - Returns: once available, the captured settings under `data`. - - Args: - input_data: The extraction. `source_model`, `template_name`, - `template_type` and `save_path` are required; - `include_custom_properties` and `include_dimensions` default to on. - - Returns: - dict[str, Any]: The template, or a `not_supported` error. - """ - require_capability( - adapter, - "extract_template", - "Active adapter does not support extract_template; no " - f"template was extracted from {input_data.source_model}.", - ) - result = await adapter.extract_template(input_data.model_dump()) - require_success(result, "Failed to extract template") - return { - "status": "success", - "message": f"Template '{input_data.template_name}' extracted from {input_data.source_model}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def apply_template(input_data: TemplateApplicationInput) -> dict[str, Any]: - """Apply a saved template's properties, dimensions and materials to a model. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. To set a - material or a property today, use `set_material` or `set_custom_property`. - Changes: once available, overwrites the target model's matching settings. - Returns: once available, what changed under `data`. - - Args: - input_data: The application. `template_path` and `target_model` are - required; `overwrite_existing`, `apply_dimensions` and - `apply_materials` have defaults. - - Returns: - dict[str, Any]: The changes, or a `not_supported` error. - """ - require_capability( - adapter, - "apply_template", - "Active adapter does not support apply_template; " - f"{input_data.target_model} was not changed.", - ) - result = await adapter.apply_template(input_data.model_dump()) - require_success(result, "Failed to apply template") - return { - "status": "success", - "message": f"Template applied to {input_data.target_model}", - "data": result.data, - "execution_time": result.execution_time, - } - - @mcp.tool() - async def batch_apply_template(input_data: TemplateBatchInput) -> dict[str, Any]: - """Apply one template to every matching model in a folder. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Changes: once - available, overwrites settings in each matching file, optionally keeping - backups. Returns: once available, a per-file result under `data`. - - Args: - input_data: The batch. `template_path` and `source_folder` are - required; `file_pattern`, `recursive` and `backup_originals` have - defaults. - - Returns: - dict[str, Any]: The results, or a `not_supported` error. - """ - require_capability( - adapter, - "batch_apply_template", - "Active adapter does not support batch_apply_template; " - f"no files in {input_data.source_folder} were changed.", - ) - result = await adapter.batch_apply_template(input_data.model_dump()) - require_success(result, "Failed batch template application") - return { - "status": "success", - "message": "Batch template application completed", - "data": result.data, - "execution_time": result.execution_time, - } - @mcp.tool() async def compare_templates(input_data: TemplateComparisonInput) -> dict[str, Any]: """Compare two template files on disk: whether they are byte-identical, and how their sizes differ. @@ -274,68 +111,5 @@ async def compare_templates(input_data: TemplateComparisonInput) -> dict[str, An ), } - @mcp.tool() - async def save_to_template_library(input_data: dict[str, Any]) -> dict[str, Any]: - """Add a template to a shared, categorised template library. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Changes: once - available, copies the template into the library, replacing an entry with the - same name. Returns: once available, the library entry under `data`. - - Args: - input_data: A mapping with the `template_name` and the template's path. - - Returns: - dict[str, Any]: The entry, or a `not_supported` error. - """ - if hasattr(adapter, "save_to_template_library"): - result = await adapter.save_to_template_library(input_data) - require_success(result, "Failed to save to library") - return { - "status": "success", - "message": "Template saved to library", - "data": result.data, - "execution_time": result.execution_time, - } - - template_name = input_data.get("template_name", "") - - raise UnsupportedOperationError( - "Active adapter does not support save_to_template_library; " - f"'{template_name}' was not saved to any library. There is " - "no local template registry — this tool needs a real " - "adapter-backed library service." - ) - - @mcp.tool() - async def list_template_library(input_data: dict[str, Any]) -> dict[str, Any]: - """List the templates in the shared template library. - - Not available yet: no adapter implements it, so every call returns an error with - `error_type: "not_supported"`. It is planned for a future release. Read-only. - Returns: once available, the library's templates under `data`. - - Args: - input_data: A mapping of optional filters; none is required. - - Returns: - dict[str, Any]: The templates, or a `not_supported` error. - """ - require_capability( - adapter, - "list_template_library", - "Active adapter does not support list_template_library; " - "there is no local template registry to list.", - ) - result = await adapter.list_template_library(input_data) - require_success(result, "Failed to list template library") - return { - "status": "success", - "message": "Template library listed successfully", - "data": result.data, - "execution_time": result.execution_time, - } - - tool_count = 6 # Template management tools + tool_count = 1 # compare_templates return tool_count diff --git a/src/solidworks_mcp/tools/tool_boundary.py b/src/solidworks_mcp/tools/tool_boundary.py index 709c8757..138ba888 100644 --- a/src/solidworks_mcp/tools/tool_boundary.py +++ b/src/solidworks_mcp/tools/tool_boundary.py @@ -12,8 +12,8 @@ adapter's timing, else the tool's own wall time) - using :class:`ErrorClassifier` to name the failure. :class:`ToolRegistrar` applies the boundary to every tool at registration, so no tool can forget it. It also adds each tool's support level (from -``support_levels.py``) to its tags and, for a beta or experimental tool, a -``warning`` to its successful results. +``support_levels.py``) to its tags and, for a beta, experimental or deprecated +tool, a ``warning`` to its successful results. """ from __future__ import annotations @@ -358,7 +358,7 @@ def _support(self, name: str) -> Support: if support is None: raise KeyError( f"Tool {name!r} has no entry in tools/support_levels.py; add its " - "support level (stable, beta, experimental or planned) there." + "support level (stable, beta, experimental, planned or deprecated) there." ) return support @@ -368,8 +368,8 @@ def _metadata( """The registration kwargs with the tool's title, hints and tag added. Explicit ``title``/``annotations``/``description`` kwargs win over - the tables; tags are merged. A beta or experimental tool's - description opens with its level sentence, the same as its + the tables; tags are merged. A beta, experimental or deprecated + tool's description opens with its level sentence, the same as its ``warning``. Args: diff --git a/src/solidworks_mcp/tools/tool_hints.py b/src/solidworks_mcp/tools/tool_hints.py index 5f1c379d..05a11416 100644 --- a/src/solidworks_mcp/tools/tool_hints.py +++ b/src/solidworks_mcp/tools/tool_hints.py @@ -100,18 +100,9 @@ def _discards(title: str) -> ToolHints: "calculate_mass_properties": _reads("Calculate Mass Properties"), "get_mass_properties": _reads("Get Mass Properties"), "check_interference": _reads("Check Assembly Interference"), - "analyze_geometry": _reads("Analyze Geometry"), - "get_material_properties": _reads("Get Material Properties"), "verify_model": _reads("Verify Model Against Expectations"), # automation "generate_vba_code": _reads("Generate VBA Code"), - "automation_start_macro_recording": _adds("Start Macro Recording (Automation)"), - "automation_stop_macro_recording": _discards("Stop Macro Recording (Automation)"), - "batch_process_files": _discards("Batch Process Files"), - "manage_design_table": _adds("Manage Design Table"), - "execute_workflow": _discards("Execute Workflow"), - "create_template": _overwrites("Create Template File"), - "optimize_performance": _sets("Optimize SolidWorks Performance"), # docs_discovery "discover_solidworks_docs": _sets("Rebuild SolidWorks API Index"), "search_solidworks_api_help": _reads("Search SolidWorks API"), @@ -131,19 +122,11 @@ def _discards(title: str) -> ToolHints: "check_drawing_standards": _reads("Check Drawing Standards"), "create_technical_drawing": _adds("Create Technical Drawing"), "add_drawing_view": _adds("Add Drawing View"), - "add_annotation": _adds("Add Drawing Annotation"), "update_title_block": _sets("Update Title Block"), "list_drawing_views": _reads("List Drawing Views"), "auto_center_marks": _adds("Add Centre Marks"), # drawing_analysis - "analyze_drawing_comprehensive": _reads("Analyze Drawing (All Checks)"), - "analyze_drawing_dimensions": _reads("Analyze Drawing Dimensions"), - "analyze_drawing_annotations": _reads("Analyze Drawing Annotations"), - "check_drawing_compliance": _reads("Check Drawing Compliance"), - "analyze_drawing_views": _reads("Analyze Drawing Views"), - "generate_drawing_report": _reads("Generate Drawing Report"), "compare_drawing_versions": _reads("Compare Drawing Files"), - "validate_drawing_completeness": _reads("Validate Drawing Completeness"), # drawing_automation "insert_model_dimensions": _adds("Insert Model Dimensions"), "arrange_dimensions": _sets("Arrange Drawing Dimensions"), @@ -168,7 +151,6 @@ def _discards(title: str) -> ToolHints: "export_pdf": _overwrites("Export PDF"), "export_dwg": _overwrites("Export DWG"), "export_image": _overwrites("Export Image"), - "batch_export": _overwrites("Batch Export"), # file_management "save_file": _overwrites("Save File"), "save_as": _overwrites("Save As"), @@ -178,9 +160,6 @@ def _discards(title: str) -> ToolHints: "get_selected_entities": _reads("Get Selected Entities"), "classify_feature_tree": _reads("Classify Feature Tree"), "list_configurations": _reads("List Configurations"), - "manage_file_properties": _discards("Manage File Properties"), - "convert_file_format": _overwrites("Convert File Format"), - "batch_file_operations": _discards("Batch File Operations"), "load_part": _sets("Load Part"), "load_assembly": _sets("Load Assembly"), "save_part": _overwrites("Save Part"), @@ -190,13 +169,7 @@ def _discards(title: str) -> ToolHints: "activate_document": _sets("Activate Document"), "save_body_as_part": _overwrites("Save Body as Part"), # macro_recording - "start_macro_recording": _adds("Start Macro Recording"), - "stop_macro_recording": _discards("Stop Macro Recording"), "execute_macro": _discards("Run Macro"), - "analyze_macro": _reads("Analyze Macro"), - "batch_execute_macros": _discards("Run Macros in Batch"), - "optimize_macro": _reads("Optimize Macro"), - "create_macro_library": _overwrites("Create Macro Library"), # modeling "open_model": _sets("Open Model"), "create_part": _adds("Create Part"), @@ -248,14 +221,8 @@ def _discards(title: str) -> ToolHints: "sketch_mirror": _adds("Mirror Sketch Entities"), "sketch_offset": _adds("Offset Sketch Entities"), "sketch_tutorial_simple_hole": _adds("Tutorial: Hole Sketch"), - "tutorial_simple_hole": _adds("Tutorial: Simple Hole"), # template_management - "extract_template": _overwrites("Extract Template"), - "apply_template": _overwrites("Apply Template"), - "batch_apply_template": _overwrites("Apply Template in Batch"), "compare_templates": _reads("Compare Templates"), - "save_to_template_library": _overwrites("Save to Template Library"), - "list_template_library": _reads("List Template Library"), # vba_generation "generate_vba_extrusion": _reads("Generate VBA: Extrusion"), "generate_vba_revolve": _reads("Generate VBA: Revolve"), diff --git a/src/solidworks_mcp/ui/services/llm_service.py b/src/solidworks_mcp/ui/services/llm_service.py index 467f9dd8..c06f7039 100644 --- a/src/solidworks_mcp/ui/services/llm_service.py +++ b/src/solidworks_mcp/ui/services/llm_service.py @@ -172,7 +172,7 @@ def _tools_for_feature_name(feature_name: str, position: int) -> list[str]: return ["create_revolve"] if "extrude" in lower: return ["create_extrusion"] - return ["analyze_geometry"] + return ["get_model_info", "list_features", "get_mass_properties"] def _family_for_feature_order(ordered_features: list[str], current_family: str) -> str: @@ -421,7 +421,7 @@ async def _run_structured_agent( " classify_feature_tree, create_sketch, add_line, add_arc, add_circle, add_rectangle,\n" " create_extrusion, create_revolve, create_cut_extrude, export_image, export_step,\n" " export_stl, select_feature, select_face_edges, add_fillet, add_chamfer,\n" - " rebuild_model, check_interference, analyze_geometry,\n" + " rebuild_model, check_interference,\n" " generate_vba_code, execute_macro\n" "Prefer tools in the order listed above (inspect → classify → plan → execute → verify).\n" "Do not invent tools not in this list.\n" diff --git a/src/utils/check_tool_docs_consistency.py b/src/utils/check_tool_docs_consistency.py index 93275702..969c5095 100644 --- a/src/utils/check_tool_docs_consistency.py +++ b/src/utils/check_tool_docs_consistency.py @@ -57,6 +57,9 @@ "macro_recording.py": "Macro Recording", "docs_discovery.py": "Docs Discovery", "drawing_analysis.py": "Drawing Analysis", + "drawing_automation.py": "Drawing Automation", + "engineering_data.py": "Engineering Data", + "server_admin.py": "Server Admin", } diff --git a/src/utils/generate_tool_catalog.py b/src/utils/generate_tool_catalog.py index 032352f3..427507d3 100644 --- a/src/utils/generate_tool_catalog.py +++ b/src/utils/generate_tool_catalog.py @@ -500,21 +500,15 @@ def _make_sample_payload(fields: list[dict[str, Any]]) -> dict[str, Any]: "calculate_mass_properties": "Active model with solid geometry", "get_mass_properties": "Active model with solid geometry", "check_interference": "Active assembly", - "analyze_geometry": "Active model with geometry", - "get_material_properties": "Active part with assigned material", "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", - "batch_export": "Writable source and output directories", "save_file": "Active open document", "save_as": "Active open document, writable output path", "get_file_properties": "Active document", - "manage_file_properties": "Active document", - "convert_file_format": "Valid source file path", - "batch_file_operations": "Writable directories", "load_part": "SolidWorks running, valid .sldprt path", "load_assembly": "SolidWorks running, valid .sldasm path", "save_part": "Active Part document", diff --git a/tests/integration/test_all_endpoints_harness.py b/tests/integration/test_all_endpoints_harness.py index 4eb429b7..2bbf1ff4 100644 --- a/tests/integration/test_all_endpoints_harness.py +++ b/tests/integration/test_all_endpoints_harness.py @@ -456,7 +456,6 @@ def test_sample_path_env_override_is_prioritized( "operation": "export", "output_directory": "C:\\Temp\\out", }, - "manage_design_table": {"action": "list"}, "execute_workflow": {"steps": []}, "create_template": {"template_name": "smoke_template", "template_type": "part"}, "optimize_performance": {}, diff --git a/tests/integration/test_no_fabricated_payloads.py b/tests/integration/test_no_fabricated_payloads.py index 4857fd45..cfd250ed 100644 --- a/tests/integration/test_no_fabricated_payloads.py +++ b/tests/integration/test_no_fabricated_payloads.py @@ -34,8 +34,9 @@ #: search local documentation, delegate to a sibling tool, or compare files on #: disk. Anything NOT on this list that skips the adapter is fabricating. ADAPTER_FREE_TOOLS = { - "get_mass_properties", # delegates to calculate_mass_properties - "stop_macro_recording", + # Both share one plain helper that calls the adapter. + "get_mass_properties", + "calculate_mass_properties", "discover_solidworks_docs", "search_solidworks_api_help", # Same local-index reads as search_solidworks_api_help, narrower queries. @@ -57,25 +58,12 @@ "create_section_view", "create_detail_view", "check_drawing_standards", - "execute_workflow", - "manage_design_table", - "optimize_performance", - "analyze_macro", - "batch_execute_macros", - "optimize_macro", - "create_macro_library", - "apply_template", - "batch_apply_template", # File-level work that needs no SolidWorks session: comparisons read the # files, and the template tools copy a model to a template file. "compare_drawing_versions", "compare_templates", - "create_template", - "extract_template", # The template library is a JSON file on disk: these read and write it, and # stat the referenced template files. No SolidWorks session involved. - "list_template_library", - "save_to_template_library", } diff --git a/tests/integration/test_support_levels.py b/tests/integration/test_support_levels.py index 1ff27f9e..77d8b8c4 100644 --- a/tests/integration/test_support_levels.py +++ b/tests/integration/test_support_levels.py @@ -19,8 +19,11 @@ OFFLINE_FAMILIES, SUPPORT_LEVELS, SupportLevel, + deprecation_problems, + planned_problems, ) from solidworks_mcp.tools.tool_boundary import tool_family +from solidworks_mcp.version import __version__ _ROOT = Path(__file__).resolve().parents[2] _NOT_AVAILABLE = "Not available yet" @@ -87,7 +90,9 @@ async def test_a_description_opens_with_its_level(mock_adapter) -> None: warning = SUPPORT_LEVELS[tool.name].warning() if warning is not None and not text.startswith(warning): wrong.append(tool.name) - if warning is None and text.startswith(("Beta:", "Experimental:")): + if warning is None and text.startswith( + ("Beta:", "Experimental:", "Deprecated:") + ): wrong.append(tool.name) assert wrong == [] @@ -102,3 +107,16 @@ async def test_every_tool_is_tagged_with_its_level(mock_adapter) -> None: ) assert wrong == [] + + +@pytest.mark.asyncio +async def test_deprecated_tools_name_a_replacement_and_go_at_the_next_major( + mock_adapter, +) -> None: + registered = {t.name for t in await _tools(mock_adapter)} + + assert deprecation_problems(SUPPORT_LEVELS, registered, __version__) == [] + + +def test_every_planned_tool_names_the_queue_item_that_builds_it() -> None: + assert planned_problems(SUPPORT_LEVELS) == [] diff --git a/tests/integration/test_tool_descriptions.py b/tests/integration/test_tool_descriptions.py index 62b5fc6e..80b4f0bb 100644 --- a/tests/integration/test_tool_descriptions.py +++ b/tests/integration/test_tool_descriptions.py @@ -8,6 +8,7 @@ from __future__ import annotations import re +from pathlib import Path from typing import Any import pytest @@ -206,3 +207,136 @@ def test_the_field_check_follows_refs_and_nesting() -> None: ) assert undescribed_fields(tool) == ["input_data.inner.bare"] + + +#: Verbs a tool name starts with (the verb list, plus those of removed tools), +#: so a backticked ``analyze_geometry`` reads as a tool name and a backticked +#: ``volume_after`` (a reply field) does not. ``mirror`` and ``rebuild`` are +#: left out: ``mirror_line`` and ``rebuild_status`` are reply fields. +_TOOL_VERBS = ( + "add|analyze|apply|batch|check|close|compare|convert|create|delete|execute|" + "export|extract|generate|get|insert|list|load|manage|measure|open|optimize|" + "pattern|rename|save|select|set|sketch|suppress|validate|verify" +) +_TOOL_LIKE = re.compile(rf"`((?:{_TOOL_VERBS})_[a-z0-9_]+)`") + + +def unknown_tool_names(text: str, tools: set[str], fields: set[str]) -> list[str]: + """Backticked tool-like names in ``text`` that are neither tools nor fields. + + Args: + text: A tool description. + tools: Registered tool names. + fields: Every input field name of every tool. + + Returns: + list[str]: The unknown names, in order of appearance. + """ + return [n for n in _TOOL_LIKE.findall(text) if n not in tools | fields] + + +def _field_names(schema: Any) -> set[str]: + """Every property name at any depth of a JSON schema.""" + names: set[str] = set() + if isinstance(schema, dict): + names.update(schema.get("properties", {})) + for value in schema.values(): + names |= _field_names(value) + elif isinstance(schema, list): + for value in schema: + names |= _field_names(value) + return names + + +@pytest.mark.asyncio +async def test_no_description_names_a_tool_that_does_not_exist(mock_adapter) -> None: + tools = await _tools(mock_adapter) + names = {t.name for t in tools} + fields = set().union(*(_field_names(t.parameters) for t in tools)) + + unknown = { + t.name: found + for t in tools + if (found := unknown_tool_names(t.description or "", names, fields)) + } + + assert unknown == {}, "descriptions name tools that are not registered" + + +def test_the_unknown_name_check_ignores_tools_and_fields() -> None: + text = "Use `analyze_geometry`, then `get_model_info`; reads `set_value`." + + assert unknown_tool_names(text, {"get_model_info"}, {"set_value"}) == [ + "analyze_geometry" + ] + + +_STANDARD = Path(__file__).resolve().parents[2] / ( + "docs/agents/tool-description-standard.md" +) + + +def _verbs_and_exceptions(text: str) -> tuple[tuple[str, ...], set[str]]: + """The verb list and the named exceptions, read from the standard. + + Args: + text: The standard's Markdown. + + Returns: + tuple[tuple[str, ...], set[str]]: The verb prefixes (``create_``, ...) + and the exception names. + """ + section = text.split("## Tool names", 1)[1].split("\n## ", 1)[0] + table, rest = section.split("", 1) + verbs = tuple(re.findall(r"`([a-z]+_)`", table)) + block = rest.split("", 1)[0] + return verbs, set(re.findall(r"`([a-z0-9_]+)`", block)) + + +def naming_faults( + names: set[str], verbs: tuple[str, ...], exceptions: set[str] +) -> list[str]: + """Tool names that break the verb list, and exceptions that are no tool. + + Args: + names: The registered tool names. + verbs: The verb prefixes. + exceptions: The names allowed to break the list. + + Returns: + list[str]: One line per fault. + """ + faults = [ + f"{name}: starts with none of {', '.join(verbs)}" + for name in sorted(names - exceptions) + if not name.startswith(verbs) + ] + faults += [ + f"{name}: listed as an exception but not registered" + for name in sorted(exceptions - names) + ] + return faults + + +@pytest.mark.asyncio +async def test_every_tool_name_starts_with_a_listed_verb(mock_adapter) -> None: + verbs, exceptions = _verbs_and_exceptions(_STANDARD.read_text(encoding="utf-8")) + names = {t.name for t in await _tools(mock_adapter)} + + assert "create_" in verbs and "insert_component" in exceptions + assert naming_faults(names, verbs, exceptions) == [] + + +def test_an_unlisted_verb_fails_and_an_exception_passes() -> None: + verbs = ("create_", "get_") + + assert naming_faults({"make_hole"}, verbs, set()) == [ + "make_hole: starts with none of create_, get_" + ] + assert naming_faults({"insert_component"}, verbs, {"insert_component"}) == [] + + +def test_a_stale_exception_fails() -> None: + assert naming_faults(set(), ("get_",), {"load_part"}) == [ + "load_part: listed as an exception but not registered" + ] diff --git a/tests/live/test_live_sw_honest_tool_list.py b/tests/live/test_live_sw_honest_tool_list.py new file mode 100644 index 00000000..6ea60e53 --- /dev/null +++ b/tests/live/test_live_sw_honest_tool_list.py @@ -0,0 +1,141 @@ +"""The honest tool list (issue #174), checked on real SolidWorks. + +One bundle, run together, then failures are fixed one at a time: + +1. ``save_file`` to a new path, then refused for a missing folder, the wrong + extension and an existing file (and allowed with ``overwrite``); +2. ``get_model_info`` reports the file's size and dates for a saved part, and + nulls for a new one; +3. a deprecated tool still works and its result names the replacement. + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_honest_tool_list.py::test_save_file_checks_a_new_path + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows (see +``tests/live/conftest.py``). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from tests.live.evidence import evidence +from tests.live.test_live_sw_beta_tools import _sketch + +pytestmark = pytest.mark.asyncio + + +async def _tools(adapter: Any) -> dict[str, Any]: + """The tool families these tests use, registered on ``adapter``; name -> fn.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.file_management import register_file_management_tools + from solidworks_mcp.tools.modeling import register_modeling_tools + from solidworks_mcp.tools.sketching import register_sketching_tools + + mcp = FastMCP("honest-tool-list-live") + for register in ( + register_modeling_tools, + register_sketching_tools, + register_file_management_tools, + ): + await register(mcp, adapter, {}) + return {t.name: t.fn for t in await mcp.list_tools()} + + +async def _block(tools: dict[str, Any], name: str) -> None: + """A new part holding a 40 x 40 x 20 mm block (``D1@Boss-Extrude1`` = 20).""" + assert (await tools["create_part"]({"name": name}))["status"] == "success" + await _sketch(tools, "Top", {"x1": -20, "y1": -20, "x2": 20, "y2": 20}) + made = await tools["create_extrusion"]({"depth": 20}) + assert made["status"] == "success", made + + +async def test_save_file_checks_a_new_path(scratch: Any, tmp_path: Path) -> None: + """A new path saves; a missing folder, wrong extension or existing file don't.""" + tools = await _tools(scratch.adapter) + await _block(tools, "save_checks") + target = tmp_path / "block.SLDPRT" + scratch.written_files.append(str(target)) + + saved = await tools["save_file"]({"file_path": str(target)}) + missing = await tools["save_file"]( + {"file_path": str(tmp_path / "no_such_folder" / "block.SLDPRT")} + ) + wrong = await tools["save_file"]({"file_path": str(tmp_path / "block.SLDASM")}) + kept = await tools["save_file"]({"file_path": str(target)}) + replaced = await tools["save_file"]({"file_path": str(target), "overwrite": True}) + + evidence( + "save_file: new path, missing folder, wrong extension, existing file", + { + "saved": [saved["status"], target.exists()], + "missing_folder": [missing.get("error_type"), missing["message"]], + "wrong_extension": [wrong.get("error_type"), wrong["message"]], + "existing": [kept.get("error_type"), kept["message"]], + "overwrite": replaced["status"], + }, + ) + assert saved["status"] == "success", saved + assert target.stat().st_size > 0 + assert missing["error_type"] == "invalid_input" + assert not (tmp_path / "no_such_folder").exists() + assert wrong["error_type"] == "invalid_input" + assert ".sldprt" in wrong["message"] + assert kept["error_type"] == "invalid_input" + assert replaced["status"] == "success", replaced + + +async def test_get_model_info_reports_the_file(scratch: Any, tmp_path: Path) -> None: + """A saved part has a size and dates; a new one has nulls.""" + tools = await _tools(scratch.adapter) + await _block(tools, "info_saved") + target = tmp_path / "info.SLDPRT" + scratch.written_files.append(str(target)) + assert (await tools["save_file"]({"file_path": str(target)}))["status"] == ( + "success" + ) + saved = (await tools["get_model_info"]())["model_info"] + + assert (await tools["create_part"]({"name": "info_new"}))["status"] == "success" + new = (await tools["get_model_info"]())["model_info"] + + evidence( + "get_model_info on a saved part and a new one", + { + "saved": {k: saved[k] for k in ("path", "size_bytes", "modified")}, + "new": {k: new[k] for k in ("path", "size_bytes", "modified")}, + }, + ) + assert saved["size_bytes"] == target.stat().st_size + assert saved["created"] is not None and saved["modified"] is not None + assert new["size_bytes"] is None and new["modified"] is None + + +async def test_a_deprecated_tool_names_its_replacement( + scratch: Any, tmp_path: Path +) -> None: + """``load_part`` still opens a part, and says to use ``open_model``.""" + tools = await _tools(scratch.adapter) + await _block(tools, "deprecated") + target = tmp_path / "deprecated.SLDPRT" + scratch.written_files.append(str(target)) + assert (await tools["save_file"]({"file_path": str(target)}))["status"] == ( + "success" + ) + assert (await tools["close_model"]({"save": False}))["status"] == "success" + + loaded = await tools["load_part"]({"file_path": str(target)}) + + evidence( + "load_part (deprecated)", + {"status": loaded["status"], "warning": loaded.get("warning")}, + call=f'load_part({{"file_path": "{target.name}"}})', + ) + assert loaded["status"] == "success", loaded + assert loaded["warning"] == "Deprecated: use `open_model`." diff --git a/tests/solidworks_mcp/agents/test_soc_exporter.py b/tests/solidworks_mcp/agents/test_soc_exporter.py index cf9ad301..17f04c0e 100644 --- a/tests/solidworks_mcp/agents/test_soc_exporter.py +++ b/tests/solidworks_mcp/agents/test_soc_exporter.py @@ -373,7 +373,6 @@ def test_generate_script_skips_read_only_ops(): _rec("get_model_info"), _rec("list_features"), _rec("check_sketch_fully_defined"), - _rec("analyze_geometry"), _rec("get_dimension"), _rec("check_interference"), _rec("calculate_mass_properties"), diff --git a/tests/solidworks_mcp/progress/test_generate.py b/tests/solidworks_mcp/progress/test_generate.py index 599a4f53..846a45dd 100644 --- a/tests/solidworks_mcp/progress/test_generate.py +++ b/tests/solidworks_mcp/progress/test_generate.py @@ -66,6 +66,7 @@ def test_the_data_counts_levels_and_lists_tools() -> None: "beta": 1, "experimental": 0, "planned": 0, + "deprecated": 0, } assert data["tools"]["list"][0]["reason"] == "x ." assert data["com"]["core"] == {"covered": 1, "total": 4} diff --git a/tests/solidworks_mcp/progress/test_svg.py b/tests/solidworks_mcp/progress/test_svg.py index dfa49e71..84030e43 100644 --- a/tests/solidworks_mcp/progress/test_svg.py +++ b/tests/solidworks_mcp/progress/test_svg.py @@ -57,3 +57,15 @@ def test_an_empty_project_draws_empty_bars() -> None: assert "MCP tools: 0" in svg assert "0 of 0 methods · 0.0%" in svg + + +def test_deprecated_tools_are_left_out_of_the_count_and_the_bar() -> None: + svg = render({**_LEVELS, SupportLevel.DEPRECATED: 5}, _COVERAGE) + + # Still 10 tools and 80%: the five deprecated ones only show in the legend. + assert "MCP tools: 10" in svg + assert "80% work on SolidWorks today" in svg + assert "deprecated 5" in svg + assert ( + f'width="470.4" height="24" fill="{LEVEL_COLOURS[SupportLevel.STABLE]}"' in svg + ) diff --git a/tests/solidworks_mcp/tools/test_analysis.py b/tests/solidworks_mcp/tools/test_analysis.py index 45caf279..bb3d4774 100644 --- a/tests/solidworks_mcp/tools/test_analysis.py +++ b/tests/solidworks_mcp/tools/test_analysis.py @@ -16,7 +16,6 @@ SolidWorksMCPConfig, ) from solidworks_mcp.tools.analysis import ( - GeometryAnalysisInput, InterferenceCheckInput, MassPropertiesInput, register_analysis_tools, @@ -258,75 +257,6 @@ async def test_mass_properties_fallback_and_alias_inputs( alias_model = await alias_tool(input_data=MassPropertiesInput()) assert alias_model["status"] == "success" - @pytest.mark.asyncio - async def test_analysis_tools_exception_and_fallback_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover adapter exceptions plus non-adapter fallback branches.""" - await register_analysis_tools(mcp_server, mock_adapter, mock_config) - - check_tool = None - geometry_tool = None - material_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "check_interference": - check_tool = tool.fn - if tool.name == "analyze_geometry": - geometry_tool = tool.fn - if tool.name == "get_material_properties": - material_tool = tool.fn - - assert check_tool is not None - assert geometry_tool is not None - assert material_tool is not None - - # This asserted the tool's own refusal message, reached only when the - # adapter has no check_interference at all. The adapter implements it - # now, so the hasattr gate resolves to a real capability and the - # adapter's answer surfaces instead. Still an error, and still never - # a fabricated clean result: the mock refuses because the assembly - # has fewer than two components, which is the honest answer. - fallback = await check_tool(input_data=InterferenceCheckInput()) - assert fallback["status"] == "error" - assert "at least two components" in fallback["message"] - # The critical property: never a clean bill of health for an assembly - # nothing examined. - assert fallback.get("interference_found") is not False - - # Exception branch for adapter check_interference. - mock_adapter.check_interference = AsyncMock(side_effect=RuntimeError("boom")) - errored = await check_tool(input_data=InterferenceCheckInput()) - assert errored["status"] == "error" - assert errored["error_type"] == "internal" - - class _BadGeometryInput: - """Test bad geometry input.""" - - @property - def analysis_type(self): - """Test helper for analysis type.""" - raise RuntimeError("bad analysis type") - - parameters = None - - bad_geo = await geometry_tool(input_data=_BadGeometryInput()) - assert bad_geo["status"] == "error" - assert "bad analysis type" in bad_geo["message"] - - # get_material_properties must refuse rather than invent a material, - # since mock_adapter has no get_material_properties method. - material = await material_tool() - assert material["status"] == "error" - assert "does not support get_material_properties" in material["message"] - - # Exception branch for adapter get_material_properties. - mock_adapter.get_material_properties = AsyncMock( - side_effect=RuntimeError("material boom") - ) - material_errored = await material_tool() - assert material_errored["status"] == "error" - assert material_errored["error_type"] == "internal" - @pytest.mark.asyncio async def test_check_interference_refuses_when_adapter_lacks_support( self, mcp_server, mock_config @@ -350,65 +280,6 @@ class _AdapterWithoutInterferenceSupport: assert result["status"] == "error" assert "does not support check_interference" in result["message"] - @pytest.mark.asyncio - async def test_analyze_geometry_and_material_properties_adapter_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover the real-adapter success/error paths once analyze_geometry and - get_material_properties are wired to an adapter that implements them.""" - await register_analysis_tools(mcp_server, mock_adapter, mock_config) - - geometry_tool = None - material_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_geometry": - geometry_tool = tool.fn - if tool.name == "get_material_properties": - material_tool = tool.fn - - assert geometry_tool is not None - assert material_tool is not None - - mock_adapter.analyze_geometry = AsyncMock( - return_value=Mock( - is_success=True, - data={"analysis_type": "draft", "findings": []}, - execution_time=0.1, - ) - ) - geometry_success = await geometry_tool( - input_data=GeometryAnalysisInput(analysis_type="draft") - ) - assert geometry_success["status"] == "success" - assert geometry_success["data"]["analysis_type"] == "draft" - - mock_adapter.analyze_geometry = AsyncMock( - return_value=Mock(is_success=False, error="geometry analysis failed") - ) - geometry_error = await geometry_tool( - input_data=GeometryAnalysisInput(analysis_type="draft") - ) - assert geometry_error["status"] == "error" - assert "geometry analysis failed" in geometry_error["message"] - - mock_adapter.get_material_properties = AsyncMock( - return_value=Mock( - is_success=True, - data={"name": "Steel"}, - execution_time=0.1, - ) - ) - material_success = await material_tool() - assert material_success["status"] == "success" - assert material_success["data"]["name"] == "Steel" - - mock_adapter.get_material_properties = AsyncMock( - return_value=Mock(is_success=False, error="no material assigned") - ) - material_error = await material_tool() - assert material_error["status"] == "error" - assert "no material assigned" in material_error["message"] - def _make_mcp(): """Create a plain FastMCP instance.""" @@ -470,21 +341,6 @@ async def test_get_mass_properties_with_none_input(self): result = await fn(None) assert isinstance(result, dict) - @pytest.mark.asyncio - async def test_get_material_properties_returns_success(self): - """get_material_properties refuses when the adapter has no matching - capability, rather than returning static material data.""" - from solidworks_mcp.tools.analysis import register_analysis_tools - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - await register_analysis_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "get_material_properties") - result = await fn() - assert result["status"] == "error" - assert "does not support get_material_properties" in result["message"] - CAPABILITY = "check_interference" diff --git a/tests/solidworks_mcp/tools/test_automation.py b/tests/solidworks_mcp/tools/test_automation.py index 4b0d9b15..a2d953c0 100644 --- a/tests/solidworks_mcp/tools/test_automation.py +++ b/tests/solidworks_mcp/tools/test_automation.py @@ -1,12 +1,8 @@ """Tests for SolidWorks automation tools.""" -from unittest.mock import AsyncMock, Mock, patch - import pytest from fastmcp import FastMCP -from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus -from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter from solidworks_mcp.config import ( AdapterType, DeploymentMode, @@ -14,14 +10,8 @@ SolidWorksMCPConfig, ) from solidworks_mcp.tools.automation import ( - BatchProcessInput, - DesignTableInput, GenerateVBAInput, - PerformanceOptimizationInput, - RecordMacroInput, - TemplateInput, VBAGenerationInput, - WorkflowInput, register_automation_tools, ) @@ -37,7 +27,7 @@ async def test_register_automation_tools( tool_count = await register_automation_tools( mcp_server, mock_adapter, mock_config ) - assert tool_count == 8 + assert tool_count == 1 @pytest.mark.asyncio async def test_generate_vba_code_success( @@ -68,299 +58,6 @@ async def test_generate_vba_code_success( assert vba["lines_of_code"] == len(vba["code"].split("\n")) assert "style" not in vba - @pytest.mark.asyncio - async def test_start_macro_recording_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful macro recording start.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.start_macro_recording = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "recording_session_id": "rec_001", - "recording_started": True, - "output_file": "recorded_macro.swp", - "recording_mode": "User actions", - "start_timestamp": "2024-03-15T10:30:00", - }, - execution_time=0.3, - ) - ) - - input_data = RecordMacroInput( - recording_name="Test Recording", - output_file="recorded_macro.swp", - recording_mode="User actions", - capture_mouse=True, - capture_keyboard=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "automation_start_macro_recording": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["recording_started"] is True - assert result["data"]["output_file"] == "recorded_macro.swp" - mock_adapter.start_macro_recording.assert_called_once() - - @pytest.mark.asyncio - async def test_batch_process_files_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful batch file processing.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_process_files = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "total_files": 10, - "processed_files": 9, - "failed_files": 1, - "processing_time": 45.2, - "operation": "Update custom properties", - "results": [ - {"file": "part1.sldprt", "status": "success"}, - {"file": "part2.sldprt", "status": "success"}, - { - "file": "part3.sldprt", - "status": "failed", - "error": "File locked", - }, - # ... more results - ], - }, - execution_time=45.2, - ) - ) - - input_data = BatchProcessInput( - source_directory="./parts/", - operation="Update custom properties", - operation_parameters={ - "properties": {"Author": "Engineer", "Revision": "A"}, - "overwrite_existing": True, - }, - file_pattern="*.sldprt", - include_subdirectories=True, - parallel_processing=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_process_files": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_files"] == 10 - assert result["data"]["processed_files"] == 9 - assert result["data"]["failed_files"] == 1 - mock_adapter.batch_process_files.assert_called_once() - - @pytest.mark.asyncio - async def test_manage_design_table_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful design table management.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.manage_design_table = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "design_table_file": "part_configurations.xls", - "configurations_created": 5, - "parameters_linked": 12, - "operation": "Link Excel table", - "table_rows": 6, # Including header - "table_columns": 8, - }, - execution_time=1.5, - ) - ) - - input_data = DesignTableInput( - model_path="configurable_part.sldprt", - table_file="part_configurations.xls", - operation="Link Excel table", - auto_update=True, - create_configurations=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "manage_design_table": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["configurations_created"] == 5 - assert result["data"]["parameters_linked"] == 12 - mock_adapter.manage_design_table.assert_called_once() - - @pytest.mark.asyncio - async def test_execute_workflow_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful workflow execution.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.execute_workflow = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "workflow_name": "Part Creation Workflow", - "steps_completed": 8, - "total_steps": 8, - "execution_time": 12.5, - "output_files": ["final_part.sldprt", "part_drawing.slddrw"], - "workflow_status": "Completed successfully", - }, - execution_time=12.5, - ) - ) - - input_data = WorkflowInput( - workflow_name="Part Creation Workflow", - steps=[ - {"action": "open_template", "template": "part_template.prtdot"}, - {"action": "create_sketch", "plane": "Front"}, - {"action": "sketch_rectangle", "width": 50, "height": 30}, - {"action": "extrude", "depth": 25}, - {"action": "create_drawing", "template": "drawing_template.drwdot"}, - {"action": "add_views", "views": ["Front", "Right", "Top"]}, - {"action": "add_dimensions", "auto_dimension": True}, - {"action": "save_all"}, - ], - parallel_execution=False, - error_handling="Stop on error", - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "execute_workflow": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["steps_completed"] == 8 - assert result["data"]["total_steps"] == 8 - assert "final_part.sldprt" in result["data"]["output_files"] - mock_adapter.execute_workflow.assert_called_once() - - @pytest.mark.asyncio - async def test_create_template_success(self, mcp_server, mock_adapter, mock_config): - """Test successful template creation.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.create_template = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "template_file": "custom_part_template.prtdot", - "template_type": "Part", - "included_features": [ - "Base sketch", - "Custom properties", - "Material assignment", - ], - "settings_captured": 15, - "template_size": "125 KB", - }, - execution_time=2.8, - ) - ) - - input_data = TemplateInput( - source_model="reference_part.sldprt", - template_name="Custom Part Template", - template_type="Part", - output_path="templates/custom_part_template.prtdot", - include_custom_properties=True, - include_materials=True, - include_features=["Base sketch"], - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "create_template": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["template_file"] == "custom_part_template.prtdot" - assert result["data"]["settings_captured"] == 15 - mock_adapter.create_template.assert_called_once() - - @pytest.mark.asyncio - async def test_optimize_performance_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful performance optimization.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.optimize_performance = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "optimization_type": "Assembly performance", - "optimizations_applied": [ - "Lightweight components", - "Simplified representations", - "Display states optimization", - "Large assembly mode", - ], - "performance_improvement": "35%", - "memory_savings": "450 MB", - "load_time_reduction": "12.3 seconds", - }, - execution_time=3.2, - ) - ) - - input_data = PerformanceOptimizationInput( - target_file="large_assembly.sldasm", - optimization_type="Assembly performance", - optimization_level="Aggressive", - preserve_features=["Mates", "Dimensions"], - create_backup=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "optimize_performance": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["performance_improvement"] == "35%" - assert "Lightweight components" in result["data"]["optimizations_applied"] - mock_adapter.optimize_performance.assert_called_once() - @pytest.mark.asyncio async def test_automation_error_handling( self, mcp_server, mock_adapter, mock_config @@ -380,194 +77,6 @@ async def test_automation_error_handling( assert result["error_type"] == "invalid_input" assert "`parameters` is no longer an input" in result["message"] - @pytest.mark.asyncio - async def test_automation_fallback_paths_without_adapter_methods( - self, mcp_server, mock_config - ): - """Automation tools refuse rather than inventing a result when the - adapter has no matching capability. generate_vba_code is the one - exception: it produces real VBA text from the operation description, - so it still succeeds without an adapter.""" - await register_automation_tools(mcp_server, object(), mock_config) - - by_name = {tool.name: tool.fn for tool in await mcp_server.list_tools()} - - vba = await by_name["generate_vba_code"]( - input_data=VBAGenerationInput(operation_type="Create Block") - ) - start = await by_name["automation_start_macro_recording"]( - input_data=RecordMacroInput(recording_name="Macro A") - ) - stop = await by_name["automation_stop_macro_recording"]( - input_data={"session": "x"} - ) - batch = await by_name["batch_process_files"]( - input_data=BatchProcessInput( - source_directory="./parts", - operation="export", - target_format="step", - file_pattern="*.sldprt", - ) - ) - table = await by_name["manage_design_table"]( - input_data=DesignTableInput(operation="create") - ) - workflow = await by_name["execute_workflow"]( - input_data=WorkflowInput( - workflow_name="WF", - steps=[{"name": "step-1"}], - parallel_execution=False, - error_handling="stop", - ) - ) - template = await by_name["create_template"]( - input_data=TemplateInput(template_type="part", template_name="StdPart") - ) - optimize = await by_name["optimize_performance"]( - input_data={"optimization_type": "general"} - ) - - assert vba["status"] == "success" - assert "vba_code" in vba - assert start["status"] == "error" - assert "does not support start_macro_recording" in start["message"] - assert stop["status"] == "error" - assert stop["message"] # unconditional refusal, no adapter to check - assert batch["status"] == "error" - assert "does not support batch_process_files" in batch["message"] - assert table["status"] == "error" - assert "does not support manage_design_table" in table["message"] - assert workflow["status"] == "error" - assert "does not support execute_workflow" in workflow["message"] - assert template["status"] == "error" - assert "does not support create_template" in template["message"] - assert optimize["status"] == "error" - assert "does not support optimize_performance" in optimize["message"] - - @pytest.mark.asyncio - async def test_automation_exception_paths_from_adapter_methods( - self, mcp_server, mock_adapter, mock_config - ): - """Test exception handlers across automation tools that call adapter methods.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.start_macro_recording = AsyncMock( - side_effect=RuntimeError("record boom") - ) - mock_adapter.batch_process_files = AsyncMock( - side_effect=RuntimeError("batch boom") - ) - mock_adapter.manage_design_table = AsyncMock( - side_effect=RuntimeError("table boom") - ) - mock_adapter.execute_workflow = AsyncMock(side_effect=RuntimeError("wf boom")) - mock_adapter.create_template = AsyncMock(side_effect=RuntimeError("tpl boom")) - mock_adapter.optimize_performance = AsyncMock( - side_effect=RuntimeError("perf boom") - ) - - by_name = {tool.name: tool.fn for tool in await mcp_server.list_tools()} - - vba = await by_name["generate_vba_code"]( - input_data=VBAGenerationInput(operation_type="X") - ) - start = await by_name["automation_start_macro_recording"]( - input_data=RecordMacroInput(recording_name="Y") - ) - batch = await by_name["batch_process_files"]( - input_data=BatchProcessInput(source_directory="./parts", operation="export") - ) - table = await by_name["manage_design_table"]( - input_data=DesignTableInput(operation="create") - ) - workflow = await by_name["execute_workflow"]( - input_data=WorkflowInput( - workflow_name="WF", - steps=[{"name": "step-1"}], - parallel_execution=False, - error_handling="stop", - ) - ) - template = await by_name["create_template"]( - input_data=TemplateInput(template_type="part", template_name="StdPart") - ) - optimize = await by_name["optimize_performance"]( - input_data={"optimization_type": "general"} - ) - - assert vba["status"] == "success" # it never calls the adapter - assert start["status"] == "error" - assert start["error_type"] == "internal" - assert batch["status"] == "error" - assert batch["error_type"] == "internal" - assert table["status"] == "error" - assert table["error_type"] == "internal" - assert workflow["status"] == "error" - assert workflow["error_type"] == "internal" - assert template["status"] == "error" - assert template["error_type"] == "internal" - assert optimize["status"] == "error" - assert optimize["error_type"] == "internal" - - @pytest.mark.asyncio - async def test_automation_remaining_error_returns( - self, mcp_server, mock_adapter, mock_config - ): - """Cover adapter error-return branches for remaining automation tools.""" - await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_process_files = AsyncMock( - return_value=Mock(is_success=False, error="batch failed") - ) - mock_adapter.manage_design_table = AsyncMock( - return_value=Mock(is_success=False, error="table failed") - ) - mock_adapter.execute_workflow = AsyncMock( - return_value=Mock(is_success=False, error="workflow failed") - ) - mock_adapter.create_template = AsyncMock( - return_value=Mock(is_success=False, error="template failed") - ) - mock_adapter.optimize_performance = AsyncMock( - return_value=Mock(is_success=False, error="performance failed") - ) - - by_name = {tool.name: tool.fn for tool in await mcp_server.list_tools()} - - batch = await by_name["batch_process_files"]( - input_data=BatchProcessInput(source_directory="./parts", operation="export") - ) - table = await by_name["manage_design_table"]( - input_data=DesignTableInput(operation="create") - ) - workflow = await by_name["execute_workflow"]( - input_data=WorkflowInput( - workflow_name="WF", - steps=[{"name": "step-1"}], - parallel_execution=False, - error_handling="stop", - ) - ) - template = await by_name["create_template"]( - input_data=TemplateInput(template_type="part", template_name="StdPart") - ) - optimize = await by_name["optimize_performance"]( - input_data={"optimization_type": "general"} - ) - - assert batch["status"] == "error" and "batch failed" in batch["message"] - assert table["status"] == "error" and "table failed" in table["message"] - assert ( - workflow["status"] == "error" and "workflow failed" in workflow["message"] - ) - assert ( - template["status"] == "error" and "template failed" in template["message"] - ) - assert ( - optimize["status"] == "error" - and "performance failed" in optimize["message"] - ) - @pytest.mark.unit def test_vba_generation_input_validation(self): """Test input validation for VBA generation.""" @@ -578,26 +87,6 @@ def test_vba_generation_input_validation(self): assert valid_input.operation_type == "Extrusion" assert valid_input.parameters["depth"] == 25.0 - @pytest.mark.unit - def test_batch_processing_input_validation(self): - """Test input validation for batch processing.""" - # Valid input - valid_input = BatchProcessInput( - source_directory="./parts/", operation="Export STEP" - ) - assert valid_input.source_directory == "./parts/" - assert valid_input.operation == "Export STEP" - - # Test with optional parameters - full_input = BatchProcessInput( - source_directory="./parts/", - operation="Export STEP", - file_pattern="*.sldprt", - parallel_processing=True, - ) - assert full_input.file_pattern == "*.sldprt" - assert full_input.parallel_processing is True - def _make_mcp(): """Create a plain FastMCP instance.""" @@ -628,112 +117,6 @@ async def _get_tool(mcp, name: str): class TestAutomationExceptionPaths: """Test automation exception paths.""" - @pytest.mark.asyncio - async def test_start_macro_recording_adapter_error(self): - """Line 341 — adapter has method but returns error.""" - from solidworks_mcp.tools.automation import ( - RecordMacroInput, - register_automation_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.start_macro_recording = AsyncMock( - return_value=AdapterResult( - status=AdapterResultStatus.ERROR, error="rec error" - ) - ) - await register_automation_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "automation_start_macro_recording") - result = await fn(RecordMacroInput(macro_name="test", description="d")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_start_macro_recording_exception(self): - """Lines 387-389 — exception in start_macro_recording.""" - from solidworks_mcp.tools.automation import ( - RecordMacroInput, - register_automation_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.start_macro_recording = AsyncMock(side_effect=RuntimeError("boom")) - await register_automation_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "automation_start_macro_recording") - result = await fn(RecordMacroInput(macro_name="test", description="d")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_stop_macro_recording_exception(self): - """Line 412 — exception in stop_macro_recording.""" - from solidworks_mcp.tools.automation import register_automation_tools - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - - # Patch the inner dict-return path to raise - with patch("solidworks_mcp.tools.tool_boundary.logger"): - await register_automation_tools(mcp, adapter, _make_config()) - fn = await _get_tool(mcp, "automation_stop_macro_recording") - - # Trigger exception by patching after registration - - async def _raiser(input_data): - """Test raiser.""" - - raise RuntimeError("stop error") - - with patch.object( - fn, - "__wrapped__", - create=True, - new=AsyncMock(side_effect=RuntimeError("stop")), - ): - # stop_macro_recording refuses unconditionally: no adapter - # capability exists for it, so it never fabricates a - # "recording stopped" result. - result = await fn({}) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_batch_process_files_exception(self): - """Line 462 — exception in batch_process_files.""" - from solidworks_mcp.tools.automation import ( - BatchProcessInput, - register_automation_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.batch_process_files = AsyncMock(side_effect=RuntimeError("batch boom")) - await register_automation_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "batch_process_files") - result = await fn( - BatchProcessInput(source_directory="/tmp", operation_type="rebuild") - ) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_manage_design_table_exception(self): - """Line 506 — exception in manage_design_table.""" - from solidworks_mcp.tools.automation import ( - DesignTableInput, - register_automation_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.manage_design_table = AsyncMock(side_effect=RuntimeError("dt boom")) - await register_automation_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "manage_design_table") - result = await fn(DesignTableInput(table_type="create", excel_file="test.xlsx")) - assert result["status"] == "error" - @pytest.mark.parametrize( ("description", "expected"), diff --git a/tests/solidworks_mcp/tools/test_drawing.py b/tests/solidworks_mcp/tools/test_drawing.py index c89d2836..97a03c9d 100644 --- a/tests/solidworks_mcp/tools/test_drawing.py +++ b/tests/solidworks_mcp/tools/test_drawing.py @@ -9,7 +9,6 @@ from solidworks_mcp.tools.drawing import ( AddDimensionInput, AddNoteInput, - AnnotationInput, AutoCenterMarksInput, CreateDetailViewInput, CreateDrawingViewInput, @@ -155,47 +154,6 @@ async def test_add_dimension_success(self, mcp_server, mock_adapter, mock_config assert result["data"]["tolerance"] == "±0.1" mock_adapter.add_dimension.assert_called_once() - @pytest.mark.asyncio - async def test_add_annotation_success(self, mcp_server, mock_adapter, mock_config): - """Test successful annotation addition.""" - await register_drawing_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.add_annotation = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "annotation_text": "Material: Steel AISI 1020", - "annotation_type": "Note", - "position": [200.0, 280.0], - "font_size": 12, - "leader_attached": False, - }, - execution_time=0.2, - ) - ) - - input_data = AnnotationInput( - drawing_path="part_drawing.slddrw", - annotation_type="Note", - text="Material: Steel AISI 1020", - position=[200.0, 280.0], - font_size=12, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "add_annotation": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["annotation_text"] == "Material: Steel AISI 1020" - assert result["data"]["font_size"] == 12 - mock_adapter.add_annotation.assert_called_once() - @pytest.mark.asyncio async def test_update_title_block_success( self, mcp_server, mock_adapter, mock_config @@ -438,17 +396,6 @@ def test_dimension_input_validation(self): assert valid_input.dimension_type == "Linear" assert len(valid_input.entities) == 2 - @pytest.mark.unit - def test_annotation_input_validation(self): - """Test input validation for annotation operations.""" - # Valid input - valid_input = AnnotationInput( - drawing_path="test.slddrw", annotation_type="Note", text="Test note" - ) - assert valid_input.drawing_path == "test.slddrw" - assert valid_input.annotation_type == "Note" - assert valid_input.text == "Test note" - class TestDrawingToolsBranchCoverage: """Branch coverage for uncovered drawing tool paths.""" @@ -478,16 +425,6 @@ def test_dimension_input_single_entity_normalization(self): assert inp.entity2 is None assert inp.position_x == 5.0 - def test_annotation_input_position_normalization(self): - """AnnotationInput.model_post_init extracts position_x/y from position list.""" - inp = AnnotationInput( - annotation_type="Note", - text="Hello", - position=[30.0, 40.0], - ) - assert inp.position_x == 30.0 - assert inp.position_y == 40.0 - # ── add_dimension: simulation path + exception ─────────────────────── @pytest.mark.asyncio @@ -634,56 +571,6 @@ async def test_add_drawing_view_reports_the_real_outcome( assert result["status"] == "error" assert "add_drawing_view" in result["message"] - # ── add_annotation: adapter error + no-adapter simulation paths ──────── - - @pytest.mark.asyncio - async def test_add_annotation_adapter_error( - self, mcp_server, mock_adapter, mock_config - ): - """Add_annotation returns error when adapter.add_annotation returns is_success=False.""" - await register_drawing_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.add_annotation = AsyncMock( - return_value=Mock( - is_success=False, error="annotation failed", execution_time=0.1 - ) - ) - input_data = AnnotationInput( - annotation_type="Note", - text="Test", - position_x=10.0, - position_y=20.0, - ) - tool_func = next( - (t.fn for t in await mcp_server.list_tools() if t.name == "add_annotation"), - None, - ) - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_add_annotation_no_adapter_simulation( - self, mcp_server, mock_adapter, mock_config - ): - """Add_annotation refuses when adapter lacks add_annotation, rather - than inventing an annotation.""" - await register_drawing_tools(mcp_server, mock_adapter, mock_config) - if hasattr(mock_adapter, "add_annotation"): - del mock_adapter.add_annotation - - input_data = AnnotationInput( - annotation_type="Note", - text="MaterialSpec", - position_x=100.0, - position_y=200.0, - ) - tool_func = next( - (t.fn for t in await mcp_server.list_tools() if t.name == "add_annotation"), - None, - ) - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "does not support add_annotation" in result["message"] - # ── update_title_block: adapter error + no-adapter paths ─────────────── @pytest.mark.asyncio @@ -733,99 +620,6 @@ async def test_update_title_block_no_adapter_simulation( assert result["status"] == "error" assert "does not support update_title_block" in result["message"] - @pytest.mark.asyncio - async def test_typed_drawing_tools_default_error_messages( - self, mcp_server, mock_adapter, mock_config - ): - """Covers fallback error message branches when adapter returns no error text.""" - await register_drawing_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.create_technical_drawing = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - mock_adapter.add_drawing_view = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - mock_adapter.add_annotation = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - mock_adapter.update_title_block = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - - by_name = {t.name: t.fn for t in await mcp_server.list_tools()} - - r1 = await by_name["create_technical_drawing"]( - input_data=DrawingCreationInput(model_file="part.sldprt") - ) - r2 = await by_name["add_drawing_view"]( - input_data=DrawingViewInput( - drawing_path="d.slddrw", - view_type="Front", - view_name="Front", - ) - ) - r3 = await by_name["add_annotation"]( - input_data=AnnotationInput( - annotation_type="Note", - text="x", - position_x=1.0, - position_y=2.0, - ) - ) - r4 = await by_name["update_title_block"](input_data={"title": "Widget"}) - - assert r1["status"] == "error" - assert r1["message"] == "Failed to create technical drawing" - assert r2["status"] == "error" - assert r2["message"] == "Failed to add drawing view" - assert r3["status"] == "error" - assert r3["message"] == "Failed to add annotation" - assert r4["status"] == "error" - assert r4["message"] == "Failed to update title block" - - @pytest.mark.asyncio - async def test_typed_drawing_tools_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover exception handlers for typed drawing tools.""" - await register_drawing_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.create_technical_drawing = AsyncMock( - side_effect=RuntimeError("create boom") - ) - mock_adapter.add_drawing_view = AsyncMock(side_effect=RuntimeError("view boom")) - mock_adapter.add_annotation = AsyncMock(side_effect=RuntimeError("note boom")) - mock_adapter.update_title_block = AsyncMock( - side_effect=RuntimeError("title boom") - ) - - by_name = {t.name: t.fn for t in await mcp_server.list_tools()} - - r1 = await by_name["create_technical_drawing"]( - input_data=DrawingCreationInput(model_file="part.sldprt") - ) - r2 = await by_name["add_drawing_view"]( - input_data=DrawingViewInput( - drawing_path="d.slddrw", - view_type="Front", - view_name="Front", - ) - ) - r3 = await by_name["add_annotation"]( - input_data=AnnotationInput( - annotation_type="Note", - text="x", - position_x=1.0, - position_y=2.0, - ) - ) - r4 = await by_name["update_title_block"](input_data={"title": "Widget"}) - - for result in (r1, r2, r3, r4): - assert result["status"] == "error" - assert result["error_type"] == "internal" - # ── additional drawing tool branches (legacy tool set) ─────────────── @pytest.mark.asyncio diff --git a/tests/solidworks_mcp/tools/test_drawing_analysis.py b/tests/solidworks_mcp/tools/test_drawing_analysis.py index ebd627ad..e1019e13 100644 --- a/tests/solidworks_mcp/tools/test_drawing_analysis.py +++ b/tests/solidworks_mcp/tools/test_drawing_analysis.py @@ -1,32 +1,17 @@ """Tests for SolidWorks drawing analysis tools.""" from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock import pytest from fastmcp import FastMCP -from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus -from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter from solidworks_mcp.config import ( AdapterType, DeploymentMode, SecurityLevel, SolidWorksMCPConfig, ) -from solidworks_mcp.tools.drawing import ( - AnnotationInput, - DrawingCreationInput, - DrawingViewInput, - register_drawing_tools, -) -from solidworks_mcp.tools.drawing_analysis import ( - AnnotationAnalysisInput, - ComplianceCheckInput, - DimensionAnalysisInput, - DrawingAnalysisInput, - register_drawing_analysis_tools, -) +from solidworks_mcp.tools.drawing_analysis import register_drawing_analysis_tools class TestDrawingAnalysisTools: @@ -40,608 +25,7 @@ async def test_register_drawing_analysis_tools( tool_count = await register_drawing_analysis_tools( mcp_server, mock_adapter, mock_config ) - assert tool_count == 8 - - @pytest.mark.asyncio - async def test_analyze_drawing_comprehensive_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful comprehensive drawing analysis.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_comprehensive = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "analysis_summary": { - "total_views": 4, - "total_dimensions": 28, - "total_annotations": 12, - "compliance_score": 85.5, - "completeness_score": 92.3, - "quality_rating": "Good", - }, - "view_analysis": [ - { - "view_name": "Drawing View1", - "type": "Front", - "scale": "1:1", - "status": "Complete", - }, - { - "view_name": "Drawing View2", - "type": "Right", - "scale": "1:1", - "status": "Complete", - }, - { - "view_name": "Drawing View3", - "type": "Top", - "scale": "1:1", - "status": "Missing dimensions", - }, - { - "view_name": "Drawing View4", - "type": "Isometric", - "scale": "1:2", - "status": "Complete", - }, - ], - "dimension_analysis": { - "critical_dimensions": 18, - "reference_dimensions": 10, - "missing_dimensions": ["Overall height", "Hole diameter"], - "dimension_tolerances": "Standard", - }, - "annotation_analysis": { - "surface_finish_symbols": 6, - "geometric_tolerances": 4, - "notes": 8, - "missing_annotations": [ - "Material specification", - "Heat treatment note", - ], - }, - "issues_found": [ - { - "severity": "Medium", - "type": "Missing dimension", - "description": "Overall height not dimensioned", - }, - { - "severity": "Low", - "type": "Missing note", - "description": "Material specification note missing", - }, - ], - }, - execution_time=3.2, - ) - ) - - input_data = DrawingAnalysisInput( - drawing_path="part_drawing.slddrw", - analysis_depth="Comprehensive", - check_dimensions=True, - check_annotations=True, - check_compliance=True, - standards=["ISO", "ASME"], - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_comprehensive": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["analysis_summary"]["total_views"] == 4 - assert result["data"]["analysis_summary"]["compliance_score"] == 85.5 - assert len(result["data"]["view_analysis"]) == 4 - assert len(result["data"]["issues_found"]) == 2 - mock_adapter.analyze_drawing_comprehensive.assert_called_once() - - @pytest.mark.asyncio - async def test_analyze_drawing_dimensions_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful drawing dimension analysis.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_dimensions = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "dimension_summary": { - "total_dimensions": 28, - "linear_dimensions": 18, - "angular_dimensions": 4, - "radial_dimensions": 6, - "toleranced_dimensions": 15, - "reference_dimensions": 8, - }, - "dimension_quality": { - "placement_score": 88.5, - "readability_score": 91.2, - "standards_compliance": 85.0, - "completeness": 92.8, - }, - "dimension_issues": [ - {"type": "Overlapping", "count": 2, "severity": "Medium"}, - {"type": "Missing tolerance", "count": 3, "severity": "High"}, - {"type": "Poor placement", "count": 1, "severity": "Low"}, - ], - "recommendations": [ - "Add tolerances to critical dimensions", - "Reposition overlapping dimensions", - "Consider adding reference dimensions for manufacturing", - ], - "standards_analysis": { - "iso_compliance": 87.5, - "asme_compliance": 82.0, - "company_standards": 90.0, - }, - }, - execution_time=1.8, - ) - ) - - input_data = DimensionAnalysisInput( - drawing_path="part_drawing.slddrw", - analysis_type="Quality assessment", - check_tolerances=True, - check_placement=True, - standards_compliance=True, - reference_standards=["ISO 129", "ASME Y14.5"], - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_dimensions": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["dimension_summary"]["total_dimensions"] == 28 - assert result["data"]["dimension_quality"]["placement_score"] == 88.5 - assert len(result["data"]["dimension_issues"]) == 3 - assert len(result["data"]["recommendations"]) == 3 - mock_adapter.analyze_drawing_dimensions.assert_called_once() - - @pytest.mark.asyncio - async def test_analyze_drawing_annotations_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful drawing annotation analysis.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_annotations = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "annotation_summary": { - "total_annotations": 15, - "surface_finish_symbols": 8, - "geometric_tolerances": 5, - "welding_symbols": 0, - "notes_and_labels": 12, - "balloons": 0, - }, - "annotation_quality": { - "symbol_correctness": 95.0, - "placement_quality": 87.5, - "readability": 92.0, - "standards_compliance": 88.0, - }, - "annotation_issues": [ - { - "type": "Symbol placement", - "description": "Surface finish symbol too close to dimension", - "severity": "Low", - }, - { - "type": "Missing symbol", - "description": "Geometric tolerance needed for hole position", - "severity": "Medium", - }, - { - "type": "Text size", - "description": "Note text too small for standard", - "severity": "Low", - }, - ], - "missing_annotations": [ - "Material specification note", - "Heat treatment requirements", - "Inspection notes", - ], - "standards_analysis": { - "symbol_standards": "ISO 1302", - "geometric_tolerance_standards": "ISO 1101", - "compliance_level": "Good", - }, - }, - execution_time=1.5, - ) - ) - - input_data = AnnotationAnalysisInput( - drawing_path="part_drawing.slddrw", - analysis_scope="All annotations", - check_symbols=True, - check_geometric_tolerances=True, - check_surface_finish=True, - standards_verification=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_annotations": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["annotation_summary"]["total_annotations"] == 15 - assert result["data"]["annotation_quality"]["symbol_correctness"] == 95.0 - assert len(result["data"]["annotation_issues"]) == 3 - assert len(result["data"]["missing_annotations"]) == 3 - mock_adapter.analyze_drawing_annotations.assert_called_once() - - @pytest.mark.asyncio - async def test_check_drawing_compliance_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful drawing compliance checking.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.check_drawing_compliance = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "compliance_overview": { - "overall_compliance": 87.5, - "iso_compliance": 89.0, - "asme_compliance": 85.5, - "company_compliance": 88.0, - "status": "Compliant with minor issues", - }, - "compliance_details": { - "title_block": {"score": 95.0, "issues": 1}, - "dimensions": {"score": 85.0, "issues": 3}, - "annotations": {"score": 90.0, "issues": 2}, - "views": {"score": 88.0, "issues": 2}, - "line_weights": {"score": 92.0, "issues": 1}, - "text_standards": {"score": 87.0, "issues": 2}, - }, - "violations": [ - { - "standard": "ISO 5807", - "rule": "Title block completeness", - "severity": "Medium", - "description": "Missing revision date in title block", - }, - { - "standard": "ASME Y14.5", - "rule": "Dimension tolerances", - "severity": "High", - "description": "Critical dimensions missing tolerances", - }, - { - "standard": "Company Standard", - "rule": "Material callout", - "severity": "Medium", - "description": "Material specification note required", - }, - ], - "recommendations": [ - "Add revision date to title block", - "Add tolerances to critical dimensions", - "Include material specification note", - "Review dimension placement standards", - ], - }, - execution_time=2.1, - ) - ) - - input_data = ComplianceCheckInput( - drawing_path="part_drawing.slddrw", - standards_to_check=["ISO 5807", "ASME Y14.5", "Company Standard"], - compliance_level="Standard", - generate_report=True, - check_title_block=True, - check_dimensions=True, - check_annotations=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "check_drawing_compliance": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["compliance_overview"]["overall_compliance"] == 87.5 - assert ( - result["data"]["compliance_overview"]["status"] - == "Compliant with minor issues" - ) - assert len(result["data"]["violations"]) == 3 - assert len(result["data"]["recommendations"]) == 4 - mock_adapter.check_drawing_compliance.assert_called_once() - - @pytest.mark.asyncio - async def test_analyze_drawing_views_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful drawing views analysis.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_views = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "view_analysis": { - "total_views": 6, - "standard_views": 4, - "auxiliary_views": 1, - "detail_views": 1, - "section_views": 0, - "broken_out_sections": 0, - }, - "view_quality": { - "arrangement_score": 88.5, - "clarity_score": 91.0, - "completeness_score": 85.0, - "efficiency_score": 87.5, - }, - "view_details": [ - { - "view_name": "Drawing View1", - "type": "Front", - "scale": "1:1", - "position": [100, 200], - "quality_score": 92.0, - "issues": [], - }, - { - "view_name": "Drawing View2", - "type": "Right", - "scale": "1:1", - "position": [250, 200], - "quality_score": 89.0, - "issues": ["Minor dimension overlap"], - }, - ], - "optimization_suggestions": [ - "Consider adding section view for internal features", - "Improve spacing between views for clarity", - "Add detail view for small features", - ], - "missing_views": [ - "Section A-A for internal features", - "Detail view for threaded holes", - ], - }, - execution_time=1.4, - ) - ) - - input_data = { - "drawing_path": "part_drawing.slddrw", - "analysis_type": "View optimization", - "check_arrangement": True, - "check_completeness": True, - "suggest_improvements": True, - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_views": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["view_analysis"]["total_views"] == 6 - assert result["data"]["view_quality"]["arrangement_score"] == 88.5 - assert len(result["data"]["view_details"]) == 2 - assert len(result["data"]["optimization_suggestions"]) == 3 - mock_adapter.analyze_drawing_views.assert_called_once() - - @pytest.mark.asyncio - async def test_generate_drawing_report_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful drawing report generation.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.generate_drawing_report = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "drawing_file": "part_drawing.slddrw", - "report_file": "drawing_analysis_report.pdf", - "report_sections": [ - "Executive Summary", - "Drawing Overview", - "Dimension Analysis", - "Annotation Review", - "Compliance Check", - "Quality Assessment", - "Recommendations", - ], - "report_statistics": { - "total_pages": 8, - "charts_included": 5, - "images_included": 12, - "tables_included": 6, - }, - "key_findings": [ - "Overall compliance: 87.5%", - "28 dimensions analyzed", - "15 annotations reviewed", - "3 compliance violations found", - "Quality rating: Good", - ], - "export_formats": ["PDF", "HTML", "Excel"], - "generation_time": 4.2, - }, - execution_time=4.2, - ) - ) - - input_data = { - "drawing_path": "part_drawing.slddrw", - "report_type": "Comprehensive", - "include_images": True, - "include_charts": True, - "export_format": "PDF", - "output_path": "reports/drawing_analysis_report.pdf", - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "generate_drawing_report": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["report_file"] == "drawing_analysis_report.pdf" - assert result["data"]["report_statistics"]["total_pages"] == 8 - assert len(result["data"]["key_findings"]) == 5 - mock_adapter.generate_drawing_report.assert_called_once() - - @pytest.mark.asyncio - async def test_drawing_analysis_error_handling( - self, mcp_server, mock_adapter, mock_config - ): - """Test error handling in drawing analysis.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_comprehensive = AsyncMock( - return_value=Mock( - is_success=False, - error="Drawing file is corrupted or invalid", - execution_time=0.1, - ) - ) - - input_data = DrawingAnalysisInput( - drawing_path="corrupted_drawing.slddrw", analysis_depth="Basic" - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_comprehensive": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "corrupted or invalid" in result["message"] - - @pytest.mark.asyncio - async def test_drawing_analysis_fallback_paths_refuse( - self, mcp_server, mock_config - ): - """Drawing analysis tools refuse rather than inventing results when the - adapter has no matching capability.""" - await register_drawing_analysis_tools(mcp_server, object(), mock_config) - - comprehensive_tool = None - dimension_tool = None - annotation_tool = None - compliance_tool = None - completeness_tool = None - - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_comprehensive": - comprehensive_tool = tool.fn - if tool.name == "analyze_drawing_dimensions": - dimension_tool = tool.fn - if tool.name == "analyze_drawing_annotations": - annotation_tool = tool.fn - if tool.name == "check_drawing_compliance": - compliance_tool = tool.fn - if tool.name == "validate_drawing_completeness": - completeness_tool = tool.fn - - assert comprehensive_tool is not None - assert dimension_tool is not None - assert annotation_tool is not None - assert compliance_tool is not None - assert completeness_tool is not None - - comprehensive_result = await comprehensive_tool( - input_data=DrawingAnalysisInput(drawing_path="demo.slddrw") - ) - assert comprehensive_result["status"] == "error" - assert ( - "does not support analyze_drawing_comprehensive" - in (comprehensive_result["message"]) - ) - - dimension_result = await dimension_tool( - input_data=DimensionAnalysisInput(drawing_path="demo.slddrw") - ) - assert dimension_result["status"] == "error" - assert ( - "does not support analyze_drawing_dimensions" - in (dimension_result["message"]) - ) - - annotation_result = await annotation_tool( - input_data=AnnotationAnalysisInput(drawing_path="demo.slddrw") - ) - assert annotation_result["status"] == "error" - assert ( - "does not support analyze_drawing_annotations" - in (annotation_result["message"]) - ) - - compliance_result = await compliance_tool( - input_data=ComplianceCheckInput(drawing_path="demo.slddrw", standard="ISO") - ) - assert compliance_result["status"] == "error" - assert ( - "does not support check_drawing_compliance" - in (compliance_result["message"]) - ) - - completeness_result = await completeness_tool( - input_data={ - "drawing_path": "demo.slddrw", - "manufacturing_type": "machining", - } - ) - assert completeness_result["status"] == "error" - assert ( - "does not support validate_drawing_completeness" - in (completeness_result["message"]) - ) + assert tool_count == 1 @pytest.mark.asyncio async def test_compare_drawing_versions_reads_real_files( @@ -703,222 +87,6 @@ async def test_compare_drawing_versions_reads_real_files( b"different content, longer" ) - len(b"same content") - @pytest.mark.asyncio - async def test_drawing_analysis_adapter_error_and_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Test adapter error returns and exception handlers across drawing analysis tools.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_views = AsyncMock( - return_value=Mock(is_success=False, error="view analysis failed") - ) - mock_adapter.generate_drawing_report = AsyncMock( - return_value=Mock(is_success=False, error="report generation failed") - ) - - view_tool = None - report_tool = None - compare_tool = None - completeness_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_views": - view_tool = tool.fn - if tool.name == "generate_drawing_report": - report_tool = tool.fn - if tool.name == "compare_drawing_versions": - compare_tool = tool.fn - if tool.name == "validate_drawing_completeness": - completeness_tool = tool.fn - - assert view_tool is not None - assert report_tool is not None - assert compare_tool is not None - assert completeness_tool is not None - - view_error = await view_tool(input_data={"drawing_path": "demo.slddrw"}) - assert view_error["status"] == "error" - assert "view analysis failed" in view_error["message"] - - report_error = await report_tool(input_data={"drawing_path": "demo.slddrw"}) - assert report_error["status"] == "error" - assert "report generation failed" in report_error["message"] - - # "a" and "b" are not real files on disk, so compare_drawing_versions - # must refuse rather than inventing a diff. - compare_missing_files = await compare_tool( - input_data={"drawing_version_1": "a", "drawing_version_2": "b"} - ) - assert compare_missing_files["status"] == "error" - assert "not found on disk" in compare_missing_files["message"] - - # mock_adapter has no validate_drawing_completeness method, so the - # tool must refuse rather than inventing a completeness score. - completeness_refuses = await completeness_tool( - input_data={"drawing_path": "demo.slddrw"} - ) - assert completeness_refuses["status"] == "error" - assert ( - "does not support validate_drawing_completeness" - in completeness_refuses["message"] - ) - - @pytest.mark.asyncio - async def test_drawing_analysis_annotation_and_compliance_adapter_errors( - self, mcp_server, mock_adapter, mock_config - ): - """Cover adapter error branches for annotation and compliance tools.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_annotations = AsyncMock( - return_value=Mock(is_success=False, error="annotation analysis failed") - ) - mock_adapter.check_drawing_compliance = AsyncMock( - return_value=Mock(is_success=False, error="compliance failed") - ) - - annotation_tool = None - compliance_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_annotations": - annotation_tool = tool.fn - if tool.name == "check_drawing_compliance": - compliance_tool = tool.fn - - assert annotation_tool is not None - assert compliance_tool is not None - - annotation_error = await annotation_tool( - input_data=AnnotationAnalysisInput(drawing_path="demo.slddrw") - ) - assert annotation_error["status"] == "error" - assert "annotation analysis failed" in annotation_error["message"] - - compliance_error = await compliance_tool( - input_data=ComplianceCheckInput(drawing_path="demo.slddrw", standard="ISO") - ) - assert compliance_error["status"] == "error" - assert "compliance failed" in compliance_error["message"] - - @pytest.mark.asyncio - async def test_drawing_analysis_exception_handlers( - self, mcp_server, mock_adapter, mock_config - ): - """Test exception branches for view/report/version/completeness tools.""" - await register_drawing_analysis_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_drawing_views = AsyncMock( - side_effect=RuntimeError("views crashed") - ) - mock_adapter.generate_drawing_report = AsyncMock( - side_effect=RuntimeError("report crashed") - ) - - view_tool = None - report_tool = None - compare_tool = None - completeness_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_drawing_views": - view_tool = tool.fn - if tool.name == "generate_drawing_report": - report_tool = tool.fn - if tool.name == "compare_drawing_versions": - compare_tool = tool.fn - if tool.name == "validate_drawing_completeness": - completeness_tool = tool.fn - - view_exception = await view_tool(input_data={"drawing_path": "demo.slddrw"}) - assert view_exception["status"] == "error" - assert view_exception["error_type"] == "internal" - - report_exception = await report_tool(input_data={"drawing_path": "demo.slddrw"}) - assert report_exception["status"] == "error" - assert report_exception["error_type"] == "internal" - - # A typed input: a list is refused as bad input, not a crash. - compare_exception = await compare_tool(input_data=[]) - assert compare_exception["status"] == "error" - assert compare_exception["error_type"] == "invalid_input" - - completeness_exception = await completeness_tool(input_data=[]) - assert completeness_exception["status"] == "error" - assert completeness_exception["error_type"] == "internal" - - @pytest.mark.unit - def test_drawing_analysis_input_validation(self): - """Test input validation for drawing analysis.""" - # Valid input - valid_input = DrawingAnalysisInput( - drawing_path="test.slddrw", analysis_depth="Basic" - ) - assert valid_input.drawing_path == "test.slddrw" - assert valid_input.analysis_depth == "Basic" - - # Test with optional parameters - full_input = DrawingAnalysisInput( - drawing_path="test.slddrw", - analysis_depth="Comprehensive", - check_dimensions=True, - check_annotations=False, - standards=["ISO", "ASME"], - ) - assert full_input.check_dimensions is True - assert full_input.check_annotations is False - assert "ISO" in full_input.standards - - @pytest.mark.unit - def test_compliance_check_input_validation(self): - """Test input validation for compliance checking.""" - # Valid input - valid_input = ComplianceCheckInput( - drawing_path="test.slddrw", standards_to_check=["ISO 5807"] - ) - assert valid_input.drawing_path == "test.slddrw" - assert len(valid_input.standards_to_check) == 1 - - # Test with optional parameters - full_input = ComplianceCheckInput( - drawing_path="test.slddrw", - standards_to_check=["ISO 5807", "ASME Y14.5"], - compliance_level="Strict", - generate_report=True, - check_title_block=False, - ) - assert full_input.compliance_level == "Strict" - assert full_input.generate_report is True - assert full_input.check_title_block is False - - -@pytest.mark.asyncio -async def test_validate_drawing_completeness_success(mcp_server, mock_config) -> None: - """An adapter that can validate returns its data and timing unchanged.""" - from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus - - adapter = Mock() - adapter.validate_drawing_completeness = AsyncMock( - return_value=AdapterResult( - status=AdapterResultStatus.SUCCESS, - data={"complete": True, "missing": []}, - execution_time=0.2, - ) - ) - await register_drawing_analysis_tools(mcp_server, adapter, mock_config) - tool = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "validate_drawing_completeness" - ) - - result = await tool({"drawing_path": "a.slddrw"}) - - assert result == { - "status": "success", - "message": "Drawing completeness validation completed", - "data": {"complete": True, "missing": []}, - "execution_time": 0.2, - } - def _ok(data): """Test helper for ok.""" @@ -949,138 +117,10 @@ async def add_drawing_view(self, *_args, **_kwargs): """Test helper for add drawing view.""" return _ok({"view_name": "Front"}) - async def add_annotation(self, *_args, **_kwargs): - """Test helper for add annotation.""" - return _ok({"annotation": "ok"}) - async def update_title_block(self, *_args, **_kwargs): """Test helper for update title block.""" return _ok({"title": "T"}) - async def analyze_drawing_comprehensive(self, *_args, **_kwargs): - """Test helper for analyze drawing comprehensive.""" - return _ok({"score": 90}) - - async def analyze_drawing_dimensions(self, *_args, **_kwargs): - """Test helper for analyze drawing dimensions.""" - return _ok({"dims": 10}) - - async def analyze_drawing_annotations(self, *_args, **_kwargs): - """Test helper for analyze drawing annotations.""" - return _ok({"notes": 3}) - - async def check_drawing_compliance(self, *_args, **_kwargs): - """Test helper for check drawing compliance.""" - return _ok({"compliant": True}) - - async def analyze_drawing_views(self, *_args, **_kwargs): - """Test helper for analyze drawing views.""" - return _ok({"views": 4}) - - async def generate_drawing_report(self, *_args, **_kwargs): - """Test helper for generate drawing report.""" - return _ok({"report": "ok"}) - - -@pytest.mark.asyncio -async def test_drawing_analysis_refuses_without_adapter_support( - mcp_server, mock_config -): - """Drawing analysis tools refuse rather than inventing a result when the - adapter (a plain `object()` here) has no matching capability.""" - await register_drawing_analysis_tools(mcp_server, object(), mock_config) - - assert ( - await (await _tool(mcp_server, "analyze_drawing_comprehensive"))( - input_data=DrawingAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "error" - assert ( - await (await _tool(mcp_server, "analyze_drawing_dimensions"))( - input_data=DimensionAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "error" - assert ( - await (await _tool(mcp_server, "analyze_drawing_annotations"))( - input_data=AnnotationAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "error" - assert ( - await (await _tool(mcp_server, "check_drawing_compliance"))( - input_data=ComplianceCheckInput(drawing_path="a.slddrw") - ) - )["status"] == "error" - assert ( - await (await _tool(mcp_server, "analyze_drawing_views"))( - input_data={"drawing_path": "a.slddrw"} - ) - )["status"] == "error" - assert ( - await (await _tool(mcp_server, "generate_drawing_report"))( - input_data={"drawing_path": "a.slddrw", "report_type": "summary"} - ) - )["status"] == "error" - - -@pytest.mark.asyncio -async def test_drawing_and_analysis_adapter_passthrough_success( - mcp_server, mock_config -): - """Test drawing and analysis adapter passthrough success.""" - adapter = _DrawingAndAnalysisAdapterStub() - await register_drawing_tools(mcp_server, adapter, mock_config) - await register_drawing_analysis_tools(mcp_server, adapter, mock_config) - - assert ( - await (await _tool(mcp_server, "create_technical_drawing"))( - input_data=DrawingCreationInput() - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "add_drawing_view"))( - input_data=DrawingViewInput(view_name="Front") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "add_annotation"))( - input_data=AnnotationInput(text="n", annotation_type="Note") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "update_title_block"))(input_data={"title": "T"}) - )["status"] == "success" - - assert ( - await (await _tool(mcp_server, "analyze_drawing_comprehensive"))( - input_data=DrawingAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "analyze_drawing_dimensions"))( - input_data=DimensionAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "analyze_drawing_annotations"))( - input_data=AnnotationAnalysisInput(drawing_path="a.slddrw") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "check_drawing_compliance"))( - input_data=ComplianceCheckInput(drawing_path="a.slddrw") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "analyze_drawing_views"))( - input_data={"drawing_path": "a.slddrw"} - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "generate_drawing_report"))( - input_data={"drawing_path": "a.slddrw"} - ) - )["status"] == "success" - def _make_mcp(): """Create a plain FastMCP instance.""" @@ -1110,83 +150,3 @@ async def _get_tool(mcp, name: str): class TestDrawingAnalysisExceptionPaths: """Test drawing analysis exception paths.""" - - @pytest.mark.asyncio - async def test_analyze_drawing_dimensions_adapter_error(self): - """Line 294 — adapter returns error result.""" - from solidworks_mcp.tools.drawing_analysis import ( - DimensionAnalysisInput, - register_drawing_analysis_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.analyze_drawing_dimensions = AsyncMock( - return_value=AdapterResult( - status=AdapterResultStatus.ERROR, error="dim error" - ) - ) - await register_drawing_analysis_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "analyze_drawing_dimensions") - result = await fn(DimensionAnalysisInput(drawing_path="test.slddrw")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_analyze_drawing_dimensions_exception(self): - """Lines 376-378 — exception in analyze_drawing_dimensions.""" - from solidworks_mcp.tools.drawing_analysis import ( - DimensionAnalysisInput, - register_drawing_analysis_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.analyze_drawing_dimensions = AsyncMock( - side_effect=RuntimeError("dim boom") - ) - await register_drawing_analysis_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "analyze_drawing_dimensions") - result = await fn(DimensionAnalysisInput(drawing_path="test.slddrw")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_analyze_drawing_annotations_exception(self): - """Line 415 — exception in analyze_drawing_annotations.""" - from solidworks_mcp.tools.drawing_analysis import ( - AnnotationAnalysisInput, - register_drawing_analysis_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.analyze_drawing_annotations = AsyncMock( - side_effect=RuntimeError("ann boom") - ) - await register_drawing_analysis_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "analyze_drawing_annotations") - result = await fn(AnnotationAnalysisInput(drawing_path="test.slddrw")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_check_drawing_compliance_exception(self): - """Lines 512-514 — exception in check_drawing_compliance.""" - from solidworks_mcp.tools.drawing_analysis import ( - ComplianceCheckInput, - register_drawing_analysis_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.check_drawing_compliance = AsyncMock( - side_effect=RuntimeError("comp boom") - ) - await register_drawing_analysis_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "check_drawing_compliance") - result = await fn( - ComplianceCheckInput(drawing_path="test.slddrw", standard="ASME") - ) - assert result["status"] == "error" diff --git a/tests/solidworks_mcp/tools/test_export.py b/tests/solidworks_mcp/tools/test_export.py index 68e0d1ca..bf500e62 100644 --- a/tests/solidworks_mcp/tools/test_export.py +++ b/tests/solidworks_mcp/tools/test_export.py @@ -7,7 +7,6 @@ from fastmcp import FastMCP from solidworks_mcp.tools.export import ( - BatchExportInput, ExportFileInput, ExportImageInput, register_export_tools, @@ -21,7 +20,7 @@ class TestExportTools: async def test_register_export_tools(self, mcp_server, mock_adapter, mock_config): """Test that export tools register correctly.""" tool_count = await register_export_tools(mcp_server, mock_adapter, mock_config) - assert tool_count == 7 + assert tool_count == 6 @pytest.mark.asyncio async def test_export_step_success(self, mcp_server, mock_adapter, mock_config): @@ -239,75 +238,6 @@ async def test_export_image_success(self, mcp_server, mock_adapter, mock_config) assert result["data"]["resolution"] == "1920x1080" mock_adapter.export_image.assert_called_once() - @pytest.mark.asyncio - async def test_batch_export_success(self, mcp_server, mock_adapter, mock_config): - """Test successful batch export operation.""" - await register_export_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_export = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "total_files": 5, - "exported_files": 5, - "failed_files": 0, - "export_format": "STEP", - "total_time": 3.8, - "results": [ - { - "file": "part1.sldprt", - "status": "success", - "output": "part1.step", - }, - { - "file": "part2.sldprt", - "status": "success", - "output": "part2.step", - }, - { - "file": "part3.sldprt", - "status": "success", - "output": "part3.step", - }, - { - "file": "part4.sldprt", - "status": "success", - "output": "part4.step", - }, - { - "file": "part5.sldprt", - "status": "success", - "output": "part5.step", - }, - ], - }, - execution_time=3.8, - ) - ) - - input_data = BatchExportInput( - source_directory="./parts/", - output_directory="./exports/", - export_format="STEP", - file_pattern="*.sldprt", - include_subdirectories=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_export": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_files"] == 5 - assert result["data"]["failed_files"] == 0 - assert result["data"]["export_format"] == "STEP" - mock_adapter.batch_export.assert_called_once() - @pytest.mark.asyncio async def test_export_error_handling(self, mcp_server, mock_adapter, mock_config): """Test error handling in export operations.""" @@ -333,128 +263,10 @@ async def test_export_error_handling(self, mcp_server, mock_adapter, mock_config assert result["status"] == "error" assert "Output directory does not exist" in result["message"] - @pytest.mark.unit - def test_batch_export_input_validation(self): - """Test input validation for batch export.""" - # Valid input - valid_input = BatchExportInput( - source_directory="./parts/", - output_directory="./exports/", - export_format="STEP", - ) - assert valid_input.source_directory == "./parts/" - assert valid_input.export_format == "STEP" - - # Test with optional parameters - full_input = BatchExportInput( - source_directory="./parts/", - output_directory="./exports/", - export_format="IGES", - file_pattern="*.sld*", - include_subdirectories=True, - ) - assert full_input.file_pattern == "*.sld*" - assert full_input.include_subdirectories is True - class TestExportToolsBranchCoverage: """Additional branch coverage for export error and exception paths.""" - @pytest.mark.asyncio - async def test_remaining_export_error_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover non-success adapter branches across remaining export tools.""" - await register_export_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.export_iges = AsyncMock( - return_value=Mock(is_success=False, error="iges failed", execution_time=0.1) - ) - mock_adapter.export_stl = AsyncMock( - return_value=Mock(is_success=False, error="stl failed", execution_time=0.1) - ) - mock_adapter.export_pdf = AsyncMock( - return_value=Mock(is_success=False, error="pdf failed", execution_time=0.1) - ) - mock_adapter.export_dwg = AsyncMock( - return_value=Mock(is_success=False, error="dwg failed", execution_time=0.1) - ) - # exercise default fallback message branches where error is missing - mock_adapter.export_image = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - mock_adapter.batch_export = AsyncMock( - return_value=Mock(is_success=False, error=None, execution_time=0.1) - ) - - by_name = {t.name: t.fn for t in await mcp_server.list_tools()} - - r1 = await by_name["export_iges"]( - input_data=ExportFileInput(file_path="a.iges") - ) - r2 = await by_name["export_stl"](input_data=ExportFileInput(file_path="a.stl")) - r3 = await by_name["export_pdf"](input_data=ExportFileInput(file_path="a.pdf")) - r4 = await by_name["export_dwg"](input_data=ExportFileInput(file_path="a.dwg")) - r5 = await by_name["export_image"]( - input_data=ExportImageInput(model_path="a.sldprt", output_path="a.png") - ) - r6 = await by_name["batch_export"]( - input_data=BatchExportInput( - source_directory="./in", - output_directory="./out", - export_format="STEP", - ) - ) - - assert r1["status"] == "error" and "iges failed" in r1["message"].lower() - assert r2["status"] == "error" and "stl failed" in r2["message"].lower() - assert r3["status"] == "error" and "pdf failed" in r3["message"].lower() - assert r4["status"] == "error" and "dwg failed" in r4["message"].lower() - assert ( - r5["status"] == "error" - and "failed to export image" in r5["message"].lower() - ) - assert ( - r6["status"] == "error" and "batch export failed" in r6["message"].lower() - ) - - @pytest.mark.asyncio - async def test_remaining_export_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover exception handlers for IGES/STL/PDF/DWG/image/batch export tools.""" - await register_export_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.export_iges = AsyncMock(side_effect=RuntimeError("boom iges")) - mock_adapter.export_stl = AsyncMock(side_effect=RuntimeError("boom stl")) - mock_adapter.export_pdf = AsyncMock(side_effect=RuntimeError("boom pdf")) - mock_adapter.export_dwg = AsyncMock(side_effect=RuntimeError("boom dwg")) - mock_adapter.export_image = AsyncMock(side_effect=RuntimeError("boom image")) - mock_adapter.batch_export = AsyncMock(side_effect=RuntimeError("boom batch")) - - by_name = {t.name: t.fn for t in await mcp_server.list_tools()} - - results = [ - await by_name["export_iges"](ExportFileInput(file_path="a.iges")), - await by_name["export_stl"](ExportFileInput(file_path="a.stl")), - await by_name["export_pdf"](ExportFileInput(file_path="a.pdf")), - await by_name["export_dwg"](ExportFileInput(file_path="a.dwg")), - await by_name["export_image"]( - ExportImageInput(model_path="a.sldprt", output_path="a.png") - ), - await by_name["batch_export"]( - BatchExportInput( - source_directory="./in", - output_directory="./out", - export_format="STEP", - ) - ), - ] - - for result in results: - assert result["status"] == "error" - assert result["error_type"] == "internal" - @pytest.mark.asyncio async def test_export_step_exception_path( self, mcp_server, mock_adapter, mock_config @@ -608,67 +420,6 @@ async def export_image(self, *_args, **_kwargs): """Test helper for export image.""" return _ok({"fmt": "image"}) - async def batch_export(self, *_args, **_kwargs): - """Test helper for batch export.""" - return _ok({"count": 2}) - - -@pytest.mark.asyncio -async def test_export_tools_fallback_and_aliases(mcp_server, mock_config): - """Test export tools fallback and aliases.""" - await register_export_tools(mcp_server, _ExportFallbackAdapter(), mock_config) - - assert ( - await (await _tool(mcp_server, "export_step"))( - input_data={"file_path": "a.step", "format_type": "step"} - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_iges"))( - input_data=ExportFileInput(file_path="a.igs", format_type="iges") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_stl"))( - input_data=ExportFileInput(file_path="a.stl", format_type="stl") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_pdf"))( - input_data=ExportFileInput(file_path="a.pdf", format_type="pdf") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_dwg"))( - input_data=ExportFileInput(file_path="a.dwg", format_type="dwg") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_image"))( - input_data=ExportImageInput( - output_path="a.png", image_format="png", resolution="800x600" - ) - ) - )["status"] == "success" - # _ExportFallbackAdapter has no batch_export capability (unlike - # export_file, which the single-file export tools fall back to), so - # batch_export must refuse rather than inventing a batch result. - assert ( - await (await _tool(mcp_server, "batch_export"))( - input_data=BatchExportInput( - source_directory="src", - output_directory="out", - export_format="step", - file_pattern="*.sldprt", - ) - ) - )["status"] == "error" - - error_result = await (await _tool(mcp_server, "export_step"))( - input_data={"file_path": None, "format_type": "step"} - ) - assert error_result["status"] == "error" - @pytest.mark.asyncio @pytest.mark.parametrize("adapter_cls", [_ExportFallbackAdapter, _ExportNativeAdapter]) @@ -691,50 +442,6 @@ async def test_export_tools_accept_a_plain_dict( assert f"a.{fmt}" in result["message"] -@pytest.mark.asyncio -async def test_export_tools_native_adapter_methods(mcp_server, mock_config): - """Test export tools native adapter methods.""" - await register_export_tools(mcp_server, _ExportNativeAdapter(), mock_config) - - assert ( - await (await _tool(mcp_server, "export_step"))( - input_data=ExportFileInput(file_path="a.step", format_type="step") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_iges"))( - input_data=ExportFileInput(file_path="a.igs", format_type="iges") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_stl"))( - input_data=ExportFileInput(file_path="a.stl", format_type="stl") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_pdf"))( - input_data=ExportFileInput(file_path="a.pdf", format_type="pdf") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_dwg"))( - input_data=ExportFileInput(file_path="a.dwg", format_type="dwg") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "export_image"))( - input_data=ExportImageInput(file_path="a.png", format_type="png") - ) - )["status"] == "success" - assert ( - await (await _tool(mcp_server, "batch_export"))( - input_data=BatchExportInput( - source_directory="src", output_directory="out", format_type="step" - ) - ) - )["status"] == "success" - - @pytest.mark.asyncio async def test_a_file_export_without_format_type_uses_the_tools_own( mcp_server, mock_adapter, mock_config diff --git a/tests/solidworks_mcp/tools/test_file_management.py b/tests/solidworks_mcp/tools/test_file_management.py index d41777c8..a5845dbb 100644 --- a/tests/solidworks_mcp/tools/test_file_management.py +++ b/tests/solidworks_mcp/tools/test_file_management.py @@ -1,14 +1,14 @@ """Tests for SolidWorks file management tools.""" from pathlib import Path +from typing import Any from unittest.mock import AsyncMock, Mock, patch import pytest +from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter from solidworks_mcp.tools.file_management import ( ActivateDocumentInput, - FileOperationInput, - FormatConversionInput, SaveAsInput, SaveBodyAsPartInput, register_file_management_tools, @@ -33,266 +33,6 @@ async def test_register_file_management_tools( registered_tool_names = {tool.name for tool in await mcp_server.list_tools()} assert tool_count == len(registered_tool_names) - @pytest.mark.asyncio - async def test_manage_file_properties_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful file property management.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.manage_file_properties = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "properties_updated": 5, - "custom_properties": { - "Author": "Test User", - "Description": "Test Part", - "Material": "Steel", - "PartNo": "SW-001", - "Revision": "A", - }, - "system_properties": { - "Created": "2024-01-15", - "Modified": "2024-03-15", - "Size": "1.2 MB", - }, - }, - execution_time=0.4, - ) - ) - - input_data = FileOperationInput( - file_path="test_part.sldprt", - operation="get_properties", - parameters={"include_custom": True, "include_system": True}, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "manage_file_properties": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["properties_updated"] == 5 - assert "Author" in result["data"]["custom_properties"] - assert "Created" in result["data"]["system_properties"] - mock_adapter.manage_file_properties.assert_called_once() - - @pytest.mark.asyncio - async def test_convert_file_format_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful file format conversion.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.convert_file_format = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "source_file": "test_part.sldprt", - "target_file": "test_part.step", - "format_from": "SLDPRT", - "format_to": "STEP", - "file_size": "2.1 MB", - "conversion_time": 1.8, - }, - execution_time=1.8, - ) - ) - - input_data = FormatConversionInput( - source_file="test_part.sldprt", - target_format="STEP", - output_path="exports/test_part.step", - conversion_options={"quality": "high", "units": "mm"}, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "convert_file_format": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["format_to"] == "STEP" - assert result["data"]["target_file"] == "test_part.step" - mock_adapter.convert_file_format.assert_called_once() - - @pytest.mark.asyncio - async def test_batch_file_operations_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful batch file operations.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_file_operations = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "total_files": 3, - "processed_files": 3, - "failed_files": 0, - "results": [ - { - "file": "part1.sldprt", - "status": "success", - "operation": "backup", - }, - { - "file": "part2.sldprt", - "status": "success", - "operation": "backup", - }, - { - "file": "assembly1.sldasm", - "status": "success", - "operation": "backup", - }, - ], - "processing_time": 2.5, - }, - execution_time=2.5, - ) - ) - - input_data = FileOperationInput( - file_path="./parts/", - operation="batch_backup", - parameters={ - "target_directory": "./backups/", - "include_subdirectories": True, - "file_pattern": "*.sld*", - }, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_file_operations": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_files"] == 3 - assert result["data"]["failed_files"] == 0 - mock_adapter.batch_file_operations.assert_called_once() - - @pytest.mark.asyncio - async def test_file_properties_error_handling( - self, mcp_server, mock_adapter, mock_config - ): - """Test error handling in file property management.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.manage_file_properties = AsyncMock( - return_value=Mock( - is_success=False, - error="File is read-only or locked", - execution_time=0.1, - ) - ) - - input_data = FileOperationInput( - file_path="locked_part.sldprt", - operation="set_properties", - parameters={"Author": "New User"}, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "manage_file_properties": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "read-only or locked" in result["message"] - - @pytest.mark.asyncio - async def test_format_conversion_error_handling( - self, mcp_server, mock_adapter, mock_config - ): - """Test error handling in format conversion.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.convert_file_format = AsyncMock( - return_value=Mock( - is_success=False, error="Unsupported target format", execution_time=0.1 - ) - ) - - input_data = FormatConversionInput( - source_file="test_part.sldprt", target_format="INVALID_FORMAT" - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "convert_file_format": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "Unsupported target format" in result["message"] - - @pytest.mark.asyncio - async def test_file_management_tools_refuse_without_adapter_methods( - self, mcp_server, mock_config - ): - """Tools refuse rather than inventing a result when the adapter has - no specialized methods.""" - adapter_without_methods = object() - await register_file_management_tools( - mcp_server, adapter_without_methods, mock_config - ) - - manage_tool = None - convert_tool = None - batch_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "manage_file_properties": - manage_tool = tool.fn - if tool.name == "convert_file_format": - convert_tool = tool.fn - if tool.name == "batch_file_operations": - batch_tool = tool.fn - - assert manage_tool is not None - assert convert_tool is not None - assert batch_tool is not None - - manage_result = await manage_tool( - input_data=FileOperationInput(file_path="demo.sldprt", operation="rename") - ) - assert manage_result["status"] == "error" - assert "does not support manage_file_properties" in manage_result["message"] - - convert_result = await convert_tool( - input_data=FormatConversionInput( - source_file="demo.sldprt", - target_file="demo.step", - target_format="STEP", - ) - ) - assert convert_result["status"] == "error" - assert "does not support convert_file_format" in convert_result["message"] - - batch_result = await batch_tool( - input_data=FileOperationInput(file_path="./parts", operation="batch") - ) - assert batch_result["status"] == "error" - assert "does not support batch_file_operations" in batch_result["message"] - @pytest.mark.asyncio async def test_list_open_documents_success( self, mcp_server, mock_adapter, mock_config @@ -755,122 +495,6 @@ async def test_save_as_exception_path(self, mcp_server, mock_adapter, mock_confi assert result["status"] == "error" assert result["error_type"] == "internal" - @pytest.mark.asyncio - async def test_batch_file_operations_adapter_error_path( - self, mcp_server, mock_adapter, mock_config - ): - """Cover batch_file_operations branch when adapter returns non-success.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_file_operations = AsyncMock( - return_value=Mock(is_success=False, error="batch rejected") - ) - - batch_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_file_operations": - batch_tool = tool.fn - break - - assert batch_tool is not None - result = await batch_tool( - input_data=FileOperationInput(file_path="./parts", operation="batch") - ) - assert result["status"] == "error" - assert "batch rejected" in result["message"] - - @pytest.mark.asyncio - async def test_manage_convert_batch_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Test exception branches for manage/convert/batch file operations.""" - await register_file_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.manage_file_properties = AsyncMock( - side_effect=RuntimeError("properties crash") - ) - mock_adapter.convert_file_format = AsyncMock( - side_effect=RuntimeError("conversion crash") - ) - mock_adapter.batch_file_operations = AsyncMock( - side_effect=RuntimeError("batch crash") - ) - - manage_tool = None - convert_tool = None - batch_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "manage_file_properties": - manage_tool = tool.fn - if tool.name == "convert_file_format": - convert_tool = tool.fn - if tool.name == "batch_file_operations": - batch_tool = tool.fn - - assert manage_tool is not None - assert convert_tool is not None - assert batch_tool is not None - - manage_result = await manage_tool( - input_data=FileOperationInput(file_path="x.sldprt", operation="rename") - ) - assert manage_result["status"] == "error" - assert manage_result["error_type"] == "internal" - - convert_result = await convert_tool( - input_data=FormatConversionInput( - source_file="x.sldprt", - target_file="x.step", - target_format="STEP", - ) - ) - assert convert_result["status"] == "error" - assert convert_result["error_type"] == "internal" - - batch_result = await batch_tool( - input_data=FileOperationInput(file_path="./parts", operation="batch") - ) - assert batch_result["status"] == "error" - assert batch_result["error_type"] == "internal" - - @pytest.mark.unit - def test_file_operation_input_validation(self): - """Test input validation for file operations.""" - # Valid input - valid_input = FileOperationInput( - file_path="test.sldprt", operation="get_properties" - ) - assert valid_input.file_path == "test.sldprt" - assert valid_input.operation == "get_properties" - - # Test with parameters - input_with_params = FileOperationInput( - file_path="test.sldprt", - operation="set_properties", - parameters={"Author": "Test User"}, - ) - assert input_with_params.parameters == {"Author": "Test User"} - - @pytest.mark.unit - def test_format_conversion_input_validation(self): - """Test input validation for format conversion.""" - # Valid input - valid_input = FormatConversionInput( - source_file="test.sldprt", target_format="STEP" - ) - assert valid_input.source_file == "test.sldprt" - assert valid_input.target_format == "STEP" - - # Test with optional parameters - full_input = FormatConversionInput( - source_file="test.sldprt", - target_format="IGES", - output_path="exports/test.igs", - conversion_options={"units": "mm", "precision": "high"}, - ) - assert full_input.output_path == "exports/test.igs" - assert full_input.conversion_options["units"] == "mm" - @pytest.mark.asyncio async def test_get_model_info_list_features_list_configurations_paths( self, mcp_server, mock_adapter, mock_config @@ -2369,3 +1993,206 @@ async def test_save_file_refuses_force_save( assert result["error_type"] == "invalid_input" assert "the tool always saves" in result["message"] mock_adapter.save_file.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_get_file_properties_reports_a_failed_model_read(mcp_server, mock_config): + """The adapter can't read the active document: the error says why.""" + adapter = Mock() + adapter.get_model_info = AsyncMock( + return_value=Mock(is_success=False, error="No active model", data=None) + ) + await register_file_management_tools(mcp_server, adapter, mock_config) + tool = next( + t.fn for t in await mcp_server.list_tools() if t.name == "get_file_properties" + ) + + result = await tool() + + assert result["status"] == "error" + assert "No active model" in result["message"] + + +def _info(doc_type: str | None, path: str = "") -> Mock: + """A successful get_model_info result for a document of ``doc_type``.""" + return Mock( + is_success=True, + data={"type": doc_type, "path": path, "title": "Doc"}, + error=None, + execution_time=0.0, + ) + + +async def _save_file_tool(mcp_server, mock_config, adapter: Mock) -> Any: + await register_file_management_tools(mcp_server, adapter, mock_config) + return next(t.fn for t in await mcp_server.list_tools() if t.name == "save_file") + + +def _save_adapter(doc_type: str | None = "Part") -> Mock: + adapter = Mock() + adapter.get_model_info = AsyncMock(return_value=_info(doc_type)) + adapter.save_file = AsyncMock( + return_value=Mock(is_success=True, data=None, error=None, execution_time=0.0) + ) + return adapter + + +@pytest.mark.asyncio +async def test_save_file_to_a_new_path(mcp_server, mock_config, tmp_path) -> None: + adapter = _save_adapter("Part") + save = await _save_file_tool(mcp_server, mock_config, adapter) + target = tmp_path / "bracket.sldprt" + + result = await save(input_data={"file_path": str(target)}) + + assert result["status"] == "success" + assert result["file_path"] == str(target) + adapter.save_file.assert_awaited_once_with(str(target)) + + +@pytest.mark.asyncio +async def test_save_file_refuses_a_missing_folder( + mcp_server, mock_config, tmp_path +) -> None: + adapter = _save_adapter("Part") + save = await _save_file_tool(mcp_server, mock_config, adapter) + folder = tmp_path / "no" / "such" + + result = await save(input_data={"file_path": str(folder / "bracket.sldprt")}) + + assert result["status"] == "error" + assert result["error_type"] == "invalid_input" + assert str(folder) in result["message"] + adapter.save_file.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_save_file_refuses_the_wrong_extension( + mcp_server, mock_config, tmp_path +) -> None: + adapter = _save_adapter("Assembly") + save = await _save_file_tool(mcp_server, mock_config, adapter) + + result = await save(input_data={"file_path": str(tmp_path / "frame.sldprt")}) + + assert result["status"] == "error" + assert result["error_type"] == "invalid_input" + assert ".sldasm" in result["message"] + adapter.save_file.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_save_file_keeps_an_existing_file_unless_overwrite( + mcp_server, mock_config, tmp_path +) -> None: + adapter = _save_adapter("Part") + save = await _save_file_tool(mcp_server, mock_config, adapter) + target = tmp_path / "bracket.sldprt" + target.write_text("old", encoding="utf-8") + + kept = await save(input_data={"file_path": str(target)}) + replaced = await save(input_data={"file_path": str(target), "overwrite": True}) + + assert kept["status"] == "error" + assert kept["error_type"] == "invalid_input" + assert "overwrite" in kept["message"] + assert replaced["status"] == "success" + adapter.save_file.assert_awaited_once_with(str(target)) + + +@pytest.mark.asyncio +async def test_save_file_in_place_skips_the_checks(mcp_server, mock_config) -> None: + adapter = _save_adapter(None) + save = await _save_file_tool(mcp_server, mock_config, adapter) + + result = await save(input_data={}) + + assert result["status"] == "success" + assert "file_path" not in result + adapter.get_model_info.assert_not_awaited() + adapter.save_file.assert_awaited_once_with(None) + + +@pytest.mark.asyncio +async def test_save_file_needs_the_document_type_for_a_new_path( + mcp_server, mock_config, tmp_path +) -> None: + adapter = _save_adapter("Unknown") + save = await _save_file_tool(mcp_server, mock_config, adapter) + + result = await save(input_data={"file_path": str(tmp_path / "x.sldprt")}) + + assert result["status"] == "error" + assert "active document's type" in result["message"] + adapter.save_file.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_save_file_reports_a_failed_type_read( + mcp_server, mock_config, tmp_path +) -> None: + adapter = _save_adapter("Part") + adapter.get_model_info = AsyncMock( + return_value=Mock(is_success=False, data=None, error="No active model") + ) + save = await _save_file_tool(mcp_server, mock_config, adapter) + + result = await save(input_data={"file_path": str(tmp_path / "x.sldprt")}) + + assert result["status"] == "error" + assert "No active model" in result["message"] + + +async def _model_info_tool(mcp_server, mock_config, adapter: Mock) -> Any: + await register_file_management_tools(mcp_server, adapter, mock_config) + return next( + t.fn for t in await mcp_server.list_tools() if t.name == "get_model_info" + ) + + +@pytest.mark.asyncio +async def test_get_model_info_reports_a_saved_file( + mcp_server, mock_config, tmp_path +) -> None: + saved = tmp_path / "bracket.sldprt" + saved.write_bytes(b"x" * 42) + adapter = Mock() + adapter.get_model_info = AsyncMock(return_value=_info("Part", str(saved))) + info_tool = await _model_info_tool(mcp_server, mock_config, adapter) + + info = (await info_tool())["model_info"] + + assert info["size_bytes"] == 42 + assert info["created"] > 0 + assert info["modified"] > 0 + assert info["type"] == "Part" + + +@pytest.mark.asyncio +async def test_get_model_info_on_an_unsaved_part(mcp_server, mock_config) -> None: + adapter = Mock() + adapter.get_model_info = AsyncMock(return_value=_info("Part", "")) + info_tool = await _model_info_tool(mcp_server, mock_config, adapter) + + result = await info_tool() + + assert result["status"] == "success" + assert result["model_info"]["size_bytes"] is None + assert result["model_info"]["created"] is None + assert result["model_info"]["modified"] is None + + +@pytest.mark.asyncio +async def test_get_model_info_on_the_mock_adapter_has_no_file( + mcp_server, mock_config +) -> None: + """A new mock part's ``Mock://`` path is no file, so the details are null.""" + adapter = MockSolidWorksAdapter({}) + await adapter.connect() + await adapter.create_part() + info_tool = await _model_info_tool(mcp_server, mock_config, adapter) + + info = (await info_tool())["model_info"] + + assert info["path"].startswith("Mock://") + assert info["size_bytes"] is None diff --git a/tests/solidworks_mcp/tools/test_macro_recording.py b/tests/solidworks_mcp/tools/test_macro_recording.py index e888395a..2a4c74fa 100644 --- a/tests/solidworks_mcp/tools/test_macro_recording.py +++ b/tests/solidworks_mcp/tools/test_macro_recording.py @@ -5,7 +5,6 @@ import pytest from fastmcp import FastMCP -from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus from solidworks_mcp.adapters.mock_adapter import MockSolidWorksAdapter from solidworks_mcp.config import ( AdapterType, @@ -14,10 +13,7 @@ SolidWorksMCPConfig, ) from solidworks_mcp.tools.macro_recording import ( - MacroAnalysisInput, - MacroBatchInput, MacroPlaybackInput, - MacroRecordingInput, register_macro_recording_tools, ) @@ -33,109 +29,7 @@ async def test_register_macro_recording_tools( tool_count = await register_macro_recording_tools( mcp_server, mock_adapter, mock_config ) - assert tool_count == 8 - - @pytest.mark.asyncio - async def test_start_macro_recording_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful macro recording start.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.start_macro_recording = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "recording_id": "REC_20240315_103000", - "recording_file": "user_actions.swp", - "recording_started": True, - "recording_mode": "User actions", - "start_time": "2024-03-15T10:30:00", - "capture_settings": { - "mouse_actions": True, - "keyboard_actions": True, - "feature_operations": True, - "sketch_operations": True, - }, - }, - execution_time=0.2, - ) - ) - - input_data = MacroRecordingInput( - recording_name="User Workflow Recording", - output_file="user_actions.swp", - recording_mode="User actions", - capture_mouse=True, - capture_keyboard=True, - auto_cleanup=True, - recording_quality="High", - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "start_macro_recording": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["recording_started"] is True - assert result["data"]["recording_file"] == "user_actions.swp" - assert result["data"]["recording_id"] == "REC_20240315_103000" - mock_adapter.start_macro_recording.assert_called_once() - - @pytest.mark.asyncio - async def test_stop_macro_recording_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful macro recording stop.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.stop_macro_recording = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "recording_id": "REC_20240315_103000", - "recording_stopped": True, - "final_file": "user_actions_completed.swp", - "recording_duration": 185.5, - "actions_captured": 42, - "file_size": "8.7 KB", - "summary": { - "sketch_operations": 15, - "feature_operations": 18, - "view_changes": 5, - "selection_operations": 4, - }, - }, - execution_time=0.5, - ) - ) - - input_data = { - "recording_id": "REC_20240315_103000", - "save_location": "./macros/", - "optimize_code": True, - "include_comments": True, - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "stop_macro_recording": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["recording_stopped"] is True - assert result["data"]["actions_captured"] == 42 - assert result["data"]["recording_duration"] == 185.5 - mock_adapter.stop_macro_recording.assert_called_once() + assert tool_count == 1 @pytest.mark.asyncio async def test_execute_macro_success(self, mcp_server, mock_adapter, mock_config): @@ -181,402 +75,6 @@ async def test_execute_macro_success(self, mcp_server, mock_adapter, mock_config assert result["message"] == "Macro completed 1 run" mock_adapter.execute_macro.assert_called_once() - @pytest.mark.asyncio - async def test_analyze_macro_success(self, mcp_server, mock_adapter, mock_config): - """Test successful macro analysis.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_macro = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "macro_file": "complex_workflow.swp", - "analysis_results": { - "complexity_score": 7.5, - "estimated_execution_time": 45.2, - "code_lines": 185, - "function_count": 8, - "loop_count": 3, - "conditional_count": 12, - }, - "optimization_suggestions": [ - { - "type": "REDUNDANT_OPERATIONS", - "description": "Remove duplicate selections", - "impact": "15% faster", - }, - { - "type": "LOOP_OPTIMIZATION", - "description": "Combine nested loops", - "impact": "Memory savings", - }, - { - "type": "ERROR_HANDLING", - "description": "Add error checking for file operations", - "impact": "Reliability", - }, - ], - "dependencies": ["SldWorks API", "File System"], - "risk_assessment": "Medium", - "maintainability_score": 6.8, - }, - execution_time=1.1, - ) - ) - - input_data = MacroAnalysisInput( - macro_file="complex_workflow.swp", - analysis_depth="Comprehensive", - include_performance_analysis=True, - include_security_analysis=True, - suggest_optimizations=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_macro": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["analysis_results"]["complexity_score"] == 7.5 - assert result["data"]["analysis_results"]["code_lines"] == 185 - assert len(result["data"]["optimization_suggestions"]) == 3 - assert result["data"]["risk_assessment"] == "Medium" - mock_adapter.analyze_macro.assert_called_once() - - @pytest.mark.asyncio - async def test_batch_execute_macros_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful batch macro execution.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_execute_macros = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "batch_id": "BATCH_20240315_114500", - "total_macros": 5, - "successful_executions": 4, - "failed_executions": 1, - "total_execution_time": 89.7, - "execution_results": [ - {"macro": "macro1.swp", "status": "success", "time": 15.2}, - {"macro": "macro2.swp", "status": "success", "time": 22.8}, - { - "macro": "macro3.swp", - "status": "failed", - "error": "File not found", - }, - {"macro": "macro4.swp", "status": "success", "time": 18.5}, - {"macro": "macro5.swp", "status": "success", "time": 33.2}, - ], - "log_file": "batch_execution_log.txt", - }, - execution_time=89.7, - ) - ) - - input_data = MacroBatchInput( - macro_list=[ - "macro1.swp", - "macro2.swp", - "macro3.swp", - "macro4.swp", - "macro5.swp", - ], - target_directory="./input_files/", - execution_mode="Sequential", - continue_on_error=True, - log_execution=True, - parallel_limit=2, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_execute_macros": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_macros"] == 5 - assert result["data"]["successful_executions"] == 4 - assert result["data"]["failed_executions"] == 1 - mock_adapter.batch_execute_macros.assert_called_once() - - @pytest.mark.asyncio - async def test_optimize_macro_success(self, mcp_server, mock_adapter, mock_config): - """Test successful macro optimization.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.optimize_macro = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "original_macro": "unoptimized_workflow.swp", - "optimized_macro": "optimized_workflow.swp", - "optimization_results": { - "original_lines": 245, - "optimized_lines": 180, - "lines_removed": 65, - "performance_improvement": "28%", - "estimated_time_savings": 8.5, - }, - "optimizations_applied": [ - "Removed redundant selections", - "Consolidated similar operations", - "Optimized loop structures", - "Added error handling", - "Improved variable declarations", - ], - "warnings": [ - "Some manual review recommended for complex operations" - ], - }, - execution_time=2.1, - ) - ) - - input_data = { - "macro_file": "unoptimized_workflow.swp", - "optimization_level": "Aggressive", - "preserve_functionality": True, - "add_error_handling": True, - "optimize_loops": True, - "remove_redundant_code": True, - "output_file": "optimized_workflow.swp", - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "optimize_macro": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert ( - result["data"]["optimization_results"]["performance_improvement"] == "28%" - ) - assert result["data"]["optimization_results"]["lines_removed"] == 65 - assert "Removed redundant selections" in result["data"]["optimizations_applied"] - mock_adapter.optimize_macro.assert_called_once() - - @pytest.mark.asyncio - async def test_create_macro_library_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful macro library creation.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.create_macro_library = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "library_name": "Engineering Workflows", - "library_path": "C:\\MacroLibrary\\", - "categories_created": ["Modeling", "Drawing", "Analysis", "Export"], - "templates_included": 15, - "documentation_generated": True, - "index_file": "library_index.html", - "total_macros": 0, # Initial empty library - "library_structure": { - "root": "C:\\MacroLibrary\\", - "categories": ["Modeling", "Drawing", "Analysis", "Export"], - "documentation": "docs/", - "templates": "templates/", - }, - }, - execution_time=1.8, - ) - ) - - input_data = { - "library_name": "Engineering Workflows", - "library_path": "C:\\MacroLibrary\\", - "categories": ["Modeling", "Drawing", "Analysis", "Export"], - "include_templates": True, - "generate_documentation": True, - "version_control": True, - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "create_macro_library": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["library_name"] == "Engineering Workflows" - assert len(result["data"]["categories_created"]) == 4 - assert result["data"]["documentation_generated"] is True - mock_adapter.create_macro_library.assert_called_once() - - @pytest.mark.asyncio - async def test_macro_recording_error_handling( - self, mcp_server, mock_adapter, mock_config - ): - """Test error handling in macro recording.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.start_macro_recording = AsyncMock( - return_value=Mock( - is_success=False, - error="Recording already in progress", - execution_time=0.1, - ) - ) - - input_data = MacroRecordingInput( - recording_name="Test Recording", output_file="test.swp" - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "start_macro_recording": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "Recording already in progress" in result["message"] - - @pytest.mark.asyncio - async def test_start_macro_recording_exception_path( - self, mcp_server, mock_adapter, mock_config - ): - """Test start_macro_recording exception handling branch.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.start_macro_recording = AsyncMock( - side_effect=RuntimeError("recorder unavailable") - ) - - start_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "start_macro_recording": - start_tool = tool.fn - break - - assert start_tool is not None - result = await start_tool( - input_data=MacroRecordingInput( - recording_name="Explode", output_file="explode.swp" - ) - ) - - assert result["status"] == "error" - assert result["error_type"] == "internal" - - @pytest.mark.asyncio - async def test_stop_macro_recording_fallback_path(self, mcp_server, mock_config): - """stop_macro_recording refuses (no recording was ever started) when - the adapter has no stop_macro_recording capability.""" - await register_macro_recording_tools(mcp_server, object(), mock_config) - - stop_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "stop_macro_recording": - stop_tool = tool.fn - break - - assert stop_tool is not None - result = await stop_tool( - input_data={ - "session_id": "REC-12345", - "save_path": "C:\\Macros\\REC-12345.swp", - "clean_code": False, - } - ) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_stop_macro_recording_exception_path( - self, mcp_server, mock_adapter, mock_config - ): - """Test stop_macro_recording exception handling path.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.stop_macro_recording = AsyncMock( - side_effect=RuntimeError("stop failed") - ) - - stop_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "stop_macro_recording": - stop_tool = tool.fn - break - - exception_result = await stop_tool(input_data={"session_id": "REC-2"}) - assert exception_result["status"] == "error" - assert exception_result["error_type"] == "internal" - - @pytest.mark.asyncio - async def test_macro_tools_fallback_without_adapter_methods( - self, mcp_server, mock_config - ): - """Tools refuse rather than inventing a result when the adapter has - no matching capability.""" - adapter_without_methods = object() - await register_macro_recording_tools( - mcp_server, adapter_without_methods, mock_config - ) - - start_tool = None - execute_tool = None - batch_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "start_macro_recording": - start_tool = tool.fn - if tool.name == "execute_macro": - execute_tool = tool.fn - if tool.name == "batch_execute_macros": - batch_tool = tool.fn - - assert start_tool is not None - assert execute_tool is not None - assert batch_tool is not None - - start_result = await start_tool( - input_data=MacroRecordingInput( - recording_name="Fallback recording", - output_file="fallback.swp", - ) - ) - assert start_result["status"] == "error" - assert "does not support start_macro_recording" in start_result["message"] - - execute_result = await execute_tool( - input_data=MacroPlaybackInput( - macro_file="fallback.swp", - repeat_count=2, - pause_between_runs=0, - ) - ) - assert execute_result["status"] == "error" - assert "does not support execute_macro" in execute_result["message"] - - batch_result = await batch_tool( - input_data=MacroBatchInput( - macro_list=["a.swp", "b.swp", "c.swp"], - stop_on_error=True, - ) - ) - assert batch_result["status"] == "error" - assert "does not support batch_execute_macros" in batch_result["message"] - @pytest.mark.asyncio async def test_execute_macro_exception_path( self, mcp_server, mock_adapter, mock_config @@ -655,211 +153,6 @@ async def test_execute_macro_fallback_refuses_without_running_anything( assert result["status"] == "error" assert "does not support execute_macro" in result["message"] - @pytest.mark.asyncio - async def test_analyze_macro_fallback_path(self, mcp_server, mock_config): - """analyze_macro refuses rather than inventing code metrics when the - adapter has no analyze_macro capability.""" - await register_macro_recording_tools(mcp_server, object(), mock_config) - - analyze_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_macro": - analyze_tool = tool.fn - break - - assert analyze_tool is not None - result = await analyze_tool( - input_data=MacroAnalysisInput( - macro_file="analysis.swp", analysis_depth="Full" - ) - ) - assert result["status"] == "error" - assert "does not support analyze_macro" in result["message"] - - @pytest.mark.asyncio - async def test_analyze_macro_adapter_error_path( - self, mcp_server, mock_adapter, mock_config - ): - """Test analyze_macro adapter error branch.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.analyze_macro = AsyncMock( - return_value=Mock(is_success=False, error="parse failure") - ) - analyze_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "analyze_macro": - analyze_tool = tool.fn - break - - error_result = await analyze_tool( - input_data=MacroAnalysisInput(macro_file="analysis.swp") - ) - assert error_result["status"] == "error" - assert "parse failure" in error_result["message"] - - @pytest.mark.asyncio - async def test_batch_execute_macros_error_and_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Test batch_execute_macros adapter error and exception branches.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.batch_execute_macros = AsyncMock( - return_value=Mock(is_success=False, error="batch failed") - ) - - batch_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_execute_macros": - batch_tool = tool.fn - break - - assert batch_tool is not None - error_result = await batch_tool( - input_data=MacroBatchInput(macro_list=["m1.swp"], stop_on_error=True) - ) - assert error_result["status"] == "error" - assert "batch failed" in error_result["message"] - - mock_adapter.batch_execute_macros = AsyncMock( - side_effect=RuntimeError("executor down") - ) - exception_result = await batch_tool( - input_data=MacroBatchInput(macro_list=["m1.swp"], stop_on_error=True) - ) - assert exception_result["status"] == "error" - assert exception_result["error_type"] == "internal" - - @pytest.mark.asyncio - async def test_optimize_and_library_fallback_paths(self, mcp_server, mock_config): - """optimize_macro and create_macro_library refuse rather than - inventing an optimization report or a library layout when the - adapter has no matching capability.""" - await register_macro_recording_tools(mcp_server, object(), mock_config) - - optimize_tool = None - library_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "optimize_macro": - optimize_tool = tool.fn - if tool.name == "create_macro_library": - library_tool = tool.fn - - assert optimize_tool is not None - assert library_tool is not None - - optimize_result = await optimize_tool( - input_data={"macro_file": "legacy.swp", "level": "aggressive"} - ) - assert optimize_result["status"] == "error" - assert "does not support optimize_macro" in optimize_result["message"] - - library_result = await library_tool( - input_data={ - "library_name": "Team Library", - "library_path": "C:\\Macros\\Team", - "categories": ["Modeling"], - "include_templates": False, - } - ) - assert library_result["status"] == "error" - assert "does not support create_macro_library" in library_result["message"] - - @pytest.mark.asyncio - async def test_optimize_and_library_adapter_error_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Test optimize_macro and create_macro_library adapter error paths.""" - await register_macro_recording_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.optimize_macro = AsyncMock( - return_value=Mock(is_success=False, error="optimizer failed") - ) - mock_adapter.create_macro_library = AsyncMock( - return_value=Mock(is_success=False, error="library create failed") - ) - - optimize_tool = None - library_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "optimize_macro": - optimize_tool = tool.fn - if tool.name == "create_macro_library": - library_tool = tool.fn - - assert optimize_tool is not None - assert library_tool is not None - - optimize_error = await optimize_tool(input_data={"macro_file": "m.swp"}) - assert optimize_error["status"] == "error" - assert "optimizer failed" in optimize_error["message"] - - library_error = await library_tool(input_data={"library_name": "Bad"}) - assert library_error["status"] == "error" - assert "library create failed" in library_error["message"] - - @pytest.mark.unit - def test_macro_recording_input_validation(self): - """Test input validation for macro recording.""" - # Valid input - valid_input = MacroRecordingInput( - recording_name="Test Recording", output_file="test.swp" - ) - assert valid_input.recording_name == "Test Recording" - assert valid_input.output_file == "test.swp" - - # Test with optional parameters - full_input = MacroRecordingInput( - recording_name="Full Recording", - output_file="full_test.swp", - recording_mode="User actions", - capture_mouse=True, - capture_keyboard=False, - ) - assert full_input.recording_mode == "User actions" - assert full_input.capture_mouse is True - assert full_input.capture_keyboard is False - - @pytest.mark.unit - def test_macro_analysis_input_validation(self): - """Test input validation for macro analysis.""" - # Valid input - valid_input = MacroAnalysisInput(macro_file="test.swp", analysis_depth="Basic") - assert valid_input.macro_file == "test.swp" - assert valid_input.analysis_depth == "Basic" - - # Test with optional parameters - full_input = MacroAnalysisInput( - macro_file="complex.swp", - analysis_depth="Comprehensive", - include_performance_analysis=True, - suggest_optimizations=False, - ) - assert full_input.include_performance_analysis is True - assert full_input.suggest_optimizations is False - - @pytest.mark.unit - def test_macro_batch_input_validation(self): - """Test input validation for batch macro operations.""" - # Valid input - valid_input = MacroBatchInput( - macro_list=["macro1.swp", "macro2.swp"], target_directory="./files/" - ) - assert len(valid_input.macro_list) == 2 - assert valid_input.target_directory == "./files/" - - # Test with optional parameters - full_input = MacroBatchInput( - macro_list=["macro1.swp", "macro2.swp", "macro3.swp"], - target_directory="./files/", - execution_mode="Parallel", - continue_on_error=False, - parallel_limit=3, - ) - assert full_input.execution_mode == "Parallel" - assert full_input.continue_on_error is False - assert full_input.parallel_limit == 3 - def _make_mcp(): """Create a plain FastMCP instance.""" @@ -890,26 +183,6 @@ async def _get_tool(mcp, name: str): class TestMacroRecordingExceptionPaths: """Test macro recording exception paths.""" - @pytest.mark.asyncio - async def test_stop_macro_recording_adapter_error(self): - """Line 243 — adapter returns error on stop_macro_recording.""" - from solidworks_mcp.tools.macro_recording import ( - register_macro_recording_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.stop_macro_recording = AsyncMock( - return_value=AdapterResult( - status=AdapterResultStatus.ERROR, error="stop err" - ) - ) - await register_macro_recording_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "stop_macro_recording") - result = await fn({"session_id": "abc", "save_path": "/tmp/m.swp"}) - assert result["status"] == "error" - @pytest.mark.asyncio async def test_execute_macro_exception(self): """Line 358 — exception in execute_macro.""" @@ -927,39 +200,6 @@ async def test_execute_macro_exception(self): result = await fn(MacroPlaybackInput(macro_path="/tmp/m.swp")) assert result["status"] == "error" - @pytest.mark.asyncio - async def test_optimize_macro_exception(self): - """Lines 757-759 — exception in optimize_macro.""" - from solidworks_mcp.tools.macro_recording import ( - MacroAnalysisInput, - register_macro_recording_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.optimize_macro = AsyncMock(side_effect=RuntimeError("opt boom")) - await register_macro_recording_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "optimize_macro") - result = await fn(MacroAnalysisInput(macro_path="/tmp/m.swp")) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_create_macro_library_exception(self): - """Lines 914-916 — exception in create_macro_library.""" - from solidworks_mcp.tools.macro_recording import ( - register_macro_recording_tools, - ) - - mcp = _make_mcp() - adapter = MockSolidWorksAdapter({}) - adapter.create_macro_library = AsyncMock(side_effect=RuntimeError("lib boom")) - await register_macro_recording_tools(mcp, adapter, _make_config()) - - fn = await _get_tool(mcp, "create_macro_library") - result = await fn({"library_path": "/tmp/lib", "library_name": "TestLib"}) - assert result["status"] == "error" - @pytest.mark.parametrize("field", ["macro_path", "macro_file"]) @pytest.mark.parametrize( diff --git a/tests/solidworks_mcp/tools/test_sketching.py b/tests/solidworks_mcp/tools/test_sketching.py index 8c3ff16a..949efe18 100644 --- a/tests/solidworks_mcp/tools/test_sketching.py +++ b/tests/solidworks_mcp/tools/test_sketching.py @@ -23,10 +23,8 @@ AddRelationInput, AddSplineInput, CreateSketchInput, - TutorialSimpleHoleInput, register_sketching_tools, ) -from solidworks_mcp.tools.sketching import AddDimensionInput as SketchAddDimensionInput class TestSketchingTools: @@ -237,60 +235,6 @@ async def test_exit_sketch_mode(self, mcp_server, mock_adapter, mock_config): assert result["status"] == "success" assert "Exited sketch editing mode" in result["message"] - @pytest.mark.asyncio - async def test_tutorial_simple_hole(self, mcp_server, mock_adapter, mock_config): - """Test the complete tutorial for creating a simple hole.""" - await register_sketching_tools(mcp_server, mock_adapter, mock_config) - - # Mock all the operations in sequence - mock_adapter.create_sketch = AsyncMock( - return_value=Mock( - is_success=True, data={"sketch_name": "HoleSketch"}, execution_time=0.3 - ) - ) - mock_adapter.add_sketch_circle = AsyncMock( - return_value=Mock( - is_success=True, data={"entity_id": "HoleCircle"}, execution_time=0.2 - ) - ) - mock_adapter.exit_sketch = AsyncMock( - return_value=Mock( - is_success=True, data={"sketch_name": "HoleSketch"}, execution_time=0.1 - ) - ) - mock_adapter.create_cut = AsyncMock( - return_value=Mock( - is_success=True, data={"cut_name": "Cut-Extrude1"}, execution_time=0.8 - ) - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "tutorial_simple_hole": - tool_func = tool.fn - break - - input_data = TutorialSimpleHoleInput( - plane="Front Plane", center_x=0.0, center_y=0.0, diameter=8.0, depth=15.0 - ) - result = await tool_func(input_data) - - assert result["status"] == "success" - assert result["tutorial"]["plane"] == "Front Plane" - assert result["tutorial"]["diameter"] == 8.0 - assert result["tutorial"]["depth"] == 15.0 - assert len(result["tutorial"]["steps"]) == 4 - - # Check that all steps were completed - step_names = [step["step"] for step in result["tutorial"]["steps"]] - expected_steps = [ - "Create sketch", - "Add circle", - "Exit sketch", - "Create cut extrude", - ] - assert step_names == expected_steps - @pytest.mark.asyncio async def test_sketch_failure_handling(self, mcp_server, mock_adapter, mock_config): """Test error handling when sketch operations fail.""" @@ -397,17 +341,6 @@ def test_add_rectangle_input_alias_resolution(self): ) assert inp.x1 == 0.0 and inp.y1 == 0.0 and inp.x2 == 5.0 and inp.y2 == 6.0 - def test_tutorial_hole_input_validation_errors(self): - """Test tutorial hole input validation errors.""" - with pytest.raises(ValueError): - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=0, depth=5 - ) - with pytest.raises(ValueError): - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=5, depth=0 - ) - # ── Fallback adapter paths ──────────────────────────────────────────── @pytest.mark.asyncio @@ -661,29 +594,6 @@ async def test_check_sketch_fully_defined_success_empty_payload_and_exception( assert failure["status"] == "error" assert failure["error_type"] == "internal" - @pytest.mark.asyncio - async def test_tutorial_simple_hole_create_sketch_failure( - self, mcp_server, mock_config - ): - """tutorial_simple_hole should fail early when sketch creation fails.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock( - return_value=Mock(is_success=False, error="sketch failed") - ) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=8, depth=10 - ) - ) - assert result["status"] == "error" - assert "sketch failed" in result["message"] - @pytest.mark.asyncio async def test_sketch_tutorial_hole_add_circle_failure( self, mcp_server, mock_config @@ -743,139 +653,6 @@ async def test_sketch_tutorial_hole_exception(self, mcp_server, mock_config): result = await tool_func() assert result["status"] == "error" - # ── tutorial_simple_hole failure paths ──────────────────────────────── - - @pytest.mark.asyncio - async def test_tutorial_hole_circle_failure(self, mcp_server, mock_config): - """Test tutorial hole circle failure.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock( - return_value=Mock(is_success=True, data="S1", execution_time=0.1) - ) - stub.add_sketch_circle = AsyncMock( - return_value=Mock(is_success=False, error="circle failed") - ) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=8, depth=10 - ) - ) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_tutorial_hole_exit_failure(self, mcp_server, mock_config): - """Test tutorial hole exit failure.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock( - return_value=Mock(is_success=True, data="S1", execution_time=0.1) - ) - stub.add_sketch_circle = AsyncMock( - return_value=Mock(is_success=True, data="C1", execution_time=0.1) - ) - stub.exit_sketch = AsyncMock( - return_value=Mock(is_success=False, error="exit failed") - ) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=8, depth=10 - ) - ) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_tutorial_hole_cut_failure(self, mcp_server, mock_config): - """Test tutorial hole cut failure.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock( - return_value=Mock(is_success=True, data="S1", execution_time=0.1) - ) - stub.add_sketch_circle = AsyncMock( - return_value=Mock(is_success=True, data="C1", execution_time=0.1) - ) - stub.exit_sketch = AsyncMock( - return_value=Mock(is_success=True, data=None, execution_time=0.1) - ) - stub.create_cut = AsyncMock( - return_value=Mock(is_success=False, error="cut failed") - ) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=8, depth=10 - ) - ) - assert result["status"] == "error" - - @pytest.mark.asyncio - async def test_tutorial_hole_depth_none_uses_diameter( - self, mcp_server, mock_config - ): - """When depth is None, cut_depth equals diameter.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock( - return_value=Mock(is_success=True, data="S1", execution_time=0.1) - ) - stub.add_sketch_circle = AsyncMock( - return_value=Mock(is_success=True, data="C1", execution_time=0.1) - ) - stub.exit_sketch = AsyncMock( - return_value=Mock(is_success=True, data=None, execution_time=0.1) - ) - stub.create_cut = AsyncMock( - return_value=Mock( - is_success=True, data={"cut_name": "Cut1"}, execution_time=0.5 - ) - ) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=8, depth=None - ) - ) - assert result["status"] == "success" - assert result["tutorial"]["depth"] is None - stub.create_cut.assert_called_once_with("HoleSketch", 8.0) - - @pytest.mark.asyncio - async def test_tutorial_hole_exception_path(self, mcp_server, mock_config): - """Test tutorial hole exception path.""" - stub = SimpleNamespace() - stub.create_sketch = AsyncMock(side_effect=RuntimeError("boom")) - await register_sketching_tools(mcp_server, stub, mock_config) - tool_func = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "tutorial_simple_hole" - ) - result = await tool_func( - TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=5, depth=10 - ) - ) - assert result["status"] == "error" - def _ok(data): """Test helper for ok.""" @@ -1049,7 +826,7 @@ async def test_sketching_tools_uncovered_paths(mcp_server, mock_config): )["status"] == "success" assert ( await (await _tool(mcp_server, "add_sketch_dimension"))( - input_data=SketchAddDimensionInput( + input_data=AddDimensionInput( entity1="L1", dimension_type="linear", value=10 ) ) @@ -1077,13 +854,6 @@ async def test_sketching_tools_uncovered_paths(mcp_server, mock_config): assert (await (await _tool(mcp_server, "sketch_tutorial_simple_hole"))())[ "status" ] == "success" - assert ( - await (await _tool(mcp_server, "tutorial_simple_hole"))( - input_data=TutorialSimpleHoleInput( - plane="Top", center_x=0, center_y=0, diameter=5, depth=3 - ) - ) - )["status"] == "success" @pytest.mark.asyncio diff --git a/tests/solidworks_mcp/tools/test_support_levels.py b/tests/solidworks_mcp/tools/test_support_levels.py index 3de2e37e..36b625a9 100644 --- a/tests/solidworks_mcp/tools/test_support_levels.py +++ b/tests/solidworks_mcp/tools/test_support_levels.py @@ -8,6 +8,8 @@ SUPPORT_LEVELS, Support, SupportLevel, + deprecation_problems, + planned_problems, ) @@ -44,3 +46,86 @@ def test_every_reason_is_one_sentence() -> None: if support.reason: assert support.reason.endswith("."), name assert "\n" not in support.reason, name + + +def test_a_deprecated_tool_warns_with_its_replacement() -> None: + support = Support(SupportLevel.DEPRECATED, "use `open_model`.", since="2.1.0") + + assert support.warning() == "Deprecated: use `open_model`." + assert support.replacement() == "open_model" + + +def test_a_deprecated_tool_without_a_replacement() -> None: + support = Support(SupportLevel.DEPRECATED, "no replacement.", since="2.1.0") + + assert support.warning() == "Deprecated: no replacement." + assert support.replacement() is None + + +def test_only_a_deprecated_tool_has_a_since() -> None: + with pytest.raises(ValueError, match="needs `since`"): + Support(SupportLevel.DEPRECATED, "no replacement.") + with pytest.raises(ValueError, match="needs `since`"): + Support(SupportLevel.BETA, "one input is ignored.", since="2.1.0") + + +def test_other_levels_name_no_replacement() -> None: + assert Support(SupportLevel.BETA, "use `open_model`.").replacement() is None + + +def _deprecated(reason: str) -> Support: + return Support(SupportLevel.DEPRECATED, reason, since="2.1.0") + + +def test_deprecation_problems_pass_a_good_table() -> None: + levels = { + "load_part": _deprecated("use `open_model`."), + "old_example": _deprecated("no replacement."), + "open_model": Support(SupportLevel.STABLE), + } + + assert deprecation_problems(levels, set(levels), "2.1.0") == [] + + +def test_deprecation_problems_need_a_registered_replacement() -> None: + levels = {"load_part": _deprecated("use `load_anything`.")} + + assert deprecation_problems(levels, {"load_part"}, "2.1.0") == [ + "load_part: its replacement 'load_anything' is not a tool" + ] + + +def test_deprecation_problems_need_a_known_reason_form() -> None: + levels = {"load_part": _deprecated("superseded.")} + + assert deprecation_problems(levels, {"load_part"}, "2.1.0") == [ + "load_part: the reason must be 'use ``.' or 'no replacement.'" + ] + + +def test_deprecation_problems_fail_at_the_next_major_release() -> None: + levels = { + "load_part": _deprecated("use `open_model`."), + "open_model": Support(SupportLevel.STABLE), + } + + assert deprecation_problems(levels, set(levels), "2.9.0") == [] + assert deprecation_problems(levels, set(levels), "3.0.0") == [ + "load_part: deprecated in 2.1.0, so remove it before 3.0.0" + ] + # Once it is no longer registered, the entry no longer fails. + assert deprecation_problems(levels, {"open_model"}, "3.0.0") == [] + + +def test_planned_problems_need_a_queue_item() -> None: + levels = { + "add_dimension": Support( + SupportLevel.PLANNED, "planned in queue item 12 (the drawing pack)." + ), + "orphan": Support(SupportLevel.PLANNED, "no adapter implements it yet."), + "open_model": Support(SupportLevel.STABLE), + } + + assert planned_problems(levels) == [ + "orphan: a planned tool's reason names its queue item" + ] diff --git a/tests/solidworks_mcp/tools/test_template_management.py b/tests/solidworks_mcp/tools/test_template_management.py index b38e1cd1..d5b5e0d4 100644 --- a/tests/solidworks_mcp/tools/test_template_management.py +++ b/tests/solidworks_mcp/tools/test_template_management.py @@ -1,14 +1,9 @@ """Tests for SolidWorks template management tools.""" -from unittest.mock import AsyncMock, Mock - import pytest from solidworks_mcp.tools.template_management import ( - TemplateApplicationInput, - TemplateBatchInput, TemplateComparisonInput, - TemplateExtractionInput, register_template_management_tools, ) @@ -24,172 +19,7 @@ async def test_register_template_management_tools( tool_count = await register_template_management_tools( mcp_server, mock_adapter, mock_config ) - assert tool_count == 6 - - @pytest.mark.asyncio - async def test_extract_template_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful template extraction from model.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.extract_template = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "template_file": "extracted_template.prtdot", - "template_type": "Part", - "source_model": "reference_part.sldprt", - "extracted_elements": [ - "Custom properties", - "Material assignment", - "Dimension styles", - "Feature tree structure", - ], - "properties_count": 12, - "template_size": "250 KB", - }, - execution_time=1.8, - ) - ) - - input_data = TemplateExtractionInput( - source_model="reference_part.sldprt", - template_name="Engineering Part Template", - template_type="part", - save_path="templates/extracted_template.prtdot", - include_custom_properties=True, - include_dimensions=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "extract_template": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["template_file"] == "extracted_template.prtdot" - assert result["data"]["properties_count"] == 12 - assert "Custom properties" in result["data"]["extracted_elements"] - mock_adapter.extract_template.assert_called_once() - - @pytest.mark.asyncio - async def test_apply_template_success(self, mcp_server, mock_adapter, mock_config): - """Test successful template application to model.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.apply_template = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "target_model": "new_part.sldprt", - "template_applied": "engineering_template.prtdot", - "applied_elements": [ - "Custom properties", - "Material assignment", - "Dimension formatting", - "Units system", - ], - "properties_applied": 8, - "overwritten_properties": 2, - "application_time": 1.2, - }, - execution_time=1.2, - ) - ) - - input_data = TemplateApplicationInput( - template_path="templates/engineering_template.prtdot", - target_model="new_part.sldprt", - overwrite_existing=True, - apply_dimensions=True, - apply_materials=True, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "apply_template": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["template_applied"] == "engineering_template.prtdot" - assert result["data"]["properties_applied"] == 8 - assert "Material assignment" in result["data"]["applied_elements"] - mock_adapter.apply_template.assert_called_once() - - @pytest.mark.asyncio - async def test_batch_apply_template_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful batch template application.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.batch_apply_template = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "template_used": "standard_template.prtdot", - "total_files": 15, - "processed_files": 14, - "failed_files": 1, - "processing_time": 18.5, - "results": [ - { - "file": "part1.sldprt", - "status": "success", - "properties_applied": 6, - }, - { - "file": "part2.sldprt", - "status": "success", - "properties_applied": 6, - }, - { - "file": "part3.sldprt", - "status": "failed", - "error": "File locked", - }, - # ... more results - ], - "average_properties_per_file": 6.2, - }, - execution_time=18.5, - ) - ) - - input_data = TemplateBatchInput( - template_path="templates/standard_template.prtdot", - source_folder="./parts/", - output_folder="./parts_updated/", - file_pattern="*.sldprt", - include_subdirectories=True, - overwrite_existing=True, - create_backup=True, - parallel_processing=False, - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "batch_apply_template": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_files"] == 15 - assert result["data"]["processed_files"] == 14 - assert result["data"]["failed_files"] == 1 - mock_adapter.batch_apply_template.assert_called_once() + assert tool_count == 1 @pytest.mark.asyncio async def test_compare_templates_success( @@ -244,259 +74,6 @@ async def test_compare_templates_refuses_its_old_switches( assert result["error_type"] == "invalid_input" assert "compares the two files on disk" in result["message"] - @pytest.mark.asyncio - async def test_save_to_template_library_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful template library save.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.save_to_template_library = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "library_name": "Engineering Templates", - "template_name": "Standard Part Template v2.1", - "library_path": "C:\\Templates\\Library\\", - "template_id": "TPL_001_v21", - "category": "Mechanical Parts", - "tags": ["Standard", "Engineering", "ISO"], - "version": "2.1", - "created_date": "2024-03-15", - "file_size": "180 KB", - }, - execution_time=0.6, - ) - ) - - input_data = { - "template_file": "new_template.prtdot", - "library_name": "Engineering Templates", - "template_name": "Standard Part Template v2.1", - "template_description": "Standard engineering part template with updated properties", - "category": "Mechanical Parts", - "tags": ["Standard", "Engineering", "ISO"], - "version": "2.1", - "author": "Engineering Team", - "replace_existing": False, - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "save_to_template_library": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["template_name"] == "Standard Part Template v2.1" - assert result["data"]["template_id"] == "TPL_001_v21" - assert "Engineering" in result["data"]["tags"] - mock_adapter.save_to_template_library.assert_called_once() - - @pytest.mark.asyncio - async def test_list_template_library_success( - self, mcp_server, mock_adapter, mock_config - ): - """Test successful template library listing.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.list_template_library = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "library_name": "Engineering Templates", - "total_templates": 25, - "categories": [ - "Mechanical Parts", - "Electrical", - "Structural", - "Assemblies", - ], - "templates": [ - { - "id": "TPL_001", - "name": "Standard Part Template", - "category": "Mechanical Parts", - "version": "2.1", - "created": "2024-01-15", - "tags": ["Standard", "Engineering"], - }, - { - "id": "TPL_002", - "name": "Assembly Template", - "category": "Assemblies", - "version": "1.8", - "created": "2024-02-10", - "tags": ["Assembly", "Standard"], - }, - # ... more templates - ], - "library_size": "12.5 MB", - "last_updated": "2024-03-15", - }, - execution_time=0.4, - ) - ) - - input_data = { - "library_path": "C:\\Templates\\Library\\", - "filter_category": "", - "filter_tags": [], - "sort_by": "created_date", - "sort_order": "desc", - "include_details": True, - } - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "list_template_library": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - - assert result["status"] == "success" - assert result["data"]["total_templates"] == 25 - assert len(result["data"]["categories"]) == 4 - assert "Mechanical Parts" in result["data"]["categories"] - assert len(result["data"]["templates"]) >= 2 - mock_adapter.list_template_library.assert_called_once() - - @pytest.mark.asyncio - async def test_template_extraction_error_handling( - self, mcp_server, mock_adapter, mock_config - ): - """Test error handling in template extraction.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.extract_template = AsyncMock( - return_value=Mock( - is_success=False, - error="Source model file not found", - execution_time=0.1, - ) - ) - - input_data = TemplateExtractionInput( - source_model="missing_file.sldprt", - template_name="Test Template", - template_type="part", - save_path="templates/test.prtdot", - ) - - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "extract_template": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) - assert result["status"] == "error" - assert "Source model file not found" in result["message"] - - @pytest.mark.asyncio - async def test_template_management_fallback_paths_refuse( - self, mcp_server, mock_config - ): - """Template management tools refuse rather than inventing a result - when the adapter has no matching capability. compare_templates is - the one exception below with real files on disk: it reports honest - filesystem facts instead.""" - await register_template_management_tools(mcp_server, object(), mock_config) - - extract_tool = None - apply_tool = None - batch_tool = None - compare_tool = None - save_tool = None - list_tool = None - - for tool in await mcp_server.list_tools(): - if tool.name == "extract_template": - extract_tool = tool.fn - if tool.name == "apply_template": - apply_tool = tool.fn - if tool.name == "batch_apply_template": - batch_tool = tool.fn - if tool.name == "compare_templates": - compare_tool = tool.fn - if tool.name == "save_to_template_library": - save_tool = tool.fn - if tool.name == "list_template_library": - list_tool = tool.fn - - assert extract_tool is not None - assert apply_tool is not None - assert batch_tool is not None - assert compare_tool is not None - assert save_tool is not None - assert list_tool is not None - - extract_result = await extract_tool( - input_data=TemplateExtractionInput( - source_model="part.sldprt", - template_name="Fallback Template", - template_type="part", - save_path="templates/fallback.prtdot", - ) - ) - assert extract_result["status"] == "error" - assert "does not support extract_template" in extract_result["message"] - - apply_result = await apply_tool( - input_data=TemplateApplicationInput( - template_path="templates/fallback.prtdot", - target_model="target.sldprt", - overwrite_existing=True, - ) - ) - assert apply_result["status"] == "error" - assert "does not support apply_template" in apply_result["message"] - - batch_result = await batch_tool( - input_data=TemplateBatchInput( - template_path="templates/fallback.prtdot", - source_folder="./parts", - file_pattern="*.sldprt", - recursive=False, - backup_originals=False, - ) - ) - assert batch_result["status"] == "error" - assert "does not support batch_apply_template" in batch_result["message"] - - # compare_templates falls back to a real filesystem comparison, not a - # fabricated similarity score — nonexistent paths refuse cleanly. - compare_result = await compare_tool( - input_data=TemplateComparisonInput( - template1_path="templates/a.prtdot", - template2_path="templates/b.prtdot", - ) - ) - assert compare_result["status"] == "error" - assert "not found on disk" in compare_result["message"] - - save_result = await save_tool( - input_data={ - "template_name": "Library Fallback", - "template_path": "templates/fallback.prtdot", - "category": "parts", - "author": "QA", - } - ) - assert save_result["status"] == "error" - assert "does not support save_to_template_library" in save_result["message"] - - list_result = await list_tool( - input_data={"category": "all", "search_term": "", "sort_by": "name"} - ) - assert list_result["status"] == "error" - assert "does not support list_template_library" in list_result["message"] - @pytest.mark.asyncio async def test_compare_templates_reads_real_files( self, mcp_server, mock_config, tmp_path @@ -532,98 +109,6 @@ async def test_compare_templates_reads_real_files( assert different["status"] == "success" assert different["comparison"]["identical"] is False - @pytest.mark.asyncio - async def test_template_management_adapter_error_and_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Test adapter error returns and exception handlers for template tools.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.apply_template = AsyncMock( - return_value=Mock(is_success=False, error="template apply failed") - ) - mock_adapter.save_to_template_library = AsyncMock( - side_effect=RuntimeError("library storage down") - ) - mock_adapter.list_template_library = AsyncMock( - side_effect=RuntimeError("index unavailable") - ) - - apply_tool = None - compare_tool = None - save_tool = None - list_tool = None - for tool in await mcp_server.list_tools(): - if tool.name == "apply_template": - apply_tool = tool.fn - if tool.name == "compare_templates": - compare_tool = tool.fn - if tool.name == "save_to_template_library": - save_tool = tool.fn - if tool.name == "list_template_library": - list_tool = tool.fn - - assert apply_tool is not None - assert compare_tool is not None - assert save_tool is not None - assert list_tool is not None - - apply_error = await apply_tool( - input_data=TemplateApplicationInput( - template_path="templates/fallback.prtdot", target_model="target.sldprt" - ) - ) - assert apply_error["status"] == "error" - assert "template apply failed" in apply_error["message"] - - save_exception = await save_tool(input_data={"template_name": "bad"}) - assert save_exception["status"] == "error" - assert save_exception["error_type"] == "internal" - - list_exception = await list_tool(input_data={"category": "all"}) - assert list_exception["status"] == "error" - assert list_exception["error_type"] == "internal" - - @pytest.mark.unit - def test_template_extraction_input_validation(self): - """Test input validation for template extraction.""" - # Valid input - valid_input = TemplateExtractionInput( - source_model="test.sldprt", - template_name="Test Template", - template_type="part", - save_path="templates/test.prtdot", - ) - assert valid_input.source_model == "test.sldprt" - assert valid_input.template_type == "part" - - # Test with optional parameters - full_input = TemplateExtractionInput( - source_model="test.sldprt", - template_name="Test Template", - template_type="part", - save_path="templates/test.prtdot", - include_custom_properties=True, - include_dimensions=False, - ) - assert full_input.include_custom_properties is True - assert full_input.include_dimensions is False - - @pytest.mark.unit - def test_template_application_input_validation(self): - """Test input validation for template application.""" - # Valid input - valid_input = TemplateApplicationInput( - template_path="template.prtdot", target_model="model.sldprt" - ) - assert valid_input.template_path == "template.prtdot" - assert valid_input.target_model == "model.sldprt" - - # Test default values - assert valid_input.overwrite_existing is False - assert valid_input.apply_dimensions is True - assert valid_input.apply_materials is True - @pytest.mark.unit def test_template_comparison_input_validation(self): """Test input validation for template comparison.""" @@ -650,108 +135,22 @@ def test_template_comparison_input_validation(self): class TestTemplateManagementBranchCoverage: """Additional branch coverage for template management tools.""" - @pytest.mark.asyncio - async def test_typed_template_tools_exception_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Exercise exception blocks for typed-input template tools via compat runner.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - by_name = {t.name: t.fn for t in await mcp_server.list_tools()} - - r1 = await by_name["extract_template"]({"bad": True}) - r2 = await by_name["apply_template"]({"bad": True}) - r3 = await by_name["batch_apply_template"]({"bad": True}) - r4 = await by_name["compare_templates"]({"bad": True}) - for result in (r1, r2, r3, r4): - assert result["status"] == "error" +@pytest.mark.asyncio +async def test_compare_templates_refuses_files_that_are_not_on_disk( + mcp_server, mock_config +): + """Two missing paths: an error naming them, not an invented comparison.""" + await register_template_management_tools(mcp_server, object(), mock_config) + compare = next( + t.fn for t in await mcp_server.list_tools() if t.name == "compare_templates" + ) - @pytest.mark.asyncio - async def test_batch_apply_template_adapter_error_path( - self, mcp_server, mock_adapter, mock_config - ): - """Cover adapter non-success branch for batch_apply_template.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.batch_apply_template = AsyncMock( - return_value=Mock(is_success=False, error="batch apply failed") - ) - - tool = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "batch_apply_template" - ) - result = await tool( - input_data=TemplateBatchInput( - template_path="templates/t.prtdot", - source_folder="./parts", - file_pattern="*.sldprt", - ) + result = await compare( + input_data=TemplateComparisonInput( + template1_path="templates/a.prtdot", template2_path="templates/b.prtdot" ) - assert result["status"] == "error" - assert "batch apply failed" in result["message"] - - @pytest.mark.asyncio - async def test_list_template_library_refuses_without_adapter( - self, mcp_server, mock_config - ): - """list_template_library has no local registry to filter/sort, so it - must refuse rather than inventing a filtered/sorted template list.""" - await register_template_management_tools(mcp_server, object(), mock_config) - tool = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "list_template_library" - ) - - usage_sorted = await tool( - input_data={ - "category": "drawings", - "search_term": "ISO", - "sort_by": "usage", - } - ) - date_sorted = await tool( - input_data={ - "category": "all", - "search_term": "Template", - "sort_by": "date", - } - ) - - assert usage_sorted["status"] == "error" - assert "does not support list_template_library" in usage_sorted["message"] - assert date_sorted["status"] == "error" - assert "does not support list_template_library" in date_sorted["message"] - - @pytest.mark.asyncio - async def test_library_adapter_error_result_paths( - self, mcp_server, mock_adapter, mock_config - ): - """Cover adapter non-success returns for save_to_template_library and list_template_library.""" - await register_template_management_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.save_to_template_library = AsyncMock( - return_value=Mock(is_success=False, error=None) - ) - mock_adapter.list_template_library = AsyncMock( - return_value=Mock(is_success=False, error=None) - ) - - save_tool = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "save_to_template_library" - ) - list_tool = next( - t.fn - for t in await mcp_server.list_tools() - if t.name == "list_template_library" - ) - - save_result = await save_tool(input_data={"template_name": "bad"}) - list_result = await list_tool(input_data={"category": "all"}) + ) - assert save_result["status"] == "error" - assert "failed to save to library" in save_result["message"].lower() - assert list_result["status"] == "error" - assert "failed to list template library" in list_result["message"].lower() + assert result["status"] == "error" + assert "not found on disk" in result["message"] diff --git a/tests/solidworks_mcp/ui/services/test_llm_service.py b/tests/solidworks_mcp/ui/services/test_llm_service.py index 6d347b9f..b661b775 100644 --- a/tests/solidworks_mcp/ui/services/test_llm_service.py +++ b/tests/solidworks_mcp/ui/services/test_llm_service.py @@ -76,7 +76,11 @@ def test_feature_helpers_and_coerce_plan() -> None: assert llm_service._tools_for_feature_name("Cut", 1) == ["create_cut"] assert llm_service._tools_for_feature_name("Revolve", 1) == ["create_revolve"] assert llm_service._tools_for_feature_name("Extrude", 1) == ["create_extrusion"] - assert llm_service._tools_for_feature_name("Unknown", 1) == ["analyze_geometry"] + assert llm_service._tools_for_feature_name("Unknown", 1) == [ + "get_model_info", + "list_features", + "get_mass_properties", + ] assert llm_service._family_for_feature_order(["assembly"], "extrude") == "assembly" assert llm_service._family_for_feature_order(["revolve"], "extrude") == "revolve"