SolidWorks MCP
# SolidWorks MCP
[](LICENSE)

**Built and used on SOLIDWORKS 2021.** This repository's additions are developed and
tested against SOLIDWORKS 2021; see [Requirements](#requirements-and-compatibility) for other releases.
Let an AI agent (Claude, or any other MCP client) model real parametric parts and
assemblies in **your own SolidWorks** — and **check its own work**. Every
modelling call returns the measured volume, mass and bounding box, so the agent
can compare the result with the spec and correct itself instead of guessing that
it "looks about right".
> **About this repository.** This is an independent continuation of
> [hjbaard/SolidWorks-MCP](https://github.com/hjbaard/SolidWorks-MCP) (MIT), maintained at
> [Sangpaa/SolidWorks-MCP](https://github.com/Sangpaa/SolidWorks-MCP). It includes upstream up to 0.21.0 plus its own additions:
> `batch`, `run_python` / `stop_python`, dialogs of SolidWorks' helper processes
> (e.g. the Simulation solver), faster COM access for large assemblies, and notes on driving
> SOLIDWORKS Simulation. It is **not** published to PyPI: `uvx solidworks-mcp` installs the
> upstream package, so install from this repository as shown below.
>
> SOLIDWORKS is a registered trademark of Dassault Systèmes. This project is not
> affiliated with, endorsed by or sponsored by Dassault Systèmes.
<p align="center">
<img src="Docs/images/bracket.png" width="32%" alt="3D-print mounting bracket with counterbored holes, bolt circle and cable slot">
<img src="Docs/images/thread.png" width="32%" alt="M10 bolt with a real, printable ISO metric thread">
<img src="Docs/images/vase.png" width="32%" alt="Revolved and shelled vase">
</p>
<p align="center">
<img src="Docs/images/pipe.png" width="32%" alt="Swept pipe with rounded bends">
<img src="Docs/images/loft.png" width="32%" alt="Lofted and shelled horn">
</p>
<p align="center"><sub>Built by the tools themselves: a mounting bracket (every step checked against a hand calculation), an M10 bolt with a real thread, a revolved + shelled vase, a swept pipe, a lofted + shelled horn.</sub></p>
## 처음 사용하는 분을 위한 가이드 (한국어)
> 이 저장소는 [hjbaard/SolidWorks-MCP](https://github.com/hjbaard/SolidWorks-MCP)(MIT)에서 출발한 **독립 저장소**입니다.
> 원본에 없는 기능(`batch`, `run_python`, 헬퍼 프로세스 대화상자 감지, Simulation 연동 메모 등)이 들어 있으므로,
> PyPI의 `uvx solidworks-mcp`(원본 버전) 대신 **이 저장소에서 설치**하세요.
### 0. 이게 뭔가요?
AI 에이전트(Claude Code, Codex, Antigravity 등)가 **내 PC에서 실행 중인 SolidWorks**를 COM으로 직접 조작해
파트·어셈블리를 모델링하고, 매 단계마다 부피/질량/바운딩박스를 측정해서 스스로 검증하게 해 주는 MCP 서버입니다.
에이전트에게 "100×80×8 mm 판에 M5 카운터보어 4개 뚫어줘"처럼 말하면 실제 SolidWorks에 피처 트리가 그대로 생깁니다.
### 1. 준비물
| 항목 | 설명 |
|---|---|
| Windows 10/11 | COM을 쓰므로 Windows 전용 |
| SolidWorks (라이선스 활성) | **SOLIDWORKS 2021 기준**으로 개발·사용하는 저장소입니다. 원본은 2026에서 전체 테스트, 2020 이상에서 selftest 통과가 보고되어 있음 |
| Git | 저장소 clone용 |
| [uv](https://docs.astral.sh/uv/getting-started/installation/) (권장) 또는 Python 3.11+ | uv가 Python까지 알아서 받아 줍니다 |
| AI 클라이언트 중 하나 이상 | Claude Code / Codex CLI / Antigravity |
uv 설치 (PowerShell):
```powershell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```
### 2. 설치
**방법 A — 그냥 써 보기 (설치 폴더 없이):** uv가 이 저장소에서 바로 받아 실행합니다. 이 경우 아래 4단계의
command/args 대신 `uvx` / `["--from", "git+https://github.com/Sangpaa/SolidWorks-MCP", "solidworks-mcp"]`를 쓰면 됩니다.
```powershell
uvx --from git+https://github.com/Sangpaa/SolidWorks-MCP solidworks-mcp --selftest
```
**방법 B — clone해서 쓰기 (권장: 업데이트·수정·테스트가 쉬움):**
PowerShell에서 (경로는 원하는 곳으로 바꿔도 됩니다):
```powershell
cd $HOME\Desktop
git clone https://github.com/Sangpaa/SolidWorks-MCP.git
cd SolidWorks-MCP
# uv 사용 시 (권장)
uv venv --python 3.11
uv pip install -e ".[dev]"
# uv 없이 Python만 있을 때
# python -m venv .venv
# .\.venv\Scripts\python.exe -m pip install -e ".[dev]"
```
설치가 끝나면 다음 파일이 있어야 합니다. **이후 모든 클라이언트 설정에서 이 경로를 씁니다.**
```
C:\Users\<사용자>\Desktop\SolidWorks-MCP\.venv\Scripts\python.exe
```
> `-e`(editable) 설치이므로 나중에 `git pull`만 하면 최신 코드가 반영됩니다. 반영 후에는 AI 클라이언트를 재시작하세요.
### 3. 동작 확인 (selftest)
1. **SolidWorks를 먼저 실행**합니다. 서버는 이미 떠 있는 SolidWorks에 붙을 뿐, 직접 띄우지 않습니다.
2. 열린 대화상자가 없는 상태(빈 화면)에서:
```powershell
.\.venv\Scripts\python.exe -m solidworks_mcp.server --selftest
```
작은 파트 몇 개를 만들고 손계산과 비교한 뒤 저장하지 않고 닫습니다. 모든 항목이 통과하면 준비 완료입니다.
첫 실행은 COM 타입 라이브러리 래퍼(gen_py)를 생성하느라 1~2분 걸릴 수 있습니다.
### 4. AI 클라이언트에 등록
세 클라이언트 모두 **stdio 방식**으로, 같은 명령을 실행하도록 등록하면 됩니다.
- command: `C:\Users\<사용자>\Desktop\SolidWorks-MCP\.venv\Scripts\python.exe`
- args: `-m solidworks_mcp.server`
아래 예시의 `<사용자>`와 경로는 본인 환경에 맞게 바꾸세요.
#### 4-1. Claude Code
```powershell
claude mcp add solidworks --scope user -- "C:\Users\<사용자>\Desktop\SolidWorks-MCP\.venv\Scripts\python.exe" -m solidworks_mcp.server
```
- `--scope user`: 모든 프로젝트에서 사용. 특정 폴더에서만 쓰려면 생략(기본값 `local`).
- 확인: `claude mcp list` → `solidworks: ... ✔ Connected`
- Claude Code 세션 안에서 `/mcp` 를 입력하면 연결 상태와 도구 목록을 볼 수 있습니다.
- 제거: `claude mcp remove solidworks -s user`
- 오래 걸리는 작업(큰 어셈블리, 해석)이 타임아웃되면 환경변수 `MCP_TOOL_TIMEOUT`(ms)을 늘려서 실행하세요.
#### 4-2. Codex (OpenAI Codex CLI / IDE 확장)
명령으로 등록:
```powershell
codex mcp add solidworks -- "C:\Users\<사용자>\Desktop\SolidWorks-MCP\.venv\Scripts\python.exe" -m solidworks_mcp.server
```
또는 `%USERPROFILE%\.codex\config.toml`에 직접 추가 (CLI와 VS Code 확장이 같은 파일을 씁니다):
```toml
[mcp_servers.solidworks]
command = 'C:\Users\<사용자>\Desktop\SolidWorks-MCP\.venv\Scripts\python.exe'
args = ["-m", "solidworks_mcp.server"]
startup_timeout_sec = 60 # 첫 실행 시 gen_py 생성 시간 확보
tool_timeout_sec = 300 # 기본 60초는 리빌드·내보내기에 짧을 수 있음
```
- TOML에서 작은따옴표(`'...'`)는 역슬래시를 그대로 둡니다. 큰따옴표를 쓰려면 `\\`로 이스케이프하세요.
- 확인: `codex mcp list`, Codex TUI 안에서 `/mcp`
- 제거: `codex mcp remove solidworks`
#### 4-3. Antigravity (Google)
1. 에이전트 패널 우측 상단 `…` → **MCP Servers** → **Manage MCP Servers** → **View raw config**
2. 열린 `mcp_config.json` (`%USERPROFILE%\.gemini\antigravity\mcp_config.json`)에 추가:
```json
{
"mcpServers": {
"solidworks": {
"command": "C:\\Users\\<사용자>\\Desktop\\SolidWorks-MCP\\.venv\\Scripts\\python.exe",
"args": ["-m", "solidworks_mcp.server"]
}
}
}
```
3. 저장 후 MCP 관리 화면에서 **Refresh** → `solidworks`가 켜져 있고 도구 목록이 보이면 성공입니다.
- JSON에서는 역슬래시를 `\\`로 두 번 쓰거나, `C:/Users/<사용자>/...`처럼 슬래시를 써도 됩니다.
- 이미 다른 서버가 있으면 `mcpServers` 안에 `"solidworks": {...}` 항목만 추가하세요.
### 5. 첫 요청 해 보기
SolidWorks를 켠 상태에서 에이전트에게:
> SolidWorks MCP로 100 × 80 × 8 mm 판을 만들고, 가운데 Ø16 구멍, 모서리에서 12 mm 떨어진 M5 카운터보어 4개,
> 모서리 R5를 넣어줘. 매 단계 부피를 손계산과 비교하고, 끝나면 스크린샷을 찍고 `out/plate.sldprt`로 저장해줘.
팁:
- 에이전트는 연결 시 서버가 주는 짧은 가이드를 받고, 자세한 레시피는 리소스 `solidworks://guide`
([`src/solidworks_mcp/guide.md`](src/solidworks_mcp/guide.md))에 있습니다. 결과가 이상하면 "가이드를 먼저 읽어"라고 지시하세요.
- 사람이 그린 기존 파트도 다룰 수 있습니다: "열려 있는 파트의 피처 목록 보여줘", "Sketch3을 10 mm 돌출해줘".
- 단위는 항상 **mm / 도(°)**입니다.
- 도구가 커버하지 않는 작업(큰 어셈블리 메이트 점검, 서브어셈블리 내부 부품, Simulation 등)은 `run_python`
도구로 서버의 SolidWorks 연결에서 직접 API를 호출합니다(별도 스크립트보다 약 25배 빠름).
- 여러 단계를 한 번에: `batch` 도구 (열기 → 수정 → 저장 → 닫기 등).
### 6. 자주 겪는 문제
| 증상 | 해결 |
|---|---|
| `No running SolidWorks found` / 연결 실패 | SolidWorks를 먼저 켜고, 클라이언트(또는 MCP 서버)를 재시작 |
| 클라이언트에서 서버가 `Failed` / 연결 안 됨 | 설정한 python.exe 경로가 실제로 있는지 확인. 터미널에서 위 command+args를 직접 실행해 오류 메시지 확인 |
| 첫 호출이 매우 느림 / `EnsureModule` 오류 | 첫 COM 호출에서 gen_py 생성 중. 기다리거나, 꼬였으면 `%TEMP%\gen_py` 폴더 삭제 후 재시도 |
| "SolidWorks is waiting on a dialog" | SolidWorks에 모달 대화상자가 떠 있음. 직접 닫거나 에이전트에게 `list_dialogs` / `answer_dialog` 사용을 지시 |
| `{ok: false, error: ...}` | 정상 동작입니다(잘못된 형상을 만드는 대신 실패를 알림). 메시지에 원인이 적혀 있음 |
| Z-up 템플릿 관련 거부 | 새 문서 대화상자의 Y-up 선택은 API로 만든 파트에 적용되지 않습니다. Y-up 파트를 파트 템플릿으로 저장하고 그 파일을 기본 파트 템플릿으로 지정 |
| 장시간 사용 후 느려짐 / 메모리 경고 | 작업 저장 후 SolidWorks 재시작 (작업 실행 중에는 금지) |
| 여러 클라이언트를 동시에 사용 | 한 SolidWorks에 여러 에이전트가 동시에 붙으면 서로 간섭합니다. 한 번에 하나만 사용하세요 |
### 7. 업데이트 / 기여
```powershell
cd $HOME\Desktop\SolidWorks-MCP
git pull
uv pip install -e ".[dev]" # 의존성이 바뀐 경우에만
```
- 테스트: `.\.venv\Scripts\python.exe -m pytest -m "not solidworks"` (SolidWorks 없이 빠른 단위 테스트),
SolidWorks를 켠 상태에서는 `-m pytest` 전체.
- 변경은 브랜치를 만들어 PR로 올리고, 병합 후 브랜치는 삭제합니다.
---
## Why this server
- **It verifies, not just generates.** Features report measured geometry;
dimensions and mates are measured back after the rebuild.
- **Fully defined sketches.** Every sketch is constrained the way a designer
would: dimensions from the origin, relations only where the geometry is
exactly horizontal, vertical or on the origin. Tools return their dimensions
by role (`width@Sketch1`), so the part stays editable, in SolidWorks or
through the agent.
- **Real CAD, not just primitives.** Extrude, revolve, sweep, loft and splines;
holes, counterbores, slots and pockets on any face; rounded polygon corners; ISO holes from the Hole Wizard; real ISO metric threads;
fillets, chamfers, shells, patterns, mirrors, ribs, equations and materials. Assemblies
with mates and interference checks. STEP/STL/3MF export and screenshots.
Engraved and embossed text. Work on existing parts: list, delete, suppress and reorder features; read, extrude and cut a person's sketches; import STEP. Colours per part or component. Joints with concentric and angle mates, checked over their range. Printability checks and dimensioned drawings. Planes at any offset or angle. Several bodies per part, combined and split. Variable fillets and full rounds. Free sketches with tangent arcs and splines. 88 tools in total.
- **It fails loud.** A call that cannot do what was asked returns
`{ok: false, error}` with the cause, never silently wrong geometry.
- **A typed tool surface.** Modelling goes through typed tools; this fork adds
`run_python` as an explicit escape hatch for work no tool covers.
- **Tested against real SolidWorks.** 764 tests; each feature's integration test
compares the result with a hand calculation.
- **Local.** It talks to your running SolidWorks over COM; the server itself
makes no network calls.
## Quickstart
1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/).
2. **Start SolidWorks** and leave it open (the server attaches to the running
instance — it does not launch one).
3. Register the server with your MCP client.
**Claude Code:**
```bash
claude mcp add solidworks -- uvx --from git+https://github.com/Sangpaa/SolidWorks-MCP solidworks-mcp
```
**Claude Desktop** (`claude_desktop_config.json`) or any other client:
```json
{
"mcpServers": {
"solidworks": {
"command": "uvx",
"args": ["--from", "git+https://github.com/Sangpaa/SolidWorks-MCP", "solidworks-mcp"]
}
}
}
```
4. Ask for a part, for example:
> Design a 100 × 80 × 8 mm mounting plate with a Ø16 mm centre bore, four
> counterbored M5 holes 12 mm from the corners and R5 corners. Check the
> volume against your own calculation, then export a fine STL.
## Guidelines for agents
The server hands every MCP client short modelling guidelines when it connects
(conventions, verify each step, known pitfalls). The full guide is the resource
`solidworks://guide`: recipes for holes, ribs, threads and assemblies, 3D-print
advice, and how to reverse-engineer a part from a mesh (STL/3MF). The same text
is in [`src/solidworks_mcp/guide.md`](src/solidworks_mcp/guide.md).
## Requirements and compatibility
- Windows, with SolidWorks installed, licensed and **running**.
- Python 3.11+ (uv fetches one if needed).
- A **Y-up part template**, SolidWorks' standard. Since SOLIDWORKS 2025 new
parts can also be Z-up; the tools build in the Y-up frame and refuse a Z-up
part with a message that says so. Choosing Y-up in the New Document dialog
is not used for parts made through the API: make a Y-up part, save it as a
`.prtdot`, and set that file as the part template under Tools > Options >
System Options > Default Templates.
- **This repository targets SOLIDWORKS 2021.** Its additions (`batch`,
`run_python`, helper-process dialogs, the large-assembly speed-ups) are
developed and measured on SOLIDWORKS 2021; other releases are not tested here.
- **Upstream: SOLIDWORKS 2020 or newer.** Users confirmed all selftest checks on
SOLIDWORKS 2020 (SP5), 2025 and 2026, in English, German, French, Italian,
Russian and Chinese; 2024 SP5 passed all but the material check, since
fixed. The full test suite runs on SOLIDWORKS 2026 (3DEXPERIENCE R2026x).
To check your installation, run this with SolidWorks open:
```bash
uvx --from git+https://github.com/Sangpaa/SolidWorks-MCP solidworks-mcp --selftest
```
It builds a few small parts, compares each with a hand calculation and
closes them unsaved. Please paste its output in a
[compatibility report](https://github.com/Sangpaa/SolidWorks-MCP/issues/new?template=compatibility.yml),
whether it worked or not.
**Status: early (0.x).** It works end-to-end, but tool names and conventions
may still change. See [CHANGELOG.md](CHANGELOG.md).
## Troubleshooting
- **Start with the selftest**: `uvx --from git+https://github.com/Sangpaa/SolidWorks-MCP solidworks-mcp --selftest` shows your
SolidWorks release, language and templates, and which tool areas work. Add
its output to a [bug report](https://github.com/Sangpaa/SolidWorks-MCP/issues/new?template=bug_report.yml).
- **Drawings get slower and come out without dimensions, or SolidWorks
freezes, after many tool calls** — switch off *Enhanced graphics
performance* (Tools > Options > System Options > Performance) and restart
SolidWorks. With it on, `make_drawing` slowed from 8 to 16 s over a series
of calls and then placed 0 dimensions; with it off it stayed at 7 s.
- **"No running SolidWorks found" / connection fails** — SolidWorks must be
*running* before you start the server or run a script; it attaches to the active
instance via `GetActiveObject` and does not launch one.
- **First call is slow or `EnsureModule` errors** — the first COM call generates the
makepy typelib wrappers under your temp `gen_py` folder. Let it finish; if it gets
into a bad state, delete the `gen_py` cache and retry. Early binding is mandatory on
this build (see [Architecture](#architecture)).
- **"SolidWorks is waiting on a dialog"**: a modal dialog holds the call.
`list_dialogs` shows it; `answer_dialog('<button>')` presses a button and returns
the held call's result. You can also answer it in SolidWorks yourself.
- **A feature returns `{ok: false, error: ...}`** — that is by design: every tool
fails loud with a readable message rather than silently producing wrong
geometry. Read the message; it names the likely cause.
- **The full test suite runs on SOLIDWORKS 2026 (3DEXPERIENCE R2026x).** On other
builds the verified enum values or method signatures may differ — re-run
`scripts/introspect_api.py` to inspect your installed typelib.
- **`uvx` fails to download behind a company network** that inspects TLS
(certificate errors) — start it with `uvx --system-certs --from git+https://github.com/Sangpaa/SolidWorks-MCP solidworks-mcp`, so
it uses the certificates Windows trusts.
## Development
Clone the repository, then install it editable into a venv:
```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e .[dev]
```
To run the MCP server from this checkout instead of via uvx, point your client
at the venv's Python:
```json
{
"mcpServers": {
"solidworks": {
"command": "C:\\path\\to\\SolidWorks-MCP\\.venv\\Scripts\\python.exe",
"args": ["-m", "solidworks_mcp.server"]
}
}
}
```
### Run the verification scripts
With SolidWorks open:
```powershell
.\.venv\Scripts\python.exe scripts\probe_connection.py # M0
.\.venv\Scripts\python.exe scripts\m1_block.py # M1
.\.venv\Scripts\python.exe scripts\m2_parametric.py # M2
.\.venv\Scripts\python.exe scripts\test_mcp_server.py # M3 (full MCP loop over stdio)
.\.venv\Scripts\python.exe scripts\m5_demo_bracket.py # M5 (3D-print bracket, every step verified)
```
`scripts/introspect_api.py` regenerates/inspects the installed typelib and prints
verified enum values — run it if SolidWorks is upgraded and signatures change.
### Tests
```powershell
.\.venv\Scripts\python.exe -m pytest # all tests
.\.venv\Scripts\python.exe -m pytest -m "not solidworks" # fast unit layer, no SolidWorks
```
Two layers: **pure unit tests** (units, selector/direction parsing, polygon
cleaning, the component-placement maths, and that every MCP tool forwards its
arguments to the right session method) run anywhere; **integration tests**
(`solidworks` marker) drive a running SolidWorks and verify each feature's
volume — or each component's placement — against a hand calc. They auto-skip if
SolidWorks isn't reachable.
## Tools
The server speaks MCP over **stdio**.
### Part tools
| Tool | Purpose |
|---|---|
| `get_status` | Is SolidWorks reachable? revision, server version, active/current part |
| `new_part` | Create a new empty part (becomes current) |
| `add_box(width_mm, height_mm, depth_mm, name)` | Sketch rectangle + extrude; returns mass properties |
| `add_cylinder(diameter_mm, height_mm, name)` | Cylinder by revolving a profile 360° about an axis (Y axis) |
| `add_disc(diameter_mm, thickness_mm, name, x_mm, y_mm)` | Disc/puck/flange: circle extruded along +Z, centred at (x, y) (holes/patterns compose) |
| `add_cone(bottom_diameter_mm, top_diameter_mm, height_mm, name)` | Cone/frustum by revolve (top Ø = 0 → full cone) |
| `add_revolved_profile(profile_mm, angle_deg, name, corner_radii_mm, axis_mm)` | Revolve any closed `(radius, height)` profile about the Y axis (shafts, vases, rings), or `[x, y]` points about any line `axis_mm` on the Front plane; `corner_radii_mm` rounds its edges |
| `add_swept_pipe(path_mm, diameter_mm, bend_radius_mm, name, smooth)` | Sweep a round profile along a 2D path with rounded bends (pipes, tubes, rods), or along a spline through the points with `smooth=True` |
| `add_swept_profile(profile_mm, path_mm, bend_radius_mm, name, corner_radii_mm)` | Sweep any closed cross-section along a 2D path (rails, gaskets, trim, channels); `corner_radii_mm` rounds the cross-section |
| `add_lofted_solid(profiles_mm, heights_mm, name)` | Loft/blend 2+ polygon or round profiles on stacked parallel planes (transitions, adapters, a leg thick at the knee) |
| `loft_sketches(sketches, name)` | Loft through 2+ closed sketches on any planes, in order, so a loft runs in any direction |
| `add_rib(start_mm, end_mm, toward_mm, thickness_mm, z_mm, name)` | Straight rib / gusset in a plane parallel to Front at `z_mm`, grown toward `toward_mm` until it meets the part (L-bracket gussets) |
| `add_extruded_profile(points_mm, depth_mm, name, corner_radii_mm, rotate_deg, about_mm, draft_deg, merge)` | Extrude any closed polygon `[[x,y],…]` (brackets, sections); `corner_radii_mm` rounds its corners with real sketch fillets, each radius a dimension; `rotate_deg` turns it about a pivot; `draft_deg` tapers its walls; `merge=False` keeps a separate body |
| `add_plane(base, offset_mm, angle_deg, about, name)` | A reference plane offset from a plane, or turned about a model axis; its offset or angle a dimension; gives its origin and axes |
| `add_extruded_profile_on_plane(points_mm, plane, depth_mm, reverse, name, corner_radii_mm, draft_deg, merge)` | Extrude a polygon drawn on any plane (3D points on it), merged with the part |
| `list_bodies()` | The part's solid bodies: name, volume, bounding box |
| `combine_bodies(operation, main, tools, name)` | Add, subtract or intersect bodies of the part (`add` / `subtract` / `common`) |
| `split_body(plane, name)` | Split the part into two bodies along a plane |
| `add_extruded_spline(points_mm, depth_mm, name)` | Extrude a smooth closed spline through points (free-form/organic outlines) |
| `add_hole(diameter_mm, x_mm, y_mm, name)` | Cut a circular through-hole at (x, y) through the depth axis |
| `add_counterbore_hole(clearance_diameter_mm, cbore_diameter_mm, cbore_depth_mm, x_mm, y_mm, name)` | Counterbored screw hole (flush cap-head / heat-set insert) on +Z |
| `add_thread(size, x_mm, y_mm, z_mm, length_mm, internal, name)` | Real, printable ISO metric thread (e.g. `M10x1.5`) from a rod's end edge or a hole's mouth, via SolidWorks' Thread feature; the size is checked against the thread profiles. Internal: drill the basic minor diameter first (M10x1.5 → Ø8.376) |
| `add_hole_on_face(diameter_mm, face, x_mm, y_mm, z_mm, depth_mm, name)` | Round hole on ANY planar face at a 3D point, through or blind (side holes, heat-set insert holes); the face through the point is used |
| `add_hole_wizard(kind, size, face, x_mm, y_mm, z_mm, depth_mm, fit, thread, name)` | ISO hole from SolidWorks' Hole Wizard tables: clearance (ISO 273 fits), counterbore, countersink or tapped; `thread="modeled"` cuts a real, printable thread |
| `add_boss_on_face(diameter_mm, face, x_mm, y_mm, z_mm, height_mm, name)` | Round boss (standoff, peg) grown out of ANY planar face |
| `add_extruded_profile_on_face(points_mm, face, depth_mm, name, corner_radii_mm)` | Polygon pad/ledge grown out of ANY planar face (3D points on the face) |
| `add_text_on_face(text, face, x_mm, y_mm, z_mm, height_mm, depth_mm, emboss, font, name)` | Engrave text into ANY planar face, or emboss it: labels, version numbers; the position is two dimensions |
| `cut_profile(points_mm, depth_mm, name, corner_radii_mm, rotate_deg, about_mm)` | Cut a polygon pocket/slot from the +Z face (blind or through), optionally turned about a pivot |
| `cut_profile_on_face(points_mm, face, depth_mm, name, corner_radii_mm)` | Cut a polygon pocket on ANY face (3D points on the face) |
| `cut_profile_through_plane(points_mm, plane, depth_mm, name, corner_radii_mm)` | Cut a polygon drawn on the Front/Top/Right plane or a plane by name, through all both ways or `depth_mm` centred on the plane (wedges, side windows, symmetric recesses); `keep_inside` keeps the profile instead, so two views make a 3D shape |
| `cut_offset_pocket(face, x_mm, y_mm, z_mm, rim_mm, depth_mm, name)` | Pocket a face leaving a rim along its outline (I-beam web, tray, frame); rim and depth are dimensions |
| `cut_slot(length_mm, width_mm, x_mm, y_mm, angle_deg, depth_mm, name)` | Cut a straight slotted hole (obround) on the +Z face at any angle |
| `add_extruded_slot(start_mm, end_mm, width_mm, depth_mm, name)` | Extrude a stadium (rounded tab, lug, link) between two points, the round ends centred on them |
| `add_fillet(radius_mm, edges, name, radii_at_mm, skip_shorter_mm)` | Round edges (`edges`: `all`, axis `x`/`y`/`z`, a face outline `"+z:outline"`, one feature's edges `"feature:Boss"`, or indices `"2,5"`); `radii_at_mm` varies the radius from end to end; a refusal names the edges that do not fit |
| `add_full_round(face, x_mm, y_mm, z_mm, name)` | Round a rib's top off completely between its two closest opposite sides |
| `add_chamfer(distance_mm, edges, name)` | Chamfer edges at 45° (`edges`: `all`, axis, a face outline, a feature's edges, or indices) |
| `add_shell(thickness_mm, open_face)` | Hollow to a wall thickness; open a face (`+z`/…, `#5`), several (`["+z", "#5"]`) or `none` |
| `add_linear_pattern(count, spacing_mm, direction, feature_name)` | Repeat a feature N times along `+x`/`-x`/… |
| `add_circular_pattern(count, center_x_mm, center_y_mm, feature_name)` | Repeat a feature N times around an axis (bolt circle) |
| `add_mirror(plane, offset_mm, features, name)` | Mirror features (copies follow their seeds) or the whole body about the Front/Top/Right plane, or a plane by name, moved `offset_mm`; fails when a copy would land outside the part |
| `set_dimension(dimension_name, value_mm)` | Change a named driving dim (e.g. `D1@BlockExtrude`, or any name a tool returned in `dimensions`), rebuild, remeasure; an angle in degrees |
| `set_equation(equation)` | Add a global equation or variable linking dims (e.g. `"W" = 40`, then `"width@Sketch1" = "W"`), or replace the one that sets the same name; names the features that fail to rebuild |
| `set_equations(equations)` | Add or replace a list of equations with one rebuild |
| `list_equations` / `delete_equation(equation)` | List the equations (value, global, broken) / delete one by name or index |
| `slice_mesh(path, axis, heights_mm, frame)` | Cross-sections of an STL/3MF mesh as polygon loops, ready to use as profiles; needs no SolidWorks |
| `compare_with_mesh(path, axis, heights_mm, frame, offset_mm)` | Compare the part's cross-sections with a reference mesh (area and extent differences) |
| `read_sketch(name)` | A sketch read back in model coordinates: lines, arcs, circles, splines, its dimensions, fully defined or not |
| `add_sketch(plane, start_mm, segments, name)` | Sketch an outline of lines, arcs and splines on any plane, fully defined: tangent where it flows, dimensioned from the origin |
| `extrude_sketch(sketch, depth_mm, reverse, name, up_to)` / `cut_sketch(sketch, depth_mm, reverse, name)` | Build on an existing sketch by name (one a person drew): extrude it blind or up to the next face, or cut it blind or through all |
| `list_dimensions(contains)` | Every dimension in the part, or those whose name or feature holds `contains`: name (for `set_dimension`), feature, value, unit |
| `list_features()` | The part's history in tree order (name, type, suppressed); flags features that fail to rebuild and sketches that are not fully defined |
| `delete_feature(name, with_children, with_equations)` | Undo a step: delete a feature with its sketch; refuses (and names them) while other features depend on it, unless `with_children`; names the equations it breaks, or deletes them with `with_equations` |
| `suppress_feature(name, suppress)` | Take a feature out but keep it and its dimensions (try a variant); `suppress=False` brings it back with its dependents |
| `set_material(name, database, density_kg_m3)` | Assign a material (e.g. `6061 Alloy`) so mass/density are real; one SolidWorks lacks (e.g. `TPU`) comes with its density |
| `rebuild(top_only)` | Force rebuild, report errors |
| `get_mass_properties` | Volume, mass, density, surface area, centre of mass, bounding box |
| `get_bounding_box` | Tight part bounding box (min/max/size, mm) |
| `list_faces(component)` / `list_edges(face, feature, within_mm, min_length_mm)` | Inspect faces (normal/area/centre; a cylinder's axis, radius and centre, also of a component in an assembly) and edges (type/length/ends/axis) by index, narrowed to a face, a feature, a box or a length |
| `check_printability(up, overhang_deg, min_wall_mm)` | For a print direction: overhanging faces (area, worst lean, centre), islands and edge stretches that start in the air, bed contact, height; with `min_wall_mm` the walls thinner than that |
| `export(path, file_format, quality, deviation_mm, angle_deg, per_component)` | STEP/STL/IGES/Parasolid/3MF (silent; verifies file). STL/3MF tessellation: `quality` `coarse`/`fine`, or explicit `deviation_mm`+`angle_deg`; an assembly's STL as one file or one per component |
| `screenshot(path, view, zoom_mm, show_planes, from_dir)` | PNG/JPG/TIF from a standard view (`iso`, `front`, `top`, …) or any direction, zoomed to fit or onto a region; planes and axes left out unless asked for |
| `make_drawing(path)` | 2D drawing as PDF or editable `.slddrw`: front, top, right (first angle) and isometric views on A4 with the model's own dimensions, each once |
| `save_part(path)` / `open_part(path)` | Save to / open a native `.sldprt`; `open_part` also imports STEP, IGES and Parasolid files as a part to build on |
| `close_part(save)` | Close the current part or assembly; without one, SolidWorks' active document if it is saved |
| `list_documents` / `activate_document(title)` | The open documents (path, type, unsaved changes) / make one current again, also one never saved |
### Assembly tools
| Tool | Purpose |
|---|---|
| `new_assembly` | Create a new empty assembly (becomes the current document) |
| `open_assembly(path)` / `save_assembly(path)` | Open / save a native `.sldasm`; `open_assembly` also imports STEP, IGES and Parasolid assemblies, parts as components in place |
| `insert_component(path, x_mm, y_mm, z_mm, fixed)` | Insert a part, or a `.sldasm` as a sub-assembly, with its **origin** at (x, y, z); the first component is fixed by default |
| `list_components(boxes)` | Name, path, fixed, state (resolved / lightweight / suppressed), hidden, position, rotation and bounding box of every component (its own extent, also when turned), and the mates with their dimensions and errors; `boxes=False` skips the boxes, the slow part in a large assembly |
| `delete_component(component)` | Remove a component from the assembly, with its mates |
| `replace_component(name, path, reattach_mates)` | Put another file in a component's place, keeping its position and, where they find their faces, its mates |
| `set_component_transform(name, x_mm, y_mm, z_mm, rx_deg, ry_deg, rz_deg)` | Move/rotate a component; the transform is read back and verified |
| `add_mate(comp_a, face_a, comp_b, face_b, mate_type, distance_mm, angle_deg, flip)` | Mate two faces (by direction, or `#index` from `list_faces`): `coincident`, `distance`, `parallel`, `perpendicular`, `angle`, or `concentric` between cylinders — measured back afterwards; a refused mate is removed. A distance or angle mate returns its dimension: a joint angle as one number |
| `check_motion(dimension_name, values, distances)` | Step a joint through its range: overlapping pairs and chosen distances per step, the smallest distance and where it occurs, the components that moved |
| `swept_region(component, dimension, values, heights_mm, axis, margin_mm, tolerance_mm, frame)` | What a component covers in a plane over a joint's range: its outline, with a margin, in the coordinates of the part to cut from |
| `delete_mate(name)` / `suppress_mate(name, suppress)` | Delete a mate, or suppress it (and bring it back) |
| `check_interference(components)` | Component pairs whose solids overlap, with the volume in mm³ (touching faces don't count); `components` checks only those among themselves, much faster in a large assembly |
| `measure_distance(component_a, component_b, point_mm, axis_mm)` | Smallest distance between two components, to a point (with the nearest point, and whether the point is in the material), or to an axis |
| `get_assembly_bounding_box` | Tight bounding box of the whole assembly (min/max/size, mm) |
`export` and `screenshot` work on assemblies too. Measuring tools resolve a
lightweight component before they measure it.
### Session tools
| Tool | Purpose |
|---|---|
| `batch(steps, stop_on_error, detail)` | Run several tools in one call, in order: `[{"tool": "open_part", "args": {...}}, ...]`. Stops at the first failed step (that step is rolled back, earlier ones stay) and lists the documents still open; intermediate results shortened to volume and bounding box |
| `run_python(code)` | Run Python on the server's own SolidWorks connection, for work no tool covers (a large assembly's mates and errors, components inside sub-assemblies, custom checks). `sw`, `model`, `mod`, `wrap` are predefined. Variables persist between calls. COM runs with CommandInProgress set, about 25x faster than a separate script. Returns the last expression's value and what was printed |
| `list_dialogs` | The dialogs SolidWorks shows: title, text, buttons, and whether one is modal and holds every call. Works while a call is on hold |
| `answer_dialog(button, hwnd, wait_s)` | Press a dialog's button by its caption, then return the result of the call it held |
A modal dialog in SolidWorks blocks every API call until someone answers it: a
rebuild prompt, a missing-reference question, a message box. The server watches
SolidWorks' windows while a call runs. A call held this way fails within about
2 s, naming the dialog and its buttons, instead of waiting out the 120 s timeout.
Calls made meanwhile are refused at once, so they do not queue up behind it.
Faces are selected by direction in the component's **own** frame (`+x`, `-z`, …),
so a selector keeps meaning the same face however the component is turned. Add
`:inner` (e.g. `+y:inner`) for the cavity side of a hollow part — the inside of a
room wall instead of its outer skin.
All linear dimensions are **millimetres**; the server converts to/from the
SolidWorks-internal metre/radian units at the boundary.
## Architecture
```
src/solidworks_mcp/
binding.py early-binding plumbing (wrap raw dispatches in generated classes)
com_worker.py one dedicated STA thread; all COM calls serialised through it
session.py SolidWorks operations (must run on the COM thread)
server.py FastMCP tools that delegate to session via the worker
constants.py enum values read from the installed typelib (verified)
units.py mm<->m, deg<->rad
errors.py SolidWorksError -> agent-facing {ok:false,error}
```
Two non-obvious design decisions, both load-bearing:
1. **Early binding is mandatory.** On this build `GetActiveObject` returns a
dispatch whose `GetTypeInfo()` fails, so `EnsureDispatch`/`CastTo` cannot infer
types and pure late binding breaks (`IModelDoc2.FirstFeature` →
`DISP_E_MEMBERNOTFOUND`). We generate makepy wrappers from the installed
typelib and wrap each raw dispatch in the right interface class; calls then go
by dispid via `InvokeTypes`, bypassing name resolution. See `binding.py`.
2. **A dedicated COM thread.** COM is STA and thread-affine. The MCP server runs
on asyncio, so all COM work is pinned to one worker thread (`com_worker.py`)
that handlers post to and await — actively enforcing the "one COM session,
single-threaded" rule that does not hold automatically in an async server.
## Status and roadmap
Proven end-to-end against **SOLIDWORKS 2026 (3DEXPERIENCE R2026x)**:
| Milestone | What it proves | State |
|---|---|---|
| M0 | COM connection to a running SolidWorks | ✅ |
| M1 | new part → sketch rectangle → extrude → mass properties (volume matches hand calc) | ✅ |
| M2 | change a named dimension → rebuild → volume changes predictably | ✅ |
| M3 | full agent loop via the MCP server: build → measure → correct → export STEP/STL + screenshot | ✅ |
| M4 | revolve, sweep, loft, profiles, holes/pockets/counterbores, slots, fillet/chamfer, shell, patterns, equations, materials, save/open | 🚧 ongoing |
| M5 | end-to-end 3D-print part: build a functional mounting bracket through the full loop → verify every dimension → export a fine STL ([scripts/m5_demo_bracket.py](scripts/m5_demo_bracket.py)) | ✅ |
| M6 | assemblies: insert and position components, mate them, check interference — every placement and mate measured back ([tests/test_assembly.py](tests/test_assembly.py)) | ✅ |
See [Docs/PROGRESS.md](Docs/PROGRESS.md) for the detailed log and roadmap.
Feedback and contributions are welcome.
## Known limitations
- Geometry so far: **boxes**, **cylinders/cones** (revolve), **arbitrary
extruded profiles**, **holes**, **polygon pockets/slots** (`cut_profile`),
**fillets**, **chamfers**, **shells**, **linear + circular patterns** (bolt
circles); plus **equations**, **materials**, geometry **inspection**, and
**save/open** of `.sldprt`, **holes + pockets on any planar face**
(model→sketch transform), **round flanges** (disc + bore + bolt circle), and
**slotted holes** (`cut_slot`, obround at any angle — the first arc-based sketch),
**general revolves** (`add_revolved_profile`: any `(r,z)` profile → shafts,
vases, rings), **swept pipes/tubes** (`add_swept_pipe`: a round profile along
a rounded 2D path), and **lofts** (`add_lofted_solid`: blend stacked polygon
profiles → transitions/adapters), **free-form extrusions**
(`add_extruded_spline`: a smooth closed spline → organic/aesthetic outlines), and
**non-circular sweeps** (`add_swept_profile`: any cross-section along a path →
rails, gaskets, trim), and **mirrors** (`add_mirror`: features or the whole
body about a plane through the part).
- Selection: plane walk, face-by-normal/direction (`_planar_face_by_normal`,
`+z`/…, with `:inner` for the cavity side of a hollow part), and edge selection
by axis **or explicit index** (`_select_edges`). `list_faces`/`list_edges` let
an agent inspect geometry before selecting.
- Assemblies (M6): components, transforms, mates and interference detection.
Component patterns, in-context features, configurations, drawings and
Simulation (FEA) are out of scope.
## Trademarks
SOLIDWORKS is a registered trademark of Dassault Systèmes SolidWorks Corporation.
This project is an independent, unofficial tool and is not affiliated with,
endorsed by or sponsored by Dassault Systèmes.
TDQS
Scored across 93 tools
The 93 tools include many closely related families (add_extruded_profile / _on_plane / _on_face, four hole tools, multiple cylinder/disc/revolve tools), so an agent must read descriptions carefully to choose correctly. The descriptions do explain the distinctions, but the overlap is substantial enough to create real misselection risk.
Nearly all tools use snake_case with a leading verb (add_, list_, get_, cut_, delete_, set_), and there is no camelCase or chaotic mixing. A few names are noun-like or abbreviated (batch, screenshot, swept_region, rebuild), but the pattern remains readable and predictable.
93 tools is far beyond the practical 3-15 range and beyond the 50+ extreme-mismatch threshold; even for a broad CAD domain, many specialized variants could be consolidated behind parameters. The size creates a heavy selection burden for an agent and increases the chance of choosing the wrong modelling primitive.
The surface covers the full part/assembly lifecycle, extensive feature modelling, inspection, export, drawings, equations, dialogs, and a run_python escape hatch. Gaps are relatively minor (e.g., mesh import beyond slicing, deeper drawing annotation editing, sheet metal/weldments), so core SolidWorks workflows are well supported.