Skip to main content
Glama
cadmcp

cadmcp

by Farx1
README.md
# cad-agent-mcp

A local LLM agent that designs mechanical parts by driving a real CAD kernel
(OpenCascade, through CadQuery) via a typed **MCP** tool server. It ships with an
evaluation harness on 30 tasks and an **independent C++ geometry verifier**.

The LLM never writes or runs code. It can only call 10 typed, validated CAD tools,
and every result is checked by a second implementation.

![part built by the agent](docs/agent_m06.png)

*Built by `qwen2.5:7b` from "Block 80 x 40 x 30 mm with vertical edges filleted at 4 mm and a
12 mm through hole in the centre of the top face" in 3 tool calls (`box`, `fillet`, `hole`).
The part passed every check. Run `20261126-204954-cb7309`, task `m06`, seed 1.*

## Results

30 tasks, 3 seeds, 4 configurations: 360 runs. Measured on an RTX 3070 Laptop (8 GB)
with Ollama. Success means every check passes (see the table below). The values are
the mean ± standard deviation of the success rate per seed.

| Configuration | All | Easy | Medium | Hard | Δ vs baseline |
|---|---|---|---|---|---|
| `qwen2.5:7b` (baseline) | **35.6 ± 1.9 %** | 76.7 ± 5.8 % | 16.7 ± 5.8 % | 13.3 ± 5.8 % | |
| `qwen2.5:7b` + memory | 26.7 ± 6.7 % | 56.7 ± 15.3 % | 13.3 ± 5.8 % | 10.0 ± 0.0 % | −8.9 pts |
| `qwen2.5:7b`, no retry | 34.4 ± 3.8 % | 76.7 ± 5.8 % | 16.7 ± 5.8 % | 10.0 ± 0.0 % | −1.1 pts |
| `ministral-3` | 11.1 ± 3.8 % | 26.7 ± 11.5 % | 0.0 ± 0.0 % | 6.7 ± 11.5 % | −24.4 pts |

What the numbers say:

- **A 7B local model handles simple parts, not assemblies.** It reaches 76.7 % on easy
  tasks, but 16.7 % on medium and 13.3 % on hard ones. The first failing checks over the
  90 baseline runs are: two bodies left un-merged (18), wrong overall dimensions (12),
  wrong volume (13), holes misplaced or mis-sized (7), nothing built (8). Spatial
  reasoning is the bottleneck, not the tool protocol.
- **Retries do not pay off at this model size.** Feeding errors back changes the success
  rate by +1.1 points, which is within one standard deviation. It costs 3.6 LLM calls per
  run instead of 1.9, and 6,593 prompt tokens instead of 2,833.
- **Naive memory hurts, and the traces show why.** With two retrieved examples injected as
  text (`box({...})`), 15 of 89 runs end without a single tool call, against 2 of 90
  without memory. The model imitates the text format of the examples, and it reuses
  their body names (10 `no body named 'b1'` errors). This is a negative result, kept as
  measured.
- **The independent verifier agrees with the kernel.** On the 311 STL files exported by the
  agent, the C++ volume differs from the CadQuery volume by at most 4.55e-4 (median
  8.8e-6). 303 of the 311 meshes (97.4 %) are watertight.
- **Latency.** LLM call p50 1.22 s, p95 3.55 s. A whole agent run takes p50 9.8 s and
  p95 21.5 s, including the MCP server start-up.

Full report, generated by `eval/report.py` and never edited by hand:
[`results/REPORT.md`](results/REPORT.md).

### How the evaluation itself was debugged

The published numbers come from the third full run. The two earlier runs are kept,
each with its report, because what changed between them is part of the work.

| Run | Change | Baseline success | Crashed runs |
|---|---|---|---|
| v0 (discarded) | Hole positions not checked, ambiguous prompts, memory leak between near-duplicate tasks | not published | n/a |
| [v1](results/REPORT_v1.md) | Corrected checks, prompts and memory exclusion | 28.9 ± 19.2 % | 38 (32 for `ministral-3`) |
| [v2](results/REPORT_v2.md) | Agent loop: an unparsable tool call is fed back to the model instead of crashing; a prose-only answer gets one reminder | 28.9 ± 19.2 % | 7 (all Ollama timeouts) |
| v3 (above) | One sampling seed per (task, seed) instead of the same seed for every task | 35.6 ± 1.9 % | 1 (Ollama timeout) |

In v1 and v2, seed 1 gave 2 successes out of 30, against 12 for seeds 0 and 2. Every task
used the same sampling seed, so all 30 tasks drew from one random stream and their
failures were correlated. With one seed per (task, seed), the per-seed successes are
10, 11 and 11. The agent code is the same in v2 and v3: the 6.7-point difference comes
from the measurement, not from a better agent.

## Architecture

```mermaid
flowchart LR
  U[User request] --> R[agent/runner.py<br/>agent loop]
  R <-->|chat + tool schemas| L[Local LLM<br/>Ollama]
  R <-->|MCP stdio| S[cadmcp/server.py<br/>MCP server]
  S --> V[Pydantic validation<br/>bounds, units, threads]
  V --> K[CadQuery / OCC kernel]
  K --> T[Feature tree<br/>SQLite, undo = replay]
  R --> TR[traces/*.jsonl<br/>one span per call]
  R --> M[agent/memory.py<br/>nomic-embed-text]
  K --> X[STEP / STL / PNG]
  X --> G[geomcheck C++<br/>volume, watertight]
  X --> E[eval/checks.py<br/>vs reference part]
```

| Component | What it does |
|---|---|
| `cadmcp/` | MCP server (stdio and streamable HTTP). 10 CAD tools plus `new_part` and `export`. Each tool returns `{"ok", "error", "state"}`, where `state` is the measured part: volume, bounding box, cylindrical faces, validity. |
| `agent/runner.py` | Agent loop: Ollama chat with tool calling, MCP client, max steps, tool timeouts, bounded retries, loop detection. |
| `agent/memory.py` | Long-term memory: successful parts embedded with `nomic-embed-text`. The 2 nearest are injected as worked examples, and the task being solved is excluded. |
| `agent/tracing.py` | JSON Lines traces: run id, step, LLM or tool, arguments, latency, tokens, error. |
| `geomcheck/` | C++17 + pybind11. Reads the STL, computes signed volume, area and bbox, checks watertightness (vertex welding plus edge manifold test) and a sampled Hausdorff distance. Built with CMake (MSVC on Windows, g++ in CI). |
| `eval/` | 30 tasks (10 easy, 10 medium, 10 hard, 6 of them multi-turn edits), automatic checks, runner over seeds and configurations, report generator. |
| `api/app.py` | FastAPI `POST /design` returns the part, the C++ verification and the trace. |

## Design decisions

**No generated code is executed.** Most text-to-CAD agents let the LLM write
CadQuery or OpenSCAD code and run it. Here the model only fills the arguments of
typed tools. Pydantic enforces 0.1 to 2000 mm bounds and rejects unknown fields. The
server chooses every file path. The attack surface is a set of numbers and enums,
not a Python interpreter. Errors come back as actionable messages, for example
`hole d=6.6 at (500, 30) is outside the part footprint x=[0, 100], y=[0, 60]`.

**The feature tree is the source of truth.** Geometry is rebuilt by replaying the
list of operations. `undo` drops the last one and replays, and persistence stores
the list in SQLite. A rejected operation never touches the tree: the new geometry
is computed on the side and kept only if it is a valid, non-empty solid.

**Tool design is measured, not guessed.** The first agent runs exposed two problems.
A single `hole_pattern(kind=grid|circle)` tool made `qwen2.5:7b` fail 3 calls in a
row, so it became `hole_grid` and `hole_circle`. The model also wrote
`diameter="M6"`, and the MCP layer rejected it with a generic parse error, so the
model fell back to a 6 mm hole instead of the 6.6 mm clearance hole. The server now
lets that value reach the validator, which answers `pass thread='M6'`.

**Checks are strict, because volume is not enough.** A plate with four 6 mm
holes in the wrong places is within 1 % of the reference volume. Success requires
every check below. The first failing check is the failure category.

| Check | Rule |
|---|---|
| single body, valid solid | OCC validity |
| bbox | size within 0.1 mm |
| volume | within 1 % |
| holes | same cylindrical faces (holes, fillets, bosses): radius within 0.05 mm, parallel axis, axis within 0.1 mm |
| shape | symmetric-difference volume < 1 % of the reference, after aligning bbox corners |
| watertight | STL closed (C++, independent of CadQuery) |
| cross-check | C++ volume of the STL vs CadQuery volume, relative error < 1e-3 |

Success is judged on the final geometry only, whatever the stop reason.

The checker itself is tested (`tests/test_eval_checks.py`). Every reference passes
its own checks. Seven near-misses fail with the right category, including the exact
mistake the model made in the first run and a single hole moved by 3 mm.

**The evaluation was reviewed before publishing numbers.** A first full run was
discarded and archived after an independent review found four biases:
- hole positions were not checked, so one hole 3 mm off passed;
- several prompts were ambiguous (wall height with or without the base, start angle of bolt circles, distances to hole centres or to hole edges);
- near-duplicate tasks leaked through memory;
- crashed runs were never retried.

All published numbers come from the corrected run.

**Independent verification.** `geomcheck` re-measures the exported mesh in C++
with its own STL parser. It does not share code with the B-rep kernel that produced
the part. On 20 test parts the volume difference with CadQuery stays below 1e-3
(`tests/test_geomcheck.py`).

**Memory without leakage.** The memory bank is filled only by successful baseline
runs. Near-duplicate tasks share a `family` in `eval/tasks.yaml` (for example the
multi-turn `h02` starts with the exact prompt of `e02`). A run never retrieves an
entry of its own family, so the memory ablation measures transfer between
different parts, not recall of the answer.

## Quick start

Requirements: Python 3.11, [Ollama](https://ollama.com) with `qwen2.5:7b` and
`nomic-embed-text`, and CMake plus a C++17 compiler for the verifier.

```bash
python -m venv .venv && .venv/Scripts/activate        # Linux: source .venv/bin/activate
pip install -e ".[dev]"
python scripts/build_geomcheck.py                      # C++ verifier + ctest
pytest -q                                              # no GPU needed: the agent loop is tested with a scripted LLM

python -m agent.runner "Plate 100 x 60 x 5 mm with four M6 clearance holes, each 10 mm from the two nearest edges."
python -m eval.run_eval --seeds 3                      # full evaluation: 360 runs, 1.5 h on an RTX 3070 Laptop
python -m eval.report                                  # results/REPORT.md
```

**Claude Desktop or any MCP client:** see `claude_desktop_config.example.json`.
The server runs with `python -m cadmcp.server` (stdio) or `--http` (streamable HTTP on
`127.0.0.1:8000/mcp`).

**Docker:** `docker compose up --build`, then
`curl -X POST localhost:8080/design -H "Content-Type: application/json" -d '{"prompts": ["A 40 mm cube with a 10 mm through hole"]}'`.
Ollama stays on the host for GPU access.

## Limitations

- Holes are drilled vertically from the top of the bounding box only. Side holes need a direction parameter.
- The "hole outside the part" check uses the bounding box, so a hole biting the edge of a disc is accepted.
- One global MCP session per server process. Multi-user HTTP needs one session per connection.
- Prompts give explicit coordinates conventions (min corner at origin, length along X). Rotated but otherwise correct parts fail the shape check.
- 30 tasks and 3 seeds measure trends, not small differences: a 1-point gap (retry ablation) is noise. See the standard deviations.
- GPU inference is not bit-exact: replaying one run with the same seed can give a different answer. The statistics are over runs, not replays.
- `sampled_distance` in `geomcheck` is brute force, O(n x triangles). A BVH is the next step.

## What I would do next

- Inject memory examples as real past tool-call messages instead of text, then measure again: the traces show the text format is what breaks tool calling.
- Clarify `undo` in the tool description: the traces show the model calling `undo` after a *failed* call, which removes the previous *successful* operation.
- Add a "spatial plan" step (the model lists coordinates before calling tools): most failures are wrong positions or un-merged bodies, not protocol errors.
- Run the same harness on larger models (API or bigger local models) to separate model capacity from tool design.
- Add a sketch-and-extrude tool and side holes, then tasks that need them.
- Per-connection sessions, authentication and audit logs on the HTTP transport for multi-user deployment.
- OpenTelemetry export of the JSONL spans.
- Use the C++ verifier as a fast reward signal for fine-tuning or search over tool-call sequences.

## Layout

```
cadmcp/    MCP server, typed tools, feature-tree state, export
agent/     agent loop, memory, tracing
geomcheck/ C++17 verifier + pybind11 bindings + ctest
eval/      tasks.yaml, checks, runner, report
api/       FastAPI service
tests/     pytest (tools, server, agent loop, checks, C++ verifier, API)
```

MIT license.