Agents and the MCP server
CivilKit CAD includes a local server that lets an AI coding assistant build and check parts by writing scripts. It speaks the Model Context Protocol (MCP), so any MCP client can use it: Claude Code, Cursor, Claude Desktop, Codex and others. This chapter takes you from nothing to a first successful tool call, then lists every tool, error code, flag and limit.
What it is, and what it is not
- It is a separate program that runs on your computer, started from a checkout of the CivilKit CAD application repository. It is not a panel inside the browser app, but the app’s Chat panel uses it to run your Claude Code (see Chat: ask for a change in words).
- It has its own document and its own copy of the geometry kernel. By default it does not read the part you have open in the browser, and the browser does not show what the agent builds. You can link the two on purpose with the agent link (see Linking the open app): then the agent can read, take pictures of and, if you allow it, add to the part you have open. It is off until you turn it on.
- No tool or resource can load an existing part into the server. The agent starts from an empty document and builds everything with scripts, so none of your hand edits are involved or preserved.
- Everything on one machine shares one open document: there is one background process, one
daemon.jsonand one port. Two assistants, or two projects, that use the server at the same time overwrite each other’s work. - Work moves between the two by file. The agent calls
exportto write a.ckpartfile (or STEP, STL, GLB), and you open it in the app with Open (see Saving and opening). - The assistant brings its own model and key. The server never reads or stores a key.
- It uses the same script language as the Script tab (see Scripting). A part an agent builds is an ordinary feature tree.
If you only use the web app, you do not need this chapter.
Before you start
You need three things.
-
Node 22.
-
Two source trees, side by side. The launcher runs TypeScript through the application repository’s own
vite-node, and its settings (vite.config.ts) point the@ck/*imports at the kernel’s packages. So you need both:-
the application repository (it contains
apps/cadandpackages/mcp), and -
the kernel repository, checked out in the same parent folder and named
kernel, like this:work/ app/ the application repository kernel/ the kernel repositoryIf the kernel checkout has another name or place, set the environment variable
CK_REBUILDto its absolute path (in the client configuration, next toCK_WASM).
Then run
npm installin the application repository:cd work/app npm install -
-
The kernel binary (
ck_wasm.wasm). It is not stored in the repository. Get it in one of two ways:-
Download the one the published app uses. The site serves it at
/cad/kernel/ck_wasm.wasm:curl -o ck_wasm.wasm https://civilkit.io/cad/kernel/ck_wasm.wasmThis build loads in the launcher and runs scripts.
-
Or build it from the kernel repository with
cargo build -p ck-wasm --target wasm32-unknown-unknown --profile fast. See the kernel guide.
-
Then tell the server where the binary is, in one of two ways:
- Set the environment variable
CK_WASMto its absolute path (the client configurations below do this), or pass--wasm PATH. - Or copy it to
apps/cad/public/kernel/ck_wasm.wasminside the checkout, which is the default place the server looks.
In the commands below, replace <checkout> with the absolute path of the application repository and <wasm> with the absolute path of the .wasm file.
Connect a client
Claude Code
claude mcp add ck-cad -e CK_WASM=<wasm> -- node <checkout>/packages/mcp/bin/ck-mcp.mjs
To share the setup with a project instead, put this in a .mcp.json file at the project root:
{
"mcpServers": {
"ck-cad": {
"command": "node",
"args": ["<checkout>/packages/mcp/bin/ck-mcp.mjs"],
"env": { "CK_WASM": "<wasm>" }
}
}
}
Cursor
Put the same JSON in .cursor/mcp.json in a project, or in ~/.cursor/mcp.json to use it everywhere. Restart Cursor or reload its MCP settings.
Claude Desktop
Add the same mcpServers entry to claude_desktop_config.json, merging it with anything already there:
| System | File |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
Restart Claude Desktop after editing. Use the absolute path of node as command (for example the output of which node on macOS), because desktop apps often do not see the PATH of your shell.
Codex
Append this to ~/.codex/config.toml:
[mcp_servers.ck-cad]
command = "node"
args = ["<checkout>/packages/mcp/bin/ck-mcp.mjs"]
env = { CK_WASM = "<wasm>" }
On Windows, write paths with forward slashes or doubled backslashes in JSON and TOML.
Check that it works
-
List the servers. In Claude Code, run
claude mcp list.ck-cadshould be listed and connected. -
Check the background process. The first tool call starts a shared background process, which can take a few seconds (the launcher waits up to 40 seconds). Then run:
node <checkout>/packages/mcp/bin/ck-mcp.mjs --statusIt prints JSON such as
{"running":true,"port":53124,"pid":4242}. It prints{"running":false}when no process is running, which is normal before the first call or after it has idled out.--stopstops it. -
Make a first call. Ask your assistant: “Use ck-cad to build an 80 by 50 plate, 12 mm thick, and report its volume.” The assistant calls
run_script. If you want to see the protocol itself, this is what a client sends and what the server answers. You can try it without any client: put the lines below in a filemsgs.jsonland runCK_WASM=<wasm> node <checkout>/packages/mcp/bin/ck-mcp.mjs --stdio-direct < msgs.jsonlThe replies print one per line. The process exits when its input ends.
A first call, as JSON-RPC
The messages below are one per line. A client sends initialize, then notifications/initialized, then calls.
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"run_script","arguments":{"mode":"new","code":"part('Plate').sketch('front', (s) => s.rect(80, 50)).extrude(12)"}}}
The reply to run_script has two text blocks. The first is a one-line summary, and the second is the JSON result (shortened here):
script#1 (new) built 2 features, volume 48000
{ "ok": true, "run": "script#1", "mode": "new", "errors": [], "warnings": [],
"created": ["F1", "F2"], "removed": [], "regenMs": 21, "featureCount": 2, "solids": 1,
"volume": 48000, "area": 11120, "centerOfMass": [0, 0, 6],
"bbox": { "min": [-40, -25, 0], "max": [40, 25, 12], "size": [80, 50, 12] },
"faceCount": 6, "edgeCount": 12, "validity": { "ok": true, "issues": [] } }
The volume is 80 x 50 x 12 = 48000, as it should be. Now facts (no arguments) and tree:
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"facts","arguments":{}}}
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"tree","arguments":{}}}
facts returns featureCount, solids, volume (48000), area (11120), centerOfMass, bbox, faceCount (6), edgeCount (12), and validity (ok: true). tree returns:
{ "name": "Plate", "featureCount": 2, "handMade": 0,
"features": [
{ "index": 0, "id": "F1", "type": "sketch", "name": null, "origin": "script#1",
"params": { "plane": { "kind": "std", "id": "front" }, "points": "5 items", "entities": "4 items", "constraints": "0 items" } },
{ "index": 1, "id": "F2", "type": "extrude", "name": null, "origin": "script#1",
"params": { "op": "add", "sketch": "F1", "end": "blind", "depth": 12 } } ],
"errorCount": 0 }
To keep the part, call export with format: "ckpart" and a path, then open the file in the app.
The tools
An agent changes the model with one tool, run_script. Everything else reads, proves, shows or documents. The measuring tools (measure, clearance, interference, thickness, draft, dfm) answer what the kernel can compute exactly, so an agent can check its own work instead of estimating: they never change the model, name the bodies and faces they talk about, and give a verdict. Touching solids merge into one body unless the feature has newBody: true, so make parts that must stay separate with it before asking about clearance or interference. Tool calls run one at a time. Every input is checked against its schema, and unknown fields are refused.
| Tool | Arguments | What it returns |
|---|---|---|
run_script | code (required, up to 40,000 characters), mode (required: new or attach), name? (part name for new), replace? (last, all or none; attach only, default last) | The result shown above: ok, run, mode, errors, warnings, created and removed feature ids, regenMs, and a summary of the part. |
tree | none | The feature list in order: id, type, name, origin (script#N) and key parameters, with any errors and hints. |
find | query (required) | Features, face names and edge names that match the text. |
inspect | id (required) | One feature in full, the faces and edges it created, what depends on it, and its error if any. |
facts | expect?: list of checks such as [{"kind":"volume","value":1200,"tol":0.01},{"kind":"valid"}] | Mass properties, bounding box, counts and validity, plus a pass or fail per check. |
probe | points?: list of [x,y,z]; rays?: list of {origin, dir} | Per point: inside, outside or boundary, with the signed distance and nearest face. Per ray: the hits with face names. |
section | plane (required: {origin?, normal}), detail? (boolean) | The exact cross-section loops, their areas and the plane frame. detail: true adds the polyline points. |
sections | axis (required: x, y or z), n? (1 to 200), positions? | Areas of several slices and the volume they add up to, compared with the exact volume. |
bodies | none | One row per body: name, creating feature, volume, bounding box, colour. The names and numbers it shows are what the measuring tools take. |
measure | a, b (required: a body name or number, a face, edge or vertex name, or a point [x,y,z]), samples? | The minimum distance between the two, the closest point on each with the face or edge it lies on, the offset between them, and whether they touch. For two faces it adds the angle between them. |
clearance | a?, b? (default: the two bodies when there are exactly two), required? (mm), within?, limit? | The gap between two bodies with the closest points and the closest face pairs, and a verdict: clear or contact, and pass or fail against required with the shortfall. |
interference | a?, b? (bodies) | Every pair of bodies that share volume: the overlap volume in mm³, its centre and box, and the share of the smaller body that is inside the other. A pair the kernel could not compute is reported as incomplete, not as clear. |
thickness | min? (mm), body?, top?, method? (ray or sphere), samples? | The thinnest wall with where it is (the point and the two faces), the mean, the thinnest few places, and pass or fail against min with the places under it. |
draft | pull? ([x,y,z] or +Z … -X; default +Z), min? (degrees; default 1), faces?, body? | The draft angle of each face against the pull direction, the class of each (ok, vertical, undercut, parting), the walls under min worst first, and the count per class. |
dfm | process (required: injection, cnc or printing), direction?, params? (per-rule limits), rules?, maxIssues? | The design checks of the Check tab for that process: each issue with its rule, severity, faces, the measured value against the limit, and a point. For injection it includes Undercut (two-part mould): faces that neither mould half can form. The limits used are listed in the result. |
snapshot | view?, up?, size? (64 to 2048), style?, projection? (ortho or perspective), section?, sheet?, highlight?, markers?, frame?, annotate?, background? | A PNG image plus a short text summary (view, size, bytes). |
checkpoint | name (required) | Saves the whole document under a name. At most 20 are kept in memory; the oldest goes. |
restore | name (required) | Replaces the document with a checkpoint. Notes are not restored. It can be undone. |
checkpoints | none | Lists the saved checkpoints. |
notes | text?, append? | Reads the scratch notes, or replaces them with text, or adds to them with append: true. Notes survive restore and undo. |
list_methods | query? | Searches the registered script methods. With no query it returns the guide, all methods with signatures, and the recipes. |
docs | names (required, 1 to 30) | Full entries (signature, summary, example) for methods, or the code of recipes by id. Unknown names are reported as unknown. |
undo, redo | none | Step through the document history (50 states). |
ask_user | question (required), options? | A “needs user input” result. MCP has no screen of its own, so the agent should ask in its reply. |
export | format (required: step, stl, glb or ckpart), path? | Writes the file and returns the path and size. Without path, it writes ./<part name>.<extension> in the server’s working directory. The server is one shared process per machine, so that is the folder of whichever client started it first, not necessarily where you are working. Always pass an absolute path. |
Attach mode
In attach mode the script’s features are added to the features already in the server’s document, which can only come from earlier scripts, since nothing can load your own part. Each feature a script makes carries an origin mark such as script#2. By default a re-run first removes the features of the previous script run, so a corrected script does not duplicate its output; replace: "all" removes every script’s features and replace: "none" only adds. If a later feature depends on one that would be replaced, the run is refused and names it. tree reports handMade, which is always 0 here. Runs are all-or-nothing: a script with an error leaves the document as it was.
What list_methods and docs cover
The registry behind list_methods and docs is a small core set of about thirty entries: part, variables, expr, face, edges, at, through, sketch, extrude, cut, revolve, thin, hole, holes.*, fillet, chamfer, shell, linearPattern, circularPattern and the basic sketch builder methods. The script language itself has many more methods, such as loft, sweep, mirror, gear, thread, surfaces and assemblies (see Scripting). These work in run_script, but the registry does not describe them: list_methods {"query":"loft"} returns no methods, and docs {"names":["loft"]} answers “unknown”. An agent that knows the method can still use it; for example this builds a valid solid:
part('L').loft([{ on: at('front', 0), draw: (s) => s.rect(20, 20) }, { on: at('front', 30), draw: (s) => s.circle(6) }])
Point your assistant at Scripting or give it the method names directly when you want these.
Linking the open app
The agent link lets an assistant see, and if you allow it change, the part you have open in the browser app. It runs only on your computer and is off until you turn it on.
- Make sure the server is running and the assistant is connected. If the app is not served from your own computer (for example the hosted app), start the server with
--allow-origin https://<the app's address>; Safari does not allow a secure page to reach your computer, so use a local copy there. - Ask the assistant to call
bridge_pair. It gives you a code like52311-ABCD-EFGH-JKMN-PQRS, valid for 10 minutes and usable once. - In the app open Settings, Agent link, paste the code and press Turn on. The status bar now shows Agent: linked, view only.
- Optional: tick Allow the agent to change this document. Without it the agent can only read and take pictures. Untick it or press Turn off at any time; closing the page also ends the link, and nothing is remembered for next time.
| Tool | What it does | Needs the edit box |
|---|---|---|
bridge_pair | Gives the one-time pairing code. Calling it again ends any current link. | no |
app_status | Whether an app is linked and whether changes are allowed. | no |
app_state | The open part, compact and paged: name, features with their errors, variables, selection and counts, with filters on id, name and type, chosen fields, a cursor, and sinceRevision for only what changed. detail: "full" adds the whole document. A result over the output budget (4000 characters by default, maxChars up to 48000) is summarised with a handle that fetch_result pages through. | no |
app_open_asset | Opens a .ckpart, .solidcraft, STEP or mesh file in the app by path, from an allow-listed folder, so the file’s bytes never travel through the chat. | yes |
app_edit | Applies a set of edits (add, replace, remove, transform, set a parameter) as one transaction guarded by expectedRevision: it is checked step by step and committed as one undo step, or not at all. | yes |
app_interfaces | The part’s interfaces: hole axes and patterns without duplicates, unique planes, contact faces and coordinate frames. | no |
app_job_start, app_job_status, app_job_cancel, app_recipe_list | Run a long job (a big open, a saved recipe, a batch) in the background, ask how it is going, stop it, and list the saved recipes. | yes |
app_screenshot | A PNG of the model (view, size). It is a rendering of the part, not a copy of your screen. | no |
app_bodies, app_measure, app_clearance, app_interference, app_thickness, app_draft, app_dfm | The same measuring tools as above, asked of the part you have open: bodies, distance, gap, overlap, wall thickness, draft angles and the manufacturing checks. They only read, so they work without the edit box. | no |
app_run_script | Runs a script on the open part in attach mode: its features are added after yours as one undo step, and the app shows a notice. | yes |
app_undo, app_redo | Step the app’s undo history. | yes |
Failures come back as ordinary error results: app_not_connected (nothing linked: call bridge_pair), edit_not_allowed, app_timeout (the tab did not answer in 60 seconds), no_document, no_body. What is not there yet: the other tools (facts, probe, section, export…) on the open part, besides the measuring ones above, and a chat panel that uses them (see Chat: ask for a change in words). The chat panel is built; it runs your Claude Code through this server.
Resources
Besides tools, the server offers read-only resources:
| URI | Content |
|---|---|
ck://docs/guide | How the script API works and the build-check loop. |
ck://docs/methods | The registered methods with signatures and summaries. |
ck://recipes/<id> | A complete example script. The ids are bracket, flange, box, bc-pulley, bc-washer, bc-hex-nut, bc-enclosure, bc-motor-end-cap, pickleball and speedboat-dash. |
ck://document | The open part as JSON. |
ck://notes | The scratch notes. |
Errors
A failed tool call returns isError: true and a JSON body {"ok": false, "error": {"code", "message", "hint"}}. A script that fails reports its errors inside the run_script result. The line is given for runtime errors. A syntax error, or an error found only when the finished document is rebuilt, has "line": 0, which means no line is known. For example this is not js returns {"line":0,"message":"Unexpected identifier 'is'"}.
| Code | Meaning |
|---|---|
bad_input | An argument is missing, has the wrong type, or is unknown. The message names the field. |
unknown_tool | No tool has that name. The hint lists the tools. |
no_such_feature | inspect or a similar call named a feature that does not exist. |
no_such_checkpoint | restore named a checkpoint that was not saved. |
nothing_to_undo, nothing_to_redo | The history has nothing in that direction. |
no_body | Only export raises it: the document has no solid to export. |
snapshot_unavailable | The snapshot renderer is not available. The checkout includes it, so you only see this in a build without it. |
snapshot_failed | The renderer returned no image. Try another view or a smaller size. |
script_crash | The script runner failed unexpectedly. |
internal_error | The kernel or the tool failed unexpectedly. Retry, or restore a checkpoint. |
Protocol-level errors use JSON-RPC codes: -32700 (parse error), -32600 (invalid request; a message that has an id but no method is treated as a client reply and ignored), -32601 (method not found), -32602 (invalid parameters), -32603 (internal error) and -32002 (resource not found).
Tool output is capped at about 48,000 characters. Long lists are cut with a “more items” marker.
Flags and environment
Pass flags after ck-mcp.mjs. In a client configuration they go in the args array, for example "args": ["<checkout>/packages/mcp/bin/ck-mcp.mjs", "--idle-seconds", "600"].
| Flag | What it does |
|---|---|
| (none) | Normal mode. Connects to the shared background process, starting it if needed. |
--stdio-direct | No background process: the kernel lives inside this one, and its state ends with the client. Useful for tests and simple setups. |
--daemon | Run the background process in the foreground. |
--status, --stop | Report on, or stop, the background process. |
--idle-seconds N | The background process exits after N idle seconds (default 1800). |
--wasm PATH | The kernel binary to use. |
--allow-origin URL[,URL] | Let a specific web page use the agent link routes (a page served from your own computer is always allowed there). Everything else still refuses web pages. |
| Variable | What it does |
|---|---|
CK_WASM | Path of the kernel binary, if --wasm is not given. |
CK_MCP_HOME | The state folder (default ~/.ck-cad). |
CK_MCP_IDLE_SECONDS | The idle time, if --idle-seconds is not given. |
The state folder is created with mode 0700. Inside it, daemon.json (mode 0600) holds the port, process id and token of the running process. Only protocol messages go to the client’s standard output.
Security
- The background process listens on
127.0.0.1only, on a random port. - Every request must carry a 256-bit random token, made at start and held in
daemon.json, as anAuthorization: Bearerheader. - The
Hostheader must be127.0.0.1orlocalhostwith the right port, which blocks DNS rebinding. - Any request with an
Originheader is refused, except the agent link routes (/bridge/...), which accept a page from your own computer or an origin you listed with--allow-origin, and only with a one-time pairing code you pasted yourself and the session it buys. That session cannot call anything else in the process. - Any other program running as your user can read
daemon.json. Treat the process as trusted by that user. - Scripts run in a restricted environment that stops accidents. It is not a security boundary. Do not run scripts you do not trust.
Limits
- One document per process, and one linked app at a time (the agent link does not change the process’s own document).
run_scriptwithmode: "new"replaces it;undobrings it back. - Checkpoints (20) and history (50 states) are in memory and end when the process stops.
- The process exits after its idle time (30 minutes by default). The next call starts a new one, with an empty document.
- The first start takes a few seconds. Later starts are fast.
- Script sketches have no constraints.
- GLB export writes flat-shaded triangles. GLB is available only through this server, not the app’s Export menu.
- The server is a developer tool, started from a checkout. It is not installed from the app.