Files
e6bbf59c31 Expose xdata through entities, properties.set and AutoLISP's -3 group (#2469)
* Expose xdata through entities, properties.set and AutoLISP's -3 group

An entity's extended data was read, kept and written back (#528) but
invisible to the API: `entities` left it out, `properties.set` had no
field for it, `entget` never returned the -3 group and `entmod` dropped
it. Now `entities {xdata: true | "APP"}` and `properties` list it per
application with values typed by group code, `properties.set {xdata}`
replaces or removes one application's data after checking codes,
values, braces and sizes, and AutoLISP's entget/entmod/entmake carry
the -3 group, with `regapp` and the APPID table. The applications
CADCraft writes from its own model are reserved (one list, now in
cadcraft_doc, shared with the DXF reader).

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Check xdata before any change in properties.set; cap entmake's xdata across applications

Review follow-ups on #2469:
- properties.set validated xdata after ensure_layer, so a request naming a new
  layer and carrying bad or oversized xdata left the layer behind on failure.
  The xdata checks now run first.
- entmake capped each application's groups but not their sum; an entity could
  exceed MAX_XDATA_GROUPS across applications. The total is checked as entmod
  already does, with a test.
- docs: the control-protocol xdata section is an h2 like its neighbours; the
  file-format-parity revision row no longer has a pipe inside a code span.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* properties.set checks every handle first; a dotted -3 group is a bad list

Review follow-ups on #2469:
- properties.set edited the objects before a handle that names nothing and
  then failed, keeping those edits (and a new layer). Every handle is checked
  before anything changes; a missing one is refused with its hex.
- xdata_from_list read `(-3 . 7)` as "no applications" and let entmake/entmod
  succeed with nothing set. A -3 whose cdr is not a list is refused (listp),
  so both return nil as for any bad list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* An xdata application's groups must be a proper list

Review follow-up on #2469: `("ACME" . 7)` in a -3 group read as "no groups",
which `entmod` takes as "remove ACME's data", and a dotted tail after real
groups was dropped. The application's tail is checked as a list (listp) like
the -3 group itself, so entmake/entmod answer nil and change nothing; test
covers both shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Runs of one xdata application in any case are one application in the API

Review follow-up on #2469: a file can carry `ACME` and `acme` runs on one
entity. `entities` showed them as two JSON keys and `entget` as two lists, and
writing either back through properties.set or entmod replaced the application
twice, keeping only the last run's groups. Both projections now merge runs
case-insensitively (first spelling, all the groups), as set_xdata_app already
treats them; tests round-trip such an entity through both APIs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Refuse raw ACAD xdata on a dimension, whose ACAD run is written from its overrides

Review follow-up on #2469 (austin62jake): properties.set accepted
`xdata: {"ACAD": …}` on a dimension and `entities` showed it, but the DXF
writer emits the dimension's ACAD run (DSTYLE) from its overrides and the
reader models it back, so the raw groups vanished on save. ACAD can't join
RESERVED_XDATA_APPS (files carry ACAD data on other entities that CADCraft
keeps raw), so the rule is per entity: `is_model_xdata_app(name, kind)` is
the reserved list on any entity plus ACAD on a dimension. properties.set
refuses it before anything changes, entmake/entmod answer nil. Tests cover
both paths, including that ACAD on a line survives a DXF round trip and the
dimension's own override does too. control-protocol.md says so.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(lisp): return and accept REAL for xdata group 1071

---------

Signed-off-by: FredApps <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-01 11:38:34 +01:00

152 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CADCraft and AI agents (MCP)
CADCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio.
## Start it
```sh
# Headless: an in-process drawing session, no window.
cadcraft-cli mcp
# Bridged to the running app (watch the agent draw):
cadcraft --control 7979 &
cadcraft-cli mcp --connect 127.0.0.1:7979
```
An MCP client usually starts its servers when it starts, often before the app is open. With
`--lazy` the bridge starts anyway and reaches the app at the first tool call; until the app answers,
each call fails with a message saying how to open it. `--launch` also opens CADCraft (macOS) with
that control port at a call that finds nothing, and waits for it:
```json
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp", "--connect", "127.0.0.1:7979", "--launch"] } } }
```
`--connect` needs the app's `HOST:PORT`. Without one (or with an unknown argument) `cadcraft-cli mcp`
exits with an error instead of falling back to a headless session, so a client meant for the app
never edits a separate drawing by mistake. If the app can't be reached, startup fails too.
Example client configuration (Claude Code / Claude Desktop):
```json
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } }
```
## Confining file access
```sh
cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out
```
The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client
configuration works across the suite) keep the agent to the folders you give it:
- Every file a command **reads** must lie inside the **read root or the write root**: `open`,
`recover`, `compare`, `script`, `import`, `insert`, `xattach` and every xref it loads, `new`
templates, `appload` and LISP `load`/`open`, support files (`linetype`, `hatch.patterns`,
`aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path,
and the shared plotter settings folder.
- Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas`
(including the temporary file and `.bak` written beside the destination), `export`, `plot`, `publish`,
`pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared
plotter settings folder, and `render {path}`. The write root itself is refused: a save's
temporary file would sit beside it, outside the root.
- Give the same folder twice for both. A root left out grants none of its *own* access: a read
root allows no writes, while a write root still allows reads inside it (files the agent wrote it
can read back). Without either flag nothing changes.
- A path is made absolute against the server's working directory, then its links are followed: a
file or folder link that leads out of a root is outside it. For a file that doesn't exist yet,
its nearest existing folder's links are followed and the rest must be plain names, so `..` below
a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared
with the root by whole folder names, exactly: `/work2/x` is not inside `/work`, and on Windows
a folder's own case comes from the file system, so a case-sensitive folder's `Root` is not
`root`. On Windows a UNC path (`\\server\share`, `\\?\UNC\...`, including `\\host@SSL\...`) is
refused before it is opened unless a root is on that same server and share. A device path
(`\\.\...`) is refused unless a root uses the same device, and a verbatim path that isn't a
disk is refused unless a root uses the same prefix. Device names (`CON`, `NUL`, `COM1`,
`LPT¹`…) are refused too.
- A path you write must also stand under the write root: a link outside it pointing in is refused,
because a drawing's `.bak` goes beside the link and a delete removes the link.
- A refused path in a tool other than `command_line` is an ordinary tool error with `isError: true`
that the agent can read and correct, for example `automation path rejected: outside the write root
/work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write
root): /etc/x.png`, `automation path rejected: the write root itself cannot be written:
/work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the
same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted:
write authority is absent: /work/project/out/x.png`.
- A refused path in a `command_line` line is not a tool error: the reply is an ordinary result, with
the refusal in its `error` field (and echoed in `output`) and without `isError`. A command that
reports the refusal at its own prompt and finishes, as `-WBLOCK` does when the file it is about to
write is refused, has no `error` field: the refusal is only in `output`. A client that drives
`command_line` has to read `error` and `output`.
- A file a drawing names is held to the roots too: an image or xref saved with a path outside them is
not loaded from there, and the answer doesn't say whether the file exists. As without roots, a file
of the same name beside the host drawing is tried next, so when one is there and inside the roots
it is loaded in its place: check what a reference loaded when it matters.
- A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`):
one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH
can't be changed, because both work on the server's autosave folder.
- SHX fonts beside an opened drawing are searched, and each file the search would open there is
checked against the roots first, whatever its name: a font that is a link leading out of the
roots is skipped, and the rest of the folder is still used.
- The server itself still reads the system's fonts, from the system font folders and
`CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file
named by a drawing can decide which of them is read.
- The roots must be existing folders; a missing one stops the server with an error. Each flag is
given once (`--flag <dir>` or `--flag=<dir>`).
The flags confine the headless server. `--connect` with them is an error, since the server would
otherwise talk to an app that isn't confined; the app's control channel does not take them yet
(#1585). Without `--connect` the server writes the files itself, so every check happens here.
A path is checked, then opened: another program on the computer that swaps in a link between the two
can still win that race, and a hard link can't be told from a file. Use the operating system's
sandbox as well if other programs can change these folders.
## Tools
| Tool | What it does |
|---|---|
| `command_line {text}` | Type at the command line exactly like a person: `line 0,0 @10,0 @0,5 c`, `circle 5,2 1`, `offset 0.5`, `zoom e`. Spaces act as Enter; empty text is Enter. Returns the new prompt, keywords and output. |
| `script {text}` | A multi-line script (like `.scr` files). |
| `execute {command, params}` | Any command with JSON parameters, never a dialog. `list_commands` shows ids and parameter docs. |
| `list_commands {filter?}` | The command catalog; `filter` matches part of a command's id, label or an alias. |
| `inspect_drawing {entities?, limit?}` | Counts, extents, layers, styles, blocks, layouts, selection, undo history and entities. |
| `query_entities {type?, layer?, window?, crossing?, xdata?, limit?, offset?}` | Filtered entities with handles and geometry. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `xdata: true` adds each entity's extended data as `{"APP": [[code, value], …]}`; an application name (or a list of names) keeps only the entities carrying that application's data and shows just it. `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
| `execute {"command": "shapes", "params": {type?, layer?, window?, crossing?, limit?, offset?, tolerance?}}` | Facts about the closed shapes — closed polylines, circles, full ellipses, closed splines: perimeter, area, centroid, winding, the first self-intersection and coincident vertices, exact with arcs and bulges. Other matches are counted under `skipped` with the reason. `selfCheck` says what was found, analysed and skipped, the caps hit with their values (`limit`, `crossingSegments`) and implausible values (perimeter past 10× the bounding-box diagonal, area larger than the drawing extents, each past a 1e-9 relative tolerance for rounding; with no visible objects there are no extents, so no area bound applies). |
| `execute {"command": "shapes", "params": {type?, layer?, window?, crossing?, limit?, offset?, tolerance?}}` | Facts about the closed shapes — closed polylines, circles, full ellipses, closed splines: perimeter, area, centroid, winding, the first self-intersection and coincident vertices, exact with arcs and bulges. Other matches are counted under `skipped` with the reason. |
| `execute {"command": "usage", "params": {type?, limit?, offset?}}` | Read-only cross-reference of the layers, blocks, text styles and linetypes: for each, the objects in model space and layouts that use it, the objects in block definitions that use it, whether it is used only inside block definitions, and whether it is empty or unused. `summary` counts each kind and `unused` lists what PURGE would offer, in table order. One scan reads at most 5,000,000 objects; a larger drawing sets `incomplete: true` with an `incompleteReason`, because counts, statuses and summaries then omit the objects past the limit. |
| `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. |
| `query_entities {type?, layer?, selected?, window?, crossing?, xdata?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `xdata: true` adds each entity's extended data (see [control-protocol.md](control-protocol.md#extended-data-xdata)); an application name keeps only the entities carrying its data. `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
Resources: `cadcraft://drawing` (inspect JSON) and `cadcraft://commands` (catalog).
Arguments are checked against each tool's input schema. An unknown tool, `arguments` that aren't an
object, a missing required argument or one of the wrong type is a JSON-RPC error `-32602` (invalid
params), so `command_line {}` never presses Enter by accident. A tool that runs and fails (a bad
point, an unknown command) returns a result with `isError: true` and the message.
## A typical session
1. `command_line {"text": "rectang 0,0 100,60"}`
2. `execute {"command": "circle", "params": {"center": [10, 10], "radius": 4}}`
3. `command_line {"text": "dimlinear 0,0 100,0 50,-8"}`
4. `inspect_drawing {}` — verify counts and geometry.
5. `render {}` — look at it.
To change properties the way the Properties palette does, find the object's handle first, for
example the dimension from step 3 with `query_entities {"type": "Dimension"}` (say its `handle`
is `"2F"`). Then `execute {"command": "properties.describe", "params": {"handles": ["2F"]}}`
lists the palette's rows for those objects: each row's `key` (what `properties.set` takes), its value (or `varies`), the value as
shown in the drawing's units, and whether it can be edited (with a `note` when not). Then
`execute {"command": "properties.set", "params": {"handles": ["2F"], "textHeight": 0.25}}`
changes it; on a dimension, style variables such as `textHeight` (or `DIMTXT`) become overrides of
that dimension, and the reply's `ignored` lists keys no selected object took.
The end-to-end test in `crates/mcp/src/tests.rs` runs a session like this and checks the result
only through MCP.