SolidworksMCP-python
CLAUDE.md121 starsChanged 4 months agoMITView on GitHub
This file is the quick orientation guide for contributors and coding agents. Use either micromamba environment commands or local virtualenv commands. - Keep tool input schemas strict and explicit. - Maintain stable response payload shapes (status, message, execution_time, plus data payload). - Every tool runs inside one error boundary (tools/tool_boundary.py, applied by ToolRegistrar at registration). Do not write try/except in a tool or build error dicts by hand: - adapter results: require_success(result, context="Failed to ...") - bad arguments: normalize_input(...) or…
- Reads credentials
- Installs packages
In this repository12 other files it gives its agents.
- docs/llms.txtllms.txt
- live-demo-signoffSkill
- openspec-apply-changeSkill
- openspec-archive-changeSkill
- openspec-exploreSkill
- openspec-proposal-auditorSkill
- openspec-proposeSkill
- openspec-sync-specsSkill
- openspec-update-changeSkill
- extract-and-testSkill
- feature-tree-reconstructionSkill
- printer-profile-tolerancingSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
28 rules. About 0 are common, 10 are distinctive, and 18 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
18
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Use either micromamba environment commands or local virtualenv commands.
- Distinctive: line 73
Prefer adapter abstraction, not direct COM calls from tool modules.
- Distinctive: line 74
Keep Windows/COM behavior behind adapter boundaries.
- Distinctive: line 75
Use mock adapter for tests unless a test explicitly requires real SolidWorks.
- Very specific: line 79
Use project logging utilities (loguru/configured helpers).
- Distinctive: line 80
Avoid ad-hoc print statements in runtime server paths.
- Distinctive: line 84
Keep tool input schemas strict and explicit.
- Very specific: line 86
Every tool runs inside one error boundary (tools/tool_boundary.py, applied by ToolRegistrar at registration).
- Very specific: line 100
Default local path: run non-solidworks_only tests first.
- Very specific: line 103
Test layout mirrors src/ (enforced by tests/integration/test_test_layout.py):
- Very specific: line 109
never add "coverage bucket" files (test_coverage_*.py).
- Distinctive: line 133
When the bridge misbehaves, walk this list in order.
- Very specific: line 154
Fix: delete %TEMP%\gen_py\, restart the MCP server.
- Very specific: line 172
Fix: call the reset_circuit_breaker tool (all operations, or one by name), or wait for the timeout (SOLIDWORKS_MCP_CIRCUIT_BREAKER_TIMEOUT, …
- Very specific: line 186
Fix: keep every COM call on the thread that ran connect().
- Distinctive: line 197
Fix: check the file out in PDM, or test with a copy outside the vault.
- Very specific: line 236
Applies to: Every SelectByID2 / SelectByID call with no real callout.
- Very specific: line 252
Fix: Call model.ForceRebuild3(True) once before the first SelectByID2 in a feature operation.
- Very specific: line 259
Read recent %APPDATA%\Claude\logs\main.log entries for Launching MCP Server: solidworks and note the timestamp.
- Very specific: line 263
If SW is older or same, try a trivial call (get_model_info).
- Distinctive: line 265
If real error text surfaces, map to #1/#2/#5/#6 via the error signature above.
- Distinctive: line 267
Only then read server source to confirm.
- Very specific: line 285
Never move adapter calls onto another thread: no
asyncio.to_thread, run_in_executor, thread pools or synchronous FastMCP tools around COM … - Very specific: line 291
Do NOT call `pythoncom.CoInitialize() anywhere else in the adapter.
- Very specific: line 317
If you add a new COM-touching function: call
dynamic.Dispatch if you need to acquire a fresh IDispatch, not EnsureDispatch. - Very specific: line 342
Not every zero-arg accessor is a method.
- Very specific: line 345
When in doubt, check the gen_py wrapper: methods live in the class body as regular defs.
- Very specific: line 359
Run these after any change to
pywin32_adapter.py, com_executor.py, sw_type_info.pyor the settle pause::
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SolidWorks MCP Server (Python)
This file is the quick orientation guide for contributors and coding agents.
Platform and Runtime
- Primary runtime is Python 3.13+.
- Real COM automation requires Windows + SolidWorks installed.
- Cross-platform development is possible in mock/test mode.
Build and Development Commands
Use either micromamba environment commands or local virtualenv commands.
Preferred PowerShell workflow
# Show command help
.\dev-commands.ps1
# Full install in micromamba env
.\dev-commands.ps1 dev-install
# Fast test pass (no SolidWorks-required tests)
.\dev-commands.ps1 dev-test
# Full test run including real SolidWorks integration
.\dev-commands.ps1 dev-test-full
# Lint and format
.\dev-commands.ps1 dev-lint
.\dev-commands.ps1 dev-format
# Docs build/serve
.\dev-commands.ps1 dev-docs-build
.\dev-commands.ps1 dev-docs-strict
.\dev-commands.ps1 dev-docs-audit
.\dev-commands.ps1 dev-docsVirtualenv direct workflow
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install --upgrade pip setuptools wheel
.\.venv\Scripts\python.exe -m pip install -e ".[dev,test,docs]"
# Run server
.\.venv\Scripts\python.exe -m solidworks_mcp.server
# Lint/types/tests/docs (CI runs mypy too and fails on any error)
.\.venv\Scripts\python.exe -m ruff check src tests
.\.venv\Scripts\python.exe -m mypy src/solidworks_mcp
.\.venv\Scripts\python.exe -m pytest tests -m "not solidworks_only"
.\.venv\Scripts\python.exe -m mkdocs build --cleanArchitecture
- Server entrypoint:
src/solidworks_mcp/server.py - CLI entrypoint:
src/solidworks_mcp/server_cli_fixed.py - Adapters:
src/solidworks_mcp/adapters/pywin32_adapter.py: real SolidWorks COM adapter (Windows)mock_adapter.py: mock adapter for tests and CI-like runsfactory.py: adapter selection/routing logic
- Tools:
src/solidworks_mcp/tools/(modeling, sketching, drawing, export, analysis, automation, templates, VBA, docs discovery) - Agent harness:
src/solidworks_mcp/agents/(prompt schemas, smoke test CLI, run/error persistence)
Key Patterns
COM and Adapter Safety
- Prefer adapter abstraction, not direct COM calls from tool modules.
- Keep Windows/COM behavior behind adapter boundaries.
- Use mock adapter for tests unless a test explicitly requires real SolidWorks.
Logging and Output
- Use project logging utilities (
loguru/configured helpers). - Avoid ad-hoc print statements in runtime server paths.
Validation and Tool Contracts
- Keep tool input schemas strict and explicit.
- Maintain stable response payload shapes (
status,message,execution_time, plus data payload). - Every tool runs inside one error boundary (
tools/tool_boundary.py, applied byToolRegistrarat registration). Do not writetry/exceptin a tool or build error dicts by hand:- adapter results:
require_success(result, context="Failed to ...") - bad arguments:
normalize_input(...)or raiseInvalidInputError - a missing capability:
require_capability(adapter, "method") - any other tool-level failure: raise
ToolOperationError(message)
- adapter results:
- Error payloads always carry
status: "error",message,error_type,hintandexecution_time(dataonly when the adapter returned diagnostics).error_typecomes from the ordered rule table intools/error_classifier.py; add a category by appending a rule there.
Testing Guidance
- Default local path: run non-
solidworks_onlytests first. - Real integration path: run
dev-test-fullon Windows with SolidWorks available. - Harness and generated report artifacts may write under
tests/.generated/and.solidworks_mcp/. - Test layout mirrors
src/(enforced bytests/integration/test_test_layout.py):src/solidworks_mcp/<path>/<module>.py→tests/solidworks_mcp/<path>/test_<module>[_<topic>].py- a package's
__init__.py→test_init.py - cross-module / end-to-end tests →
tests/integration/ - real-SolidWorks tests →
tests/live/ - never add "coverage bucket" files (
test_coverage_*.py); put each test beside the module it exercises
- Coverage is measured honestly: there is no
# pragma: no cover. Code no test can reach is deleted, after review, via the dead-code ledger (openspec/changes/archive/2026-10-30-full-coverage-and-error-boundary/dead-code.md).
Documentation Guidance
- Build docs before commit when touching docs pages:
.\dev-commands.ps1 dev-docs-build.\dev-commands.ps1 dev-docs-strict
- For local preview:
.\dev-commands.ps1 dev-docs
Agent and Model Notes
- VS Code Copilot subscription is suitable for chat-based workflows.
- Local Python smoke tests require explicit provider credentials:
- GitHub Models:
GH_TOKENorGITHUB_API_KEY - OpenAI:
OPENAI_API_KEY - Anthropic:
ANTHROPIC_API_KEY
- GitHub Models:
Troubleshooting Runbook
When the bridge misbehaves, walk this list in order. Compiled from SolidWorks forum threads, pywin32 issues, and observed failures on this install. Last updated 2026-04-24.
1. OpenDoc6 HRESULT failure — pass-by-ref params
- Cause: pywin32
makepy/gencachemarks SW's pass-by-referrorsandwarningsparameters as non-optional inputs. Calls fail unlesspythoncom.Missingis passed explicitly. - Check: grep server code for
OpenDoc6(; every callsite should passpythoncom.Missingfor the last two params. - Fix:
model, errors, warnings = sw.OpenDoc6(path, type, opts, '', pythoncom.Missing, pythoncom.Missing) - Error codes: warning=128 = already open (not fatal); error=1024 = generic open failure. S_OK with null return is also possible.
2. Member not found / NoneType not callable — stale gencache
- Cause: pywin32 caches SW type-library wrappers under
%TEMP%\gen_py\. SW upgrades (e.g. 2024 → 2025) or patches leave wrappers pointing at the old TLB. - Fix: delete
%TEMP%\gen_py\, restart the MCP server. Rebuilds on first call.
3. No active model AND OpenDoc6 errors together — stale COM handle
- Cause: MCP server process grabbed a COM pointer at startup; user has since quit and reopened SolidWorks. Pointer is dangling.
- Check: compare MCP server start time (Claude
main.log→Launching MCP Server: solidworks) to currentSLDWORKS.exestart time. - Fix: restart Claude Desktop (respawns MCP server, which grabs a fresh SW handle). Restarting SolidWorks alone will NOT fix this.
4. Circuit breaker is open for <tool>
- Cause: the server's circuit breaker pauses an operation after 5 failures. Subsequent calls fail fast even when the underlying issue is fixed. Before #208 a single failure could count many times: the server's router fell back to the VBA adapter, which re-entered the router.
- Fix: call the
reset_circuit_breakertool (all operations, or one by name), or wait for the timeout (SOLIDWORKS_MCP_CIRCUIT_BREAKER_TIMEOUT, default 60 s), or restart the server.
5. COM apartment / threading mismatch — FastMCP async workers
- Cause: SolidWorks COM is STA (single-threaded apartment). An IDispatch
proxy obtained on thread A cannot be invoked from thread B. FastMCP runs
tool handlers on worker threads distinct from where
connect()ran. - Signature (critical): pywin32 late-binding surfaces this as
AttributeError: SldWorks.Application.<method>at attribute lookup — NOT aspywintypes.com_error. Theexcept com_errorbranch in_handle_com_operationtherefore misses it, and the generic handler flattens the message to the source+method name with no traceback. - Fix: keep every COM call on the thread that ran
connect(). See "COM threading architecture" below. (History: a dedicatedComExecutorthread was used from 2026-04-24; the adapter no longer routes through it, andComExecutornow only serves standalone scripts.)
6. PDM vault files
- Cause:
OpenDoc6on a file under a PDM working folder fails when the file isn't checked out or cached locally. - Check: target path has PDM vault metadata / is under a PDM working folder.
- Fix: check the file out in PDM, or test with a copy outside the vault.
7. Silent-mode UI leak
swOpenDocOptions_Silentstill pops the UI on some SW-2025 SP levels. Cosmetic only; not a failure.
8. SW 2025 SP0 drawing crashes
- SP0 has reported
.slddrwopen crashes. If the target is a drawing, suggest upgrading to SP1+.
9. MCP log silence
- FastMCP banner output (emoji-prefixed lines to stdout) is misparsed as JSON-RPC by the Claude host — noise, not errors.
- Actual tool-call tracebacks go to stderr and are NOT captured in
%APPDATA%\Claude\logs\mcp-server-solidworks.log. Check the%LOCALAPPDATA%\solidworks_mcp\logs\directory and the FastMCP install dir for a separate Python log.
10. Claude Code settings.json UTF-8 BOM (host-side, not SW)
- A BOM on
~/.claude/settings.jsonmakes Claude Code silently drop all user settings ([SettingsIo] Failed to read ... Unexpected token ''). Strip the BOM; write plain UTF-8.
11. SelectByID2 Callout type mismatch — use VT_DISPATCH null, not None
- Signature:
(-2147352571, 'Type mismatch.', None, 8)on anySelectByID2call. Cause: The
Calloutparameter (8th arg) is typedVT_DISPATCH. PythonNonemarshals asVT_NULLwhich SW rejects. Must pass an explicit COM null pointer:import pythoncom, win32com.client as _win32com null_callout = _win32com.VARIANT(pythoncom.VT_DISPATCH, None) model.Extension.SelectByID2("", "EDGE", x, y, z, append, mark, null_callout, 0)- Applies to: Every
SelectByID2/SelectByIDcall with no real callout.
12. InsertFeatureChamfer is on IFeatureManager, not IModelDocExtension
- Signature:
<unknown>.InsertFeatureChamferwhen calling viamodel.Extension. - Cause:
InsertFeatureChamfer(DISPID 83) is onIFeatureManager. Routing throughmodel.Extension(IModelDocExtension) causesDISP_E_MEMBERNOTFOUND. - Fix:
fm = model.FeatureManager; fm.InsertFeatureChamfer(1, 1, width_m, pi/4, 0, 0, 0, 0) - More detail: See
docs/agents/com-api-pitfalls.mdfor the full pattern catalogue.
13. ForceRebuild3(True) required before coordinate-based edge/face selection
- Signature:
SelectByID2("", "EDGE", x, y, z, ...)returnsFalseon a freshly created feature. - Cause: New feature edges are not tessellated until an explicit rebuild.
SelectByID2uses the tessellated mesh to resolve coordinates. - Fix: Call
model.ForceRebuild3(True)once before the firstSelectByID2in a feature operation.
Full COM pitfall catalogue for LLM agents:
docs/agents/com-api-pitfalls.md
Decision order when starting a debug session
- Read recent
%APPDATA%\Claude\logs\main.logentries forLaunching MCP Server: solidworksand note the timestamp. - Compare to current
SLDWORKS.exeprocess start (Task Manager). If SW is newer than the server → #3, restart Claude Desktop first. - If SW is older or same, try a trivial call (
get_model_info). If it returns a circuit-breaker error, wait 60s and retry → #4. - If real error text surfaces, map to #1/#2/#5/#6 via the error signature above.
- Only then read server source to confirm.
COM threading architecture
Invariants every new COM-touching code path must respect. Revised 2026-10-21 to match the code (the earlier ComExecutor design is no longer used by the adapter).
1. All COM calls run on the thread that called connect()
_ComSessionCoordinator.connect() runs pythoncom.CoInitialize() and
acquires swApp on the calling thread, which is the server's asyncio
event-loop thread. Every tool is an async function that calls the adapter
directly on that loop, and _handle_com_operation runs its closure
synchronously, so all COM work stays in that one STA apartment.
Consequences:
- Never move adapter calls onto another thread: no
asyncio.to_thread,run_in_executor, thread pools or synchronous FastMCP tools around COM work.swApp/currentModelused from another thread raise the cross-threadAttributeErrordescribed in runbook item #5, so_handle_com_operationrefuses any call from a thread other than the oneinitialize_com_apartmentrecorded (error_type: com_wrong_thread). - Do NOT call
pythoncom.CoInitialize()anywhere else in the adapter;_ComSessionCoordinatorowns the apartment. com_executor.ComExecutor(a dedicated STA worker thread) is still available for standalone scripts such assrc/utils/convert_step_to_sldprt.py.
2. Every COM operation is followed by a settle pause
_handle_com_operation calls _settle_after(operation_name) in its
finally:: 0.25 s after every operation and 1.0 s after a document
open/create/close (SOLIDWORKS_MCP_COM_SETTLE_SECONDS /
SOLIDWORKS_MCP_DOC_SETTLE_SECONDS). Driving SolidWorks 2026 back-to-back
crashed it in its idle-time UI refresh (COM pitfall #26). Route new COM work
through _handle_com_operation so it gets the pause; unit tests set both
values to 0 in tests/conftest.py.
3. Late binding is forced, always
Connection acquires swApp with _dynamic_dispatch (a thin wrapper over
win32com.client.dynamic.Dispatch) instead of
win32com.client.Dispatch. Rationale: when the makepy-generated
gen_py wrapper is loaded (it is, as soon as sw_type_info is
imported), plain Dispatch would auto-upgrade to an early-bound wrapper.
Early-bound wrappers reject the VARIANT-based pass-by-ref out-parameters
used by OpenDoc6 and many other SW calls; migrating to pythoncom.Missing
for every such call is a much larger change than we want.
If you add a new COM-touching function: call dynamic.Dispatch if you
need to acquire a fresh IDispatch, not EnsureDispatch.
4. Method flagging via sw_type_info
sw_type_info.flag_methods(obj, *interfaces) tells pywin32's late
binding to resolve specific names as methods (Invoke with method
flags) rather than properties. Without flagging, zero-arg SW methods like
GetTitle() raise TypeError: 'str' object is not callable because
the dispatch returns the string value, which Python then tries to call.
Apply flagging:
- On
swAppafter acquiring it →flag_methods(app, "ISldWorks") - On a newly-opened document →
flag_doc(model, doc_type)(infers from doc type: Part=1, Assembly=2, Drawing=3) - On any intermediate dispatch returned from a SW call →
sw_type_info.flagged(x, "IInterfaceName")inline-style
Interface names come from the gen_py wrapper (run
python -m win32com.client.makepy "C:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\sldworks.tlb"
to regenerate after a SW version upgrade).
5. Properties are still properties
Not every zero-arg accessor is a method. IConfiguration.Name,
ModelDoc2.Visible, etc. are genuine properties — read them without
(). If you flag them as methods you'll get the opposite TypeError.
When in doubt, check the gen_py wrapper: methods live in the class body
as regular defs; properties use _prop_map_get_ / _prop_map_put_.
6. Regression tests
See tests/live/test_live_sw_regression.py for the safety net:
- ComExecutor start/stop/exception semantics (the executor scripts use)
- flag_methods incrementality + per-interface correctness
- Late-bound
swAppacquisition get_model_infofields populate correctly- a call from a worker thread is refused cleanly and the connect thread
keeps working (
test_com_calls_stay_on_the_connect_thread)
Run these after any change to pywin32_adapter.py, com_executor.py,
sw_type_info.py or the settle pause::
$env:SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1
.\.venv\Scripts\python.exe -m pytest tests/live/test_live_sw_regression.py -vReference sources
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

