Metadata-Version: 2.4
Name: caid-mcp
Version: 0.7.0
Summary: MCP server giving AI agents validated 3D modeling via CAiD + OCCT
Author: Adam Steen
Author-email: "Claude (Anthropic)" <noreply@anthropic.com>
License-Expression: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: caid[parametric]<0.3,>=0.2
Requires-Dist: mcp<2,>=1.25
Requires-Dist: pydantic>=2.7
Requires-Dist: Pillow>=10.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Dynamic: license-file

# CAiD MCP Server

<!-- mcp-name: io.github.dreliq9/caid-mcp -->

**Headless semantic CAD for AI agents.** CAiD MCP is the primary control surface for [CAiD](https://github.com/dreliq9/CAiD), a persistent parametric CAD engine built directly on OpenCASCADE/OCP.

The goal is not merely to let an LLM call geometry functions. The goal is to let an AI **work on an engineering model over time**: build it, inspect it, revise it, solve it, verify it, and save it without reconstructing the design from scratch.

```text
AI agent
   ↓ MCP
caid-mcp                  ← primary product interface
   ↓
CAiD semantic documents   ← design source of truth
   ↓
OCCT + replaceable solvers
```

No GUI is required. The CAD application is the semantic document + control plane.

## Example: build a bracket, then revise the design

Ask an agent:

> Design a 120 × 60 × 4 mm mounting bracket with four M6 medium-clearance mounting holes, a raised electronics pad, and 3 mm edge fillets. Keep the width and mounting-hole spacing parametric. Then revise it to 150 mm wide and move the mounting holes outward while preserving the pad and edge treatments.

The result is not just a second generated part. The AI edits the same semantic model.
The block below is the target evidence shape for a native run; it is illustrative until
the corresponding transcript and visual artifacts are captured:

```text
Width:        120 → 150 mm
HoleSpacing:  100 → 130 mm
mounting-hole feature IDs: unchanged
pad datum/sketch IDs:       unchanged
persistent references:      resolved
rebuild:                    PASS
save/reopen fingerprint:    exact
```

That is the core use case: **AI operating persistent CAD, not repeatedly generating anonymous geometry.**

**[See the full engineering examples →](examples/AI_NATIVE_SHOWCASE.md)**

---

## Engineering examples

The main examples are recognizable design jobs. The AI-native semantics show up as the reason those jobs survive revision and automation.

### Parametric mounting bracket

**Build → revise → rebuild.** Parameters drive overall size, hole spacing, pad geometry, standard holes, and downstream edge treatments.

### Electronics enclosure

**Fit around a changing PCB.** Shells, cutouts, standoffs, datums, and persistent references update when board dimensions change.

### Hinged sensor mount

**Parts → mates → solve → interference.** A hierarchical assembly uses local/world transforms, revolute joints, preserve-world re-parenting, and solver verification.

### Manufacturing-ready motor adapter plate

**Geometry with manufacturing intent.** M8 ISO-clearance holes, M6×1 tapped holes, countersinks, bolt-circle parameters, and preserved callout metadata.

### Checked AI revision

**Inspect → plan → apply → verify.** A design change can be fingerprint-bound, checkpointed, previewed, protected by invariants, and rejected if the source becomes stale.

The advanced examples also include a closed-loop four-bar linkage that explicitly escalates from the deterministic tree solver to Ondsel rather than inventing a traversal-order result.

The older [geometry gallery](examples/GALLERY.md) remains available for Raspberry Pi cases, stands, fasteners, cable clips, and other quick modeling demonstrations.

---

## Why this works for AI

| Remember | Refuse to guess | Change safely |
|---|---|---|
| Stable feature/reference IDs survive parametric revisions. | Deleted, split, or ambiguous design topology fails closed. | Consequential changes can be fingerprinted, checkpointed, planned, verified, and rejected when stale. |

A generic geometry API can select the current highest face. CAiD can preserve the identity of the design face an earlier operation meant. If that design entity is later destroyed, CAiD reports the loss instead of silently rebinding to something that merely looks similar.

---

## Two operating modes

### 1. Semantic document mode — primary

This is the durable engineering workflow. Agents open explicit document handles and operate on stable semantic state:

```text
create/open .caid.json
       ↓
     doc-…
       ↓
parameters + expressions
       ↓
feature graph + stable UUIDs
       ↓
datums / sketches / solids
       ↓
persistent GeometryRefs
       ↓
structured rebuild diagnostics
       ↓
verified save/reopen
```

The semantic control plane includes document sessions, parameters, feature graph
inspection, rebuilds, suppression, persistent references, datums, rectangle
sketches, extrude/cut-extrude/revolve, holes, edge finishes, shell, draft,
mirror, polyline and exact-helix paths, sweep/loft, hierarchical assemblies, and
Base/Edge Flange sheet metal. Runtime capability discovery explicitly separates
installed CAiD engine features from registered MCP workflows. New CAiD engine
features are expected to ship with companion MCP workflows before they are
considered product-ready.

### 2. Scratch scene mode — secondary

The original scene/object tools remain useful for quick geometry, concept generation, rendering, imports/exports, and one-off operations:

```text
create_box → boolean_cut → fillet → preview → export_step
```

Scratch mode is intentionally not the source of truth for serious parametric engineering work.

---

## Setup

### Prerequisites

- Python 3.12+

For an installed stdio server:

```bash
python -m venv .venv
source .venv/bin/activate   # macOS/Linux
# .venv\Scripts\activate  # Windows

pip install caid-mcp
caid-mcp
```

That installation includes CAiD and its PlaneGCS parametric extra. For source
development:

```bash
git clone https://github.com/dreliq9/caid-mcp.git
cd caid-mcp
pip install -e ".[dev]"
pytest -q
python server.py
```

The installed `caid-mcp` command, `python -m caid_mcp`, and the compatible
cloned-repository `python server.py` path all run the same stdio server.

### Connect to Claude Code

```bash
claude mcp add-json caid '{"type":"stdio","command":"/FULL/PATH/TO/.venv/bin/caid-mcp","args":[]}' --scope user
```

For a source checkout, the earlier Python-plus-`server.py` command remains
compatible. Configure either stdio command in any MCP-compatible client.

Verify:

```bash
claude mcp list
```

---

## Semantic workflow example

A typical durable modeling session looks like this conceptually:

```text
semantic_caid_capabilities()
create_caid_document("Bracket")
add_caid_parameter(doc, "Width", 120)
add_caid_parameter(doc, "Height", 60)
add_caid_parameter(doc, "Thickness", 4)
add_caid_rectangle_sketch(doc, "Profile", "Width", "Height")
add_caid_extrude_feature(doc, "Body", "Profile", "Thickness")
materialize_caid_reference(doc, "Body", role="face:+Z")
rebuild_caid_document(doc)
save_caid_document(doc, "bracket.caid.json")
```

The capability handshake preserves `feature_kinds` and
`optional_capabilities` as the installed-engine view, and adds the callable
surface explicitly:

- `mcp_semantic_document`: whether the core durable document workflow is
  registered;
- `mcp_feature_tools`: semantic feature kinds mapped to their currently
  registered tool names;
- `engine_only_feature_kinds`: installed feature kinds with no durable semantic
  constructor;
- `mcp_optional_capabilities`: optional engine capabilities that are callable
  through the current registry;
- `engine_only_capabilities`: installed optional capabilities with no MCP
  workflow;
- `registered_tool_count`: the live FastMCP registry size.

Use these fields instead of inferring callability from an installed Python class.

Later, the agent can reopen the same semantic document, modify driving parameters, inspect affected features/references, rebuild, verify, and save without reconstructing the model from a prompt.

---

## Structured outputs

Serious agent workflows should not depend on parsing prose. Semantic tools return structured identities and diagnostics such as:

```text
handle
document_id
feature_id
reference_id
fingerprint_before
fingerprint_after
status
revision
metadata
diagnostics
warnings
```

The older primitives/query surface also uses Pydantic result models where available, so clients receive both readable text and structured content.

---

## Safety model

CAiD MCP is designed around several rules that are particularly important for autonomous engineering:

- **Stable IDs over names or topology indices.** Names are for humans; UUIDs carry identity.
- **Persistent semantic references over geometric reselection.** A transient face index is never promoted to durable identity by accident.
- **Fail closed on deletion/split/ambiguity.** Do not silently produce plausible wrong geometry.
- **Bounded inspection.** Large-model queries report `visited`, `matched`, `returned`, and `truncated` rather than flooding agent context.
- **Verified persistence.** Semantic saves reopen/rebuild and compare fingerprints before being accepted.
- **Checked consequential mutation.** Plans/checkpoints/postflight protection are the intended path for autonomous high-impact edits.
- **Replaceable solver boundaries.** CAiD semantics do not serialize PlaneGCS/Ondsel runtime identities.

---

## Scratch geometry surface

For rapid modeling, CAiD MCP still includes a broad scene-oriented toolbox covering:

- primitives and arbitrary CAiD/OCP scripting;
- booleans, transforms, fillets, chamfers, shells;
- curves/sweeps and compound geometry;
- geometry queries and measurement;
- section/exploded views and rendering;
- STEP/BREP/STL import/export;
- healing and simplification;
- part libraries and scene organization.

Use scratch mode when persistence and design intent are unimportant. Promote work into semantic documents when the model must survive revision.

---

## Output files

Scratch exports go to `~/cadquery-output/` by default for backward compatibility. Override with:

```bash
export CAID_OUTPUT_DIR=/your/path
```

Semantic `.caid.json` documents are saved to the path selected by the document workflow.

---

## Architecture

```text
MCP client / AI agent
        │
        ▼
caid-mcp
        ├── semantic document sessions
        ├── semantic feature workflows
        ├── persistent inspection/references
        ├── checked mutation / recovery
        ├── semantic assembly workflows
        └── scratch scene tools
                │
                ▼
              CAiD
        ├── CaidDocument
        ├── AssemblyDocument
        ├── feature/reference semantics
        └── solver protocols
                │
                ▼
       OCP / OpenCASCADE
       PlaneGCS / Ondsel / future solvers
```

CAiD owns CAD semantics. caid-mcp owns the AI interaction/control policy. OCCT and numerical solvers remain replaceable engines.

---

## Development rule

A major CAiD feature may become **engine-ready** before its agent interface is finished, but it is not considered **product-ready** until the companion MCP workflow is implemented and integration-tested.

That prevents the engine and its primary headless interface from drifting apart.

---

## Security

`run_cadquery_script` is retained as a compatibility escape hatch and executes arbitrary Python in a subprocess. Use it only with trusted local clients unless/until that escape hatch is sandboxed.

The semantic tool surface should be preferred whenever a first-class operation exists because its mutation/identity/validation behavior is explicit and testable.

---

## Development

```bash
pip install -e ".[dev]"
pytest -q
```

CAiD engine development and native solver validation live in the [CAiD repository](https://github.com/dreliq9/CAiD).

## Acknowledgments

CAiD MCP was co-developed by Adam Steen and AI coding/reasoning systems used throughout the project's development and validation workflow.

## License

MIT — see [LICENSE](LICENSE).
