build123d-mcp
CLAUDE.md102 starsChanged 6 months agoApache-2.0View on GitHub
Always use uv run pytest — it auto-installs all dependencies from pyproject.toml before running. The target is 100% passing. There are no accepted pre-existing failures — if tests are failing, fix them. Communicates over stdio (MCP SDK v2 MCPServer). When configuring an MCP client, set cwd to the project root. 1. Create tools/<name>.py with a function def <name>(session, ...) -> str. Optional parameters must carry their defaults on this function — the worker wire omits arguments the caller didn't supply.…
- Commits and pushes
In this repositoryOne other file it gives its agents.
- b123d-drawingSkill
The file
We split this CLAUDE.md into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 5
Always use uv run pytest — it auto-installs all dependencies from pyproject.toml before running.
- Very specific: line 36
Create tools/<name>.py with a function def <name>(session, ...) -> str.
- Very specific: line 39
Add a typed stub method on WorkerSession in worker.py:
- Distinctive: line 107
After a timeout the namespace may be partially modified — don't trust state without a reset.
- Very specific: line 120
Before cutting a release: make sure CHANGELOG.md's top entry matches the version you're about to release (strip the .dev0 suffix mentally — …
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 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
build123d-mcp
Running tests
Always use uv run pytest — it auto-installs all dependencies from pyproject.toml before running.
uv run pytest tests/The target is 100% passing. There are no accepted pre-existing failures — if tests are failing, fix them.
Running the server
uv tool run --python 3.12 build123d-mcpCommunicates over stdio (MCP SDK v2 MCPServer). When configuring an MCP client, set cwd to the project root.
Project structure
server.py — MCPServer entry point; registers all MCP tools; holds module-level _session singleton
session.py — Persistent state: namespace, current_shape, objects dict, snapshots
security.py — Three-layer defence: AST check → restricted builtins → exec timeout
session_registry.py — Per-handle CAD sessions for HTTP (cap + idle eviction)
tools/execute.py — Thin wrapper delegating to session.execute()
tools/render.py — pyvista-based PNG rendering; headless (xvfb) if no DISPLAY
tools/measure.py — Geometry queries returning JSON (bounding_box, volume, area, wall thickness, clearance)
tools/export.py — STEP/STL export; path traversal blockedAdding a new tool
- Create
tools/<name>.pywith a functiondef <name>(session, ...) -> str. Optional parameters must carry their defaults on this function — the worker wire omits arguments the caller didn't supply. - Add a typed stub method on
WorkerSessioninworker.py:
The@_op(_tool(f"{_T}.<name>:<name>"), _GEOMETRY_TIMEOUT) def <name>(self, arg1: str, arg2: float = 0.0) -> str: raise NotImplementedError@_opdecorator registers the op in_OPSand replaces the body with bind-and-send — the signature is the single typed wire interface, so keep its defaults equal to the tool function's. Ops that need more thanfn(session, **args)in the worker get a small_op_<name>handler instead of_tool(...). - Register in
server.py:@mcp.tool() def <name>(...) -> str: """Docstring shown to MCP clients.""" return _session.<name>(...) - Classify the op in
tests/test_worker_boundary_coverage.py(add it to the smoke inventory,SESSION_STATEFUL_TOOLS, or the reasoned allowlist) —test_every_dispatch_op_is_classifiedfails until you do.
Session model
- Namespace persists across
execute()calls — imports and variables accumulate. current_shapeis auto-detected after each execute: an explicitshow()/annotate()in the call wins, then a variable namedresult, then any newBuildPartorShape.objectsdict holds named shapes registered viashow(shape, name=None). Name defaults to"shape"if omitted.- Snapshots save
current_shape+objectsonly — the Python namespace is NOT restored onrestore_snapshot(). reset()clears everything: namespace, shapes, objects, snapshots.
Concurrency model
- A
WorkerSessionis single-threaded over its pipe._call()holdsself._lockacrosssend → poll → recv, so concurrent callers serialise. This matters under HTTP transport, where one sharedWorkerSessionfields concurrent requests — without the lock, replies mispair. Subclasses override_do_call, not_call, so they inherit the guard (e.g.InProcessSession). Seedocs/adr/0001-worker-ipc-concurrency.md(#322). - HTTP mode shares one CAD session by default. The lock makes the sharing
safe, not isolated — concurrent clients still see one namespace. This is
still the default (
--max-sessions 1), so existing deployments are unchanged. --max-sessions N(N > 1) isolates clients by handle. A request carrying anMcp-Cad-Sessionheader gets that handle's ownWorkerSessionfromSessionRegistry(session_registry.py), resolved byCadSessionMiddlewareand created on first sight; requests without the header still share the default session. Sessions are capped and evicted after--session-idle-timeoutseconds, because each one is a subprocess with the OCC kernel loaded.- The handle comes from outside the MCP client — an auth gateway or a
client's static config. It is deliberately not the MCP protocol session id,
which dies on reconnect and would silently discard a half-built model. We do
not authenticate handles: put an auth gateway in front, and a session-aware
load balancer if running multiple processes. See
docs/adr/0003-http-cad-session-handles.md(#428), which supersedes ADR 0001's "isolation is the embedder's job" position.
Security model
Three layers, all must pass before user code runs:
- AST check — blocks imports of anything not in the allowlist (
build123d,math,numpy,typing,collections,itertools,functools,copy) and bare calls toeval,exec,open, etc. - Restricted builtins — exec namespace gets a filtered
__builtins__dict;open,eval,exec,compileremoved;__import__wrapped to enforce the same allowlist at runtime. - Exec timeout — default 120 s wall-clock, configurable via
--exec-timeoutCLI flag orBUILD123D_EXEC_TIMEOUTenv var. After timeout, the thread continues in background and the namespace may be dirty; callers shouldreset()orrestore_snapshot().
Known limits: memory exhaustion is not bounded; Python introspection chains can escape the sandbox; part-library files (--library) are trusted input — the AST check on them is non-transitive.
Gotchas
- After a timeout the namespace may be partially modified — don't trust state without a reset.
restore_snapshot()restores geometry only; Python variables set after the snapshot remain in scope.show()stores shapes by reference; mutating the shape object after callingshow()will affect the stored object.- Clip plane in
render_viewslices at the mesh's own bounding-box midpoint, not world origin.
Releasing
Cutting a release means one command: gh release create vX.Y.Z --generate-notes (or use the GitHub Release UI). That triggers the Publish workflow which builds, uploads to PyPI, and auto-bumps pyproject.toml to the next .dev0 version. Nothing else is needed.
Never edit pyproject.toml manually. Never push tags manually. Manual edits/tags don't trigger the publish workflow and create orphan tags + version drift. If you see pyproject.toml showing 0.3.14.dev0, that means 0.3.13 is the current PyPI release and 0.3.14 is the next planned release; don't "fix" the version.
Version convention: between releases, pyproject.toml carries a .dev0 suffix (PEP 440 dev release). 0.3.12 < 0.3.13.dev0 < 0.3.13.dev99 < 0.3.13 — TestPyPI builds (.devN) are always newer than the last published release but older than the eventual real release.
Before cutting a release: make sure CHANGELOG.md's top entry matches the version you're about to release (strip the .dev0 suffix mentally — pyproject.toml = 0.3.14.dev0 means you're cutting v0.3.14).
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.

