Metadata-Version: 2.5
Name: loupe-cad
Version: 1.0.1
Summary: Code-CAD & PCB review pipeline and MCP server: deterministic geometry checks, contact sheets, 3D viewer, drafts, and KiCad 10 checks.
Project-URL: Homepage, https://charlesbine.com/projects/loupe/
Project-URL: Repository, https://github.com/charlesbine/loupe
Project-URL: Issues, https://github.com/charlesbine/loupe/issues
Author: Charles Bine
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: 3d-printing,build123d,cad,cadquery,code-cad,drc,hardware,kicad,mcp,pcb,stl
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
Requires-Python: >=3.11
Requires-Dist: mcp<2,>=1.2
Description-Content-Type: text/markdown

<!-- mcp-name: io.github.charlesbine/loupe -->

<div align="center">

# loupe

**A code-CAD review pipeline for 3D printing and PCBs. Render it, prove it, preview it, slice it, or fab it.**

[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![uv PEP 723](https://img.shields.io/badge/uv-PEP%20723%20zero--setup-DE5FE9)](https://docs.astral.sh/uv/)
[![build123d & KiCad 10](https://img.shields.io/badge/CAD-build123d%20%7C%20KiCad%2010-2E7D32)](#the-pcb-pipeline)
[![MCP Server](https://img.shields.io/badge/MCP-7%20agent%20tools-111827)](#for-agents)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)

**[Live Interactive 3D Viewer & Showcase ↗](https://charlesbine.com/projects/loupe/)**

</div>

![Four-tile contact sheet of the 5-part Desk Sensor Pod: isometric view, 3D cutaway at Y=28mm, longitudinal cross-section slice showing the lip-and-groove seam, OLED risers, RF shield can, and fluted rotary knob over the encoder shaft, plus a horizontal slice at Z=11mm showing M2.5 standoffs, side louvres, and rear USB-C alignment.](docs/img/hero-slices.png)

Single-file [`uv`](https://docs.astral.sh/uv/) scripts — zero setup, inline dependencies — that turn a parametric model into something you (or an LLM agent) can actually *trust* before committing filament (or a fab order) to it:

```
draft (a YAML dimension record — written before any CAD exists)
   → draftcheck.py assert the plan — FAILS LOUDLY on a wall under minimum, a hole off the part,
                   a fit outside its class, an expression that won't resolve; and, given the
                   exported STL, on a model that has drifted from what was drafted
   → draftsheet.py a dimensioned drawing + the dim table, with every number's provenance
   → draft.py      --params: the CAD script imports the numbers instead of retyping them

CAD script (build123d / CadQuery)
   → check.py    assert geometry facts — FAILS LOUDLY if a part floats, collides, or has a thin wall
   → sheet.py    a labeled contact sheet: 8 named views + slices + interference painted red
   → viewer.py   a self-contained browser viewer: orbit, clip planes, explode, mm grid
   → slice.py    headless Bambu Studio: errors, print time, filament grams, cost — then print

board script (import pcb — parts + nets + routes, in Python)
   → pcbcheck.py  headless KiCad DRC — FAILS LOUDLY on violations, unrouted nets, netless pads
   → pcbsheet.py  one contact sheet: raytraced 3D top/bottom/iso + true copper/silk layer plots
   → pcbfab.py    gerber/drill zip, JLCPCB BOM + CPL, STEP — and an STL that feeds the row above
```

A loupe is the glass a jeweler holds to a gem, a printer to a proof sheet — the tool for catching the flaw under magnification before it costs you. These scripts are that glass for parametric CAD: they put the part under scrutiny before the printer ever does.

---

## Electronics project workflow

The shared tools also support a versioned local `loupe.json` project workflow:

```sh
uv run loupe.py --project /path/to/device doctor
uv run loupe.py --project /path/to/device build
uv run loupe.py --project /path/to/device check
uv run loupe.py --project /path/to/device review
uv run loupe.py --project /path/to/device release --target jlcpcb
```

Passing evidence is bound to input/output hashes and tool versions. Release rejects
stale or missing evidence and produces local review bundles with checksums.
Ordinary project builds preserve the reviewed native PCB and schematic.
See [the workflow contract, limits and tests](docs/workflow.md).


## Why this exists

The reliable way to do CAD with code in 2026 isn't GUI-automation-over-a-protocol, and it isn't text-to-CAD. It's three things working together:

1. **Code-CAD** — parametric Python (build123d / CadQuery, both on the OpenCascade kernel). The model is a program: diffable, versionable, reproducible.
2. **Deterministic geometric verification** — machine-checkable assertions a render can *never* guarantee (does part A actually collide with part B? is any wall under 1.2 mm? is the mesh watertight?). Exits nonzero when a fact is false.
3. **Rendered eyes** — a labeled contact sheet you look at, and a browser viewer a human opines on.

This pipeline was built during a real reverse-engineering job — modeling a part to interoperate with a commercial product. On its first day it caught **four** genuine assembly bugs (a body floating 53 mm off the floor, a 1 mm bore offset masquerading as thread interference, a hardcoded floor constant, a phantom interference from an un-rotated helical part) *before a single render existed*, and the printed test parts fit the commercial reference on the first try.

It's written to be driven by a human at a terminal **or** by an AI coding agent — the contact sheet exists precisely because an agent can `Read` a PNG, and the deterministic checks exist because "looks right" is not a specification.

![Staged collision on the 5-part Desk Sensor Pod: identical on the exterior isometric view, while a forgotten internal bezel rib crashes through the OLED module and RF shield can, painted bright red with 95.9 mm² and 56.0 mm² measured interference.](docs/img/interference.png)

*A staged internal collision: identical from the outside, while a forgotten bezel rib crashes straight through the OLED display and RF shield can inside. `sheet.py` paints the overlap red and prints the measured area into the caption; `check.py` turns the same fact into a nonzero exit code. This is the thing a pretty render can never tell you.*

---

## Requirements

- **[uv](https://docs.astral.sh/uv/)** — that's it for the first three tools. Each script declares its own dependencies inline ([PEP 723](https://peps.python.org/pep-0723/)); `uv run` resolves them into a throwaway environment on first invocation. No `pip install`, no virtualenv to manage.
- **Python ≥ 3.11** (uv will fetch one if you don't have it).
- **`slice.py` only:** a local **Bambu Studio** install. Paths default to macOS (`/Applications/BambuStudio.app`); adjust the two constants at the top for Linux/Windows. The other three tools are cross-platform.

```sh
git clone https://github.com/charlesbine/loupe.git
cd loupe
uv run check.py your_part.stl        # first run resolves deps; subsequent runs are instant
uv run examples/sensor_pod.py        # regenerate the 5-part Desk Sensor Pod used in the shots above
```

---

## The tools

### `draft.py` / `draftcheck.py` / `draftsheet.py` — the planning stage

`check.py` proves the model you built. It cannot tell you that you built the *wrong* model: a wall that's 1.8 mm when you meant 2.4 mm is watertight, collision-free, and wrong. A **draft** is the record that makes that a failing assertion — a YAML file of named dimensions, each with a tolerance and a note saying where the number came from, plus simple 2D profiles that reference them.

![Dimensioned engineering draft sheet of a coupon case showing top and side orthographic drawings with tolerance callouts alongside a full dimension provenance table.](docs/img/draft-sheet.png)

```yaml
dims:
  board_w:   {v: 20,  from: "examples/blinky_coupon.py: Board(w=20)"}
  wall:      {v: 2.0, from: "5 perimeters @ 0.4 nozzle"}
  fit_clear: {v: 0.3, tol: 0.05, from: "slip fit, FDM rule of thumb 0.2-0.3/side"}
  inset:  "wall + fit_clear"                       # derived — expressions over other dims
  case_w: {expr: "board_w + 2*inset", tol: 0.2, from: "FDM process ±0.2 typical"}
```

```sh
uv run draftcheck.py examples/coupon_case.draft.yaml            # the gate
uv run draftsheet.py examples/coupon_case.draft.yaml -o case.png  # the eyes — then Read it
uv run draft.py examples/coupon_case.draft.yaml --params dims.json
uv run draftcheck.py examples/coupon_case.draft.yaml --stl asm_case.stl   # did the model drift?
```

The gate is cheap because nothing is a mesh yet: containment and wall thickness are exact 2D polygon distances. It catches a hole 0.2 mm from an edge, a feature off the part, a clearance that isn't the fit class you claimed, and an expression that won't resolve — before a single solid exists. Given the exported STL it runs the other way too, asserting the bounding box and every drafted hole's diameter and position against what was recorded.

Because the CAD script imports the draft (`from draft import load`, or a `--params` export), the drawing and the model cannot disagree. Change a dimension in the YAML without rebuilding and the gate says so:

```
FAIL  asbuilt[asm_case].bbox: built 24.600×19.600×7.300, drafted 25.800×20.800×7.300, worst Δ1.200 (tol 0.25)
FAIL  asbuilt[asm_case].hole[m2]: built ⌀2.400 at (4.800, 14.800), drafted ⌀2.400 at (5.4, 15.4) — off-centre 0.849
```

### `check.py` — deterministic geometry verifier

Machine-checkable facts renders can't guarantee. Reports always; exits nonzero on a failed assertion, so you can wire it straight into a build.

```sh
uv run check.py part.stl                                          # watertightness + report only
uv run check.py asm_body.stl asm_lid.stl --interference-max 0.05  # exact 3D boolean overlap volume, mm³
uv run check.py col.stl bore.stl --clearance "col:bore:0.15@z=2:18"  # min gap, region-scoped
uv run check.py part.stl --min-wall 1.2 --overhang 45 --json      # thin-wall + unsupported-area report
```

- **Interference** = exact manifold boolean volume between every pair of parts, always reported.
- **Clearance** samples part A's surface and measures signed distance to part B (negative = penetration). Scope it with `@z=lo:hi` — parts that legitimately touch elsewhere (a flange resting on a rim) otherwise read 0.
- **Watertightness** is always checked. Wall preflight defaults to a 0.4 mm floor;
  `--min-wall` changes it, and `--no-wall-check` explicitly opts out for reference geometry.
  The checker samples opposing surfaces, reports sustained thin patches, and fails when
  the wall backend is indeterminate. Sharp-edge diagnostics and sampling limits remain
  visible; this does not certify physical printability. `--overhang DEG` reports
  unsupported area (the bed face is excluded).

### `sheet.py` — labeled contact sheet (the reviewer's eyes)

Renders one or more meshes into a single PNG: 8 named orthographic/iso views + custom camera angles, 2D cross-section slices with **automatic part-vs-part interference detection** (overlap painted red, mm² in the caption), 3D cutaways, and region zoom. Every tile is captioned with its camera position and screen axes — trust the captions, not your assumptions.

![A contact sheet of a multi-compartment insert: two isometric views plus front, back, left, right, top and bottom. The per-utensil channels read from the top, the ramped floor from the side, and the comb of channel walls head-on — each tile captioned with camera position and screen axes.](docs/img/contact-sheet.png)

```sh
uv run sheet.py body.stl lid.stl -o sheet.png
uv run sheet.py a.stl b.stl --slice z=50% --slice z=12,15 --slice x=50%
uv run sheet.py a.stl b.stl --cutaway "y>50%" --views iso,front,top
uv run sheet.py a.stl b.stl --view=-25,12 --roi "z=45:62" --slice z=52   # close-up on a region
uv run sheet.py a.stl --views none --slice z=10,20,30                    # slices only
```

- `--view AZ,EL` sets a custom camera. Use the `=` form for **negative** azimuths (`--view=-25,12`) — argparse eats a bare leading dash otherwise.
- `--roi "z=45:62[,x=..]"` zooms *every* tile onto a region, keeping any triangle that overlaps it.
- Surfaces that touch by design flag a few mm² of contact sliver; judge by the reported area — real collisions are 10–100× bigger.
- `--cutaway "z>50%"` (repeatable) removes everything past a plane and re-triangulates the cut faces exactly on it — the internal stack reads clean, no jagged straddling facets.

![A device enclosure shown in isometric and front views plus two 3D cutaways — one cutting in Z, one in Y — each cleanly sectioning the shell to reveal the PCB seated inside.](docs/img/cutaway.png)

### `viewer.py` — self-contained browser viewer (the human's eyes)

One HTML file (GLB embedded as base64, three.js from CDN): orbit controls, an adaptive mm grid with occluded world-space tick labels on all three axes, per-part legend, explode toggle, auto-rotate (remembered in localStorage), and **double-ended clip sliders per axis** with **solid stencil section caps** (so clipped views read as cut solids instead of hollow shells).

![The self-contained browser viewer showing the 5-part Desk Sensor Pod sectioned along Y=28mm with solid stencil section caps on a world-mm grid, exposing the fluted rotary knob, encoder shaft, beveled OLED window, RF shield can, and stepped enclosure seam alongside per-part legend, explode, and clip-plane controls.](docs/img/viewer.png)

```sh
uv run viewer.py body.stl lid.stl -o preview.html --title "My part"
uv run viewer.py case.stl panel.stl pcb.stl glass.stl io.stl \
    --group module=pcb,glass,io -o preview.html   # module stays rigid on explode
open preview.html
```

The grid coordinates match `sheet.py`'s slice coordinates exactly — "clip Z 50:55" in the viewer and `--slice z=52` in the sheet are the same place. `--group NAME=a,b,c` (repeatable) makes those parts explode as one rigid body, so an assembly (PCB + glass + connectors) stays together while the shells fly off.

### `slice.py` — headless Bambu Studio

Wraps the Bambu Studio CLI (P1S profiles by default): slices one arranged plate and reports success/error, predicted print time, filament grams/meters, spool cost, per-object bounding boxes, and slicer warnings. Writes the ready-to-print `.gcode.3mf` next to the inputs.

```sh
uv run slice.py part1.stl part2.stl                         # one plate, P1S defaults
uv run slice.py part.stl --process "0.12mm Fine @BBL X1C" \
    --filament "Bambu PETG Basic @BBL P1S 0.4 nozzle"
uv run slice.py --list-processes | --list-filaments | --list-machines
```

Defaults: P1S, 0.4 nozzle, 0.20 mm Standard, Bambu PLA Basic. Filament weight is computed from the gcode's extruded length × profile density (the CLI leaves `used_g` at 0). **macOS/Bambu-specific** — edit the `APP` and `PROFILES` paths at the top for other platforms.

---

## The PCB pipeline

The same philosophy pointed at circuit boards: the board is a program, verification is deterministic (KiCad's real DRC, headless), and review happens on a rendered contact sheet. **The board script defines the PCB netlist**; native schematic generation/checks are available through the project workflow; declare parts, connect pads, place and route with computed coordinates.

![A PCB contact sheet: raytraced 3D renders of a small green board from top, bottom and isometric angles, above three white layer plots showing front copper with routed tracks, the back copper ground pour, and the silkscreen.](docs/img/pcb-sheet.png)

```python
from pcb import Board

b = Board("blinky", w=20, h=15, corner_r=2)          # origin lower-left, +Y UP (build123d frame)
b.part("D1", "LED_SMD:LED_0603_1608Metric", at=(5, 7.5), value="LED red", lcsc="C2286")
b.part("R1", "Resistor_SMD:R_0603_1608Metric", at=(10.5, 7.5), value="1k", lcsc="C21190")
b.part("J1", "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical", at=(16.5, 8.8))
b.net("VCC", ("J1", 1), ("R1", 2))                   # the script IS the netlist
b.net("LED_A", ("R1", 1), ("D1", 2))
b.net("GND", ("J1", 2), ("D1", 1))
b.route("VCC", [("J1", 1), (13, 7.5), ("R1", 2)])    # polylines; points are pads or mm
b.route("LED_A", [("R1", 1), ("D1", 2)])
b.route("GND", [("D1", 1), (3, 7.5)])
b.via((3, 7.5), net="GND")
b.zone("GND", layer="B.Cu")                          # pour, filled headlessly
b.hole(2.5, 12.5, d=2.2)                             # NPTH mounting hole
b.silk("loupe blinky", 9.5, 12.5, size=0.9)
b.save("out")                                        # -> out/blinky.kicad_pcb
```

```sh
uv run examples/blinky_coupon.py                     # the script above -> a real .kicad_pcb
uv run pcbcheck.py examples/out/blinky.kicad_pcb     # KiCad DRC gate: nonzero exit on any error
uv run pcbsheet.py examples/out/blinky.kicad_pcb     # contact sheet -> Read the PNG
uv run pcbfab.py  examples/out/blinky.kicad_pcb --mesh   # gerbers.zip + BOM/CPL + STEP + STL
```

### How it works

`pcb.py` is a zero-dependency library with a double life: the half you import builds a JSON spec of the board; on `save()` it re-invokes itself **under KiCad's bundled Python** (the only place `pcbnew` exists) to materialize a genuine `.kicad_pcb` — real footprints from KiCad's libraries, real nets, filled zones. Everything downstream is `kicad-cli`: DRC, raytraced renders, layer plots, gerbers, position files, STEP.

Design rules are baked in from a **fab profile** (JLCPCB 2-layer by default: 0.127 mm min track/space, 0.3 mm min drill, 0.3 mm copper-to-edge), so `pcbcheck.py` enforces what your fab can actually build. Unrouted nets and pads you forgot to connect are hard failures — mark intentionally-floating pads with `b.nc(ref, pad)`.

### Case + board co-design

Board coordinates are math-style — origin at the board's lower-left, +Y up, mm — the same frame as a build123d case model. `pcbfab.py --mesh` tessellates the populated board (components included) into an STL that drops straight into `check.py` / `sheet.py` / `viewer.py` next to your enclosure parts: change a mounting-hole constant, regenerate both, and *prove* the standoffs still line up before anything is printed or fabbed.

### PCB requirements & limits

- **KiCad 10** (app bundle provides `kicad-cli`, `pcbnew` Python, and all footprint libraries). macOS paths are auto-discovered in `/Applications/KiCad` or `~/Applications/KiCad`; override with `LOUPE_KICAD=/path/to/KiCad.app`. Heads-up: `brew install --cask kicad` wants sudo (it drops demos into `/Library`); mounting the official DMG and copying the `KiCad` folder into `~/Applications` works without it.
- Routing is **explicit** — polylines you compute, not an autorouter. That's a feature at this scale (sensor carriers, LED boards, connector breakouts, keyboard matrices: placement math *is* the design); it's the wrong tool for a 6-layer RF board.
- 2-layer boards only (v1). BOM/CPL come out in JLCPCB's column format; LCSC part numbers flow from `part(..., lcsc="C1234")`.

---

## A typical loop

```sh
# 1. edit your build123d / CadQuery script, export STLs (individual + assembled `asm_*`)
uv run check.py asm_*.stl --interference-max 0.05 --min-wall 1.2   # gate: fails loudly on real bugs
uv run sheet.py asm_*.stl --slice z=50% -o sheet.png               # look at it
uv run viewer.py asm_*.stl -o preview.html && open preview.html    # let a human opine
uv run slice.py part_a.stl part_b.stl                              # time + cost, then print
```

Model multi-part designs in **assembled coordinates** and export both the individual parts and an `asm_*` set — `check.py` and `sheet.py` do interference detection across whatever files you hand them.

---

## For agents

This pipeline is built to be driven by an AI coding agent as much as a human. Three surfaces:

- **`loupe-cad` MCP server (via `uvx`):** Exposes all **7** tools (`draft_check`, `draft_sheet`, `check`, `sheet`, `slice`, `project_status`, and `project_run`). Crucially, **`sheet` and `draft_sheet` return their rendered drawings inline as PNGs**, so an agent sees the render in the same turn instead of writing a file and reading it back.

  **Claude Code (MCP one-liner):**
  ```sh
  claude mcp add loupe -- uvx loupe-cad
  ```

  **Claude Code Plugin & Agent Skill (`MCP` + lazy-loaded `SKILL.md`):**
  ```sh
  /plugin marketplace add charlesbine/loupe
  /plugin install loupe@loupe
  ```

  **Claude Desktop / Cursor / VS Code (`mcp.json`):**
  ```json
  {
    "mcpServers": {
      "loupe": {
        "command": "uvx",
        "args": ["loupe-cad"]
      }
    }
  }
  ```

  **From a local checkout (no PyPI needed):**
  ```sh
  claude mcp add loupe -- uv run /ABS/PATH/TO/loupe/loupe_mcp.py
  ```

- **[skills/loupe/SKILL.md](skills/loupe/SKILL.md)** & **[AGENTS.md](AGENTS.md)** — portable agent skill and terse operational runbook any coding agent (Claude Code, Cursor, Codex, Antigravity, Aider) can load for the exact review loop, coordinate conventions, and gotchas that waste tokens.

---

## Field notes (hard-won)

A few things that cost real time to learn:

- **trimesh:** load with `process=True` or CAD-exported STLs aren't `is_volume` (boolean ops refuse triangle soup). `polygons_full` silently drops holes unless **rtree** is installed.
- **Multi-start threads: an axial shift *is* a rotation.** Moving a helical part `dz` along its axis without also rotating it by `360·dz/lead` breaks the mesh phase and produces phantom interference. Applies to through-cut bores and to seating parts in an assembly.
- **Rounding meshes:** there is no reliable one-call "fillet everything." For your own code, fillet at the **sketch** level (2D fillets almost never fail; 3D `fillet(all_edges)` fails constantly on real parts). For downloaded STLs with no B-rep, a morphological offset (e.g. MeshLib's `doubleOffsetMesh`) rounds every convex edge in one pass — but marching-cubes leaves lumpy edges unless you use a fine voxel size and a volume-preserving smoothing pass before decimation. All mesh rounding *moves surfaces* — re-cut functional bores and mating faces afterward; rounding is for the cosmetic 90%, never datum surfaces.
- **Print fits (Bambu P1S, PLA, 0.20 mm — calibrate for your own machine):** ~0.15 mm radial clearance is a snug press fit that can bind under gravity; ~0.25 mm self-slides; ~0.35 mm has noticeable wobble. Elephant foot binds tight fits at end-of-travel.
- **Test at the smallest scale where the measured quantity is still representative.** Local fits → print a coupon/ring. Integral quantities (friction over full engagement, gravity self-slide) → only the full length is authoritative.

---

## License

Apache-2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
