Document the MCP server and add an agent skill for driving OrcaSlicer

This commit is contained in:
SoftFever committed 2026-10-28 19:43:09 +08:00
1 parent c47e1843d9
commit 0fed1f6077
5 files changed
+789

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
---
name: orca-mcp
description: "Drive a running OrcaSlicer through its MCP server - reproduce a GitHub issue, capture before/after screenshots, script deterministic GUI steps. Use when you need to run the app and see or interact with it."
---
# Driving OrcaSlicer through its MCP server
OrcaSlicer has a built-in MCP server. With it you can launch the app, load files, pick presets,
change settings, slice, click through the GUI and take screenshots, then save the session as a
script that replays the same steps. `docs/HLSD/mcp-server.md` describes the design, and
`tools/mcp/README.md` the harness.
## Launch
Build Release (`cmake --build build --config Release --target all --` on Linux), then:
```bash
tools/mcp/orca_mcp.py launch --xvfb --print-config
```
`launch` starts `build/src/Release/orca-slicer` (or `--bin PATH`) with `--mcp` and a fresh
temporary datadir. The datadir is seeded with a finished setup wizard and one printer, Bambu Lab X1
Carbon 0.4 by default. To use another printer, pass
`--printer "<model>@<nozzle>" --vendor <profile vendor> --filament "<preset>"`. `--xvfb` runs the
app on a private X display. `launch` waits until the app is ready, then prints the session as
JSON: `url`, `port`, `token`, `pid` and `datadir`. With `--print-config` it also prints the
`claude mcp add` line.
Other launch options:
- `--datadir DIR` reuses a datadir. Pass the first launch's datadir on every relaunch, so the
presets stay identical.
- `--port N` sets the port, needed when 13619 is taken, for example by your own OrcaSlicer with MCP
enabled.
- Arguments after `--` go to the app.
- `tools/mcp/orca_mcp.py stop` ends the app and its Xvfb.
You can talk to the app in two ways:
- **The harness**, which works from any shell at any time:
`tools/mcp/orca_mcp.py call <tool> '<json args>'`. Add `--wait` to follow a returned job to its
result. It also has shortcuts: `screenshot /abs/out.png --target canvas`, `snapshot`, `tools`
and `run-script FILE --out DIR`.
- **Claude Code tools**, registered with
`claude mcp add orcaslicer -- /abs/build/src/Release/orca-slicer --mcp-stdio --datadir DIR`.
The stdio bridge reads the port and token of the instance running on that datadir every time it
connects, so relaunches and token changes need no new registration. Claude Code loads MCP
servers when a session starts, so register before you start the session that will use them.
## Reproduce an issue
1. Read the issue (`gh issue view <N> --repo OrcaSlicer/OrcaSlicer --comments`). Note the
printer, process and filament presets, the changed settings and the steps. Download any
attached project or model into a work folder. Every path you pass must be absolute.
2. Call `get_state`. Check `ready`, `presets`, `dialogs` and `display_backend`. After a forced
stop, the app asks at startup whether to restore the unsaved project. Clear that and later
prompts with
`dialog_auto_answer {"rules": [{"match": "restore", "button": "no"}, {"match": "unsaved changes", "button": "no"}]}`;
a rule also answers a matching dialog that is already open.
3. Load the files with `open_files {"paths": ["/abs/work/issue.3mf"]}`. A `.3mf` opens as a project,
with its own presets and plates. Add `"as": "geometry"` to import only its objects, and
`"discard_changes": true` to replace a modified project.
4. Configure. Find presets with `list_presets {"type": "printer", "query": "Voron"}` and select one
with `select_preset {"type": "printer", "name": "<as listed>"}`; filaments take
`filament_slot`. Find setting keys with `get_settings {"query": "seam"}`, then change them with
`set_settings {"scope": "print", "values": {"wall_loops": 3, "sparse_infill_density": "15%"}}`.
For per-object overrides, use `"scope": "object", "object": 0`.
5. Do the steps, in this order of preference: typed tools, then
`list_actions {"query": "arrange"}` with `run_action {"id": "..."}`, then the GUI tools. A
Speed Dial command with a path param skips its file dialog:
`run_action {"id": "orca_command:export_stl:orca", "param": "{\"path\": \"/abs/x.stl\", \"overwrite\": true}"}`.
6. Slice with `slice {}`. Look at `status` and at `plates[].outcome`: `ok` (with print time and
filament), `error`, `cancelled`, `empty` or `skipped`.
7. Point the view:
`set_view {"tab": "preview", "camera": "iso", "layer": 40, "view_type": "feature_type"}`.
Use `"camera": "fit_objects"` to frame the model.
8. Take a screenshot:
`screenshot {"target": "canvas", "save_path": "/abs/work/before.png", "overwrite": true}`. Use
`"target": "window"` for the whole UI and `"dialog"` for the topmost modal. The reply carries
a scaled-down image; open the full-size PNG with Read to look closer.
9. Save the session as a script with `export_script {"path": "/abs/work/repro.json"}`. Failed calls
are left out; `export_script {"clear": true}` at the start drops the calls made while you
explored. Now edit the script:
- add `expect`s that hold when the bug is fixed, so the script fails before the fix and passes
after it;
- change the screenshot step's file to `after.png`;
- replace downloaded paths with `${script_dir}/…` if you keep the files beside the script.
10. Fix the code, rebuild, `stop`, and launch again with the same `--datadir`. Then run
`tools/mcp/orca_mcp.py run-script /abs/work/repro.json --out /abs/work`. It prints each step's
result and exits 0 when the script passes. Without the harness, run
`orca-slicer --datadir DIR --mcp-script repro.json --mcp-script-out /abs/work` on a display
(under Xvfb, set `DISPLAY` and `GDK_BACKEND=x11`). It writes `result.json` and the
screenshots, closes, and exits with 0 (passed), 1 (a step failed) or 2 (invalid script).
11. Compare `before.png` and `after.png` (Read both), and check each step's result.
## Rules
- **Never retry a call that returned `{"status": "running" | "blocked_by_dialog", "job": "jN"}`.**
The call is still running. Use `wait {"for": "job", "job": "jN"}` to get its result; each `wait`
lasts at most 50 s, so repeat it as needed. With the harness, use `call … --wait`. Retrying is
safe only when the error says the call was not run.
- **`blocked_by_dialog`** lists the dialog's `title`, `message` and `buttons`. Answer it with
`dialog_respond`, then wait for the job. A dialog marked `native: true` (message boxes, file
pickers) can't be clicked, so register `dialog_auto_answer` before the step that opens it, or use
a typed tool that needs no dialog. In a script, put `dialog_auto_answer` first.
- "A modal dialog is open; answer it first" means `get_state.dialogs` lists what is in the way.
- While a slice or G-code export runs, other changes are refused. `wait` for it, or `cancel` it.
- Before a screenshot after arrange, orient or anything else that runs in the background, call
`wait {"for": "idle"}`.
- Prefer typed tools, then `run_action`, then clicks. Clicks are the most fragile path.
- GUI tools act on a `target`: a ref from the latest `ui_snapshot` (`"w12"`), or a locator such
as `{"option": "layer_height"}` (a setting field), `{"label": "Slice plate"}`,
`{"label": "Show splash screen", "within": "Preferences"}`,
`{"menu": "File>Export>Export G-code"}`, `{"gltoolbar": "arrange"}`, `{"gizmo": "Move"}` or
`{"imgui": "label"}`. Examples: `ui_snapshot {"query": "Arrange"}` (`"root": "dialog"` for the
topmost modal), `ui_click {"target": "w12"}`,
`ui_input {"target": {"option": "layer_height"}, "value": "0.16"}`, `ui_key {"keys": "Ctrl+Z"}`
(to the topmost dialog when one is open), `dialog_respond {"button": "ok"}`. A target is scrolled
into view first, as a person would, so a following screenshot shows it.
- Refs go stale when the UI changes, and after a language change. Take a new snapshot (narrowed
with `"query"`) before each GUI action. Scripts store locators, not refs.
- `dialog_auto_answer {"rules": [{"match": "<regex>", "button": "no"}]}` replaces the rules your
session set before, and an empty list clears them. Inside a script, the rules last until the
script ends. `get_state.auto_answer_rules` lists the rules in force, with how often each answered.
- Paths are absolute. Output directories must exist, and an existing file is replaced only with
`"overwrite": true`. In a `run_action` param, pass the JSON string
`{"path": …, "overwrite": true}`.
- When something fails, `get_log {"level": "warning"}` shows why. Startup problems go to
`<datadir>/mcp-launch.log`.
- Never point `--datadir` at your real OrcaSlicer profile.
## Script format
```jsonc
{ "orca_script": 1, "name": "repro #12345",
"vars": {"model": "${script_dir}/part.3mf"}, // ${vars.model} below
"steps": [
{"tool": "dialog_auto_answer", "args": {"rules": [{"match": "unsaved", "button": "no"}]}},
{"tool": "open_files", "args": {"paths": ["${vars.model}"], "discard_changes": true}},
{"tool": "set_settings", "args": {"scope": "print", "values": {"wall_loops": 3}}},
{"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}},
{"tool": "set_view", "args": {"tab": "preview", "camera": "iso"}},
{"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/after.png", "overwrite": true}}
]}
```
The placeholders are `${script_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and
`${jobs.NAME}`. A step that returns a job is awaited, up to `timeout_s` (default 120), before its
`expect` is checked. To deal with a dialog the step opens, give it `"await": false, "save_as": "x"`,
answer the dialog in the next steps, then add
`{"tool": "wait", "args": {"for": "job", "job": "${jobs.x}"}}`. `expect` maps a JSON pointer into
the step's result to matchers: `eq ne gt ge lt le contains regex exists empty`. `"optional": true`
lets a step fail without stopping the run.
## Linux display notes
- `--xvfb` runs on X11, so `window` and `dialog` screenshots are exact while the window fits on the
screen. The default screen is 1600×1000; change it with `--width`/`--height`, or resize with
`set_view {"window_size": [1400, 900]}`.
- Under a Wayland session, without `--xvfb`, `get_state.display_backend` is `wayland`. There,
`window` and `dialog` screenshots come back `approximate`: they are drawn from the widget tree,
and web views can be blank. Use `"target": "canvas"`, which is exact everywhere, or launch with
`GDK_BACKEND=x11`.
- On X11, OrcaSlicer's own popups and tooltips above the window are drawn into the capture, as on
screen. A part covered by another application's window comes out black, and the result is
`approximate`. Xvfb has nothing else on top.
- When launching by hand on a fresh datadir, set `SSL_CERT_FILE` (the harness does), or a CA-bundle
prompt blocks startup.
- Testing in the Fedora or Debian VMs follows the machine's own notes and is not covered here.
+2
View File
@@ -27,6 +27,8 @@ ctest --test-dir ./tests/libslic3r -C Release # individual suite
ctest --test-dir ./tests/fff_print -C Release
```
To run the app and see or drive it (reproduce an issue, capture before/after screenshots, script GUI steps), use its MCP server through the [orca-mcp skill](.claude/skills/orca-mcp/SKILL.md); the design is in [docs/HLSD/mcp-server.md](docs/HLSD/mcp-server.md).
## Documentation
- Docs live in `docs/`; the high-level design of a subsystem goes in `docs/HLSD/<subsystem>.md`.
+458
View File
@@ -0,0 +1,458 @@
# MCP Server
## Why it exists
The MCP server lets an AI agent drive a running OrcaSlicer through the Model Context Protocol.
The same tools serve two audiences. A developer's agent reproduces a GitHub issue: it loads the
files, picks presets, changes settings, clicks through the GUI and slices. It also takes
screenshots before and after a fix and replays the steps from a script file. A user can drive
OrcaSlicer from Claude Code, Codex, Cursor or Claude Desktop.
The server runs inside the GUI process, because most of what an agent reproduces is GUI
behaviour, and reuses the Speed Dial catalog, so a feature added to the palette reaches agents and
scripts too. It is off by default; until it is first turned on, `McpService` does not exist, so
there is no thread, socket, modal-dialog hook, ImGui item recording or synthetic input state. The code is in
`src/slic3r/GUI/Mcp/`; the protocol, transport, threading core, script runner and operation logic
don't use wx, so they can be unit-tested.
```
MCP client ──POST /mcp──▶ McpHttpServer ──▶ McpProtocol ──▶ McpCore ──▶ UiInvoker ──▶ UI thread
stdio client ──▶ orca-slicer --mcp-stdio ──┘ │
JobRegistry, Journal
```
`McpService`, owned by `GUI_App`, owns all of it except the bridge, plus the `ToolRegistry` and
the `ModalTracker`.
## Transport
The endpoint is `http://127.0.0.1:<port>/mcp`, bound to loopback. The default port is 13619,
since 13618 is the OAuth callback server. It is stateless Streamable HTTP: each POST carries one
JSON-RPC message. A request gets `200 application/json`. A notification or a response gets `202`
with no body. There is no SSE stream and no `Mcp-Session-Id`. Other methods get 405 with
`Allow: POST`, and other paths get 404. Batches get `-32600`, and so does an `id` that is neither
a string nor an integer.
`McpHttpServer` runs every socket on one Boost.Beast I/O thread, with a 30 s read deadline, a
120 s keep-alive idle timeout and an 8 MiB body cap. Each complete request runs on its own thread,
because a handler can block for a tool's whole reply budget. A connection carries one request at a
time, so threads never outnumber connections. The server takes 64 connections plus an overflow
reserve of 8. At the cap, a new connection evicts the one waiting longest on its client (idle or
still sending), never one whose request is being handled, and uses a reserve place only when all
are dispatched, so a recovery call gets through even when stalled clients hold the connections.
The listening and accepted sockets are made non-inheritable (`FD_CLOEXEC`, or no
`HANDLE_FLAG_INHERIT` on Windows). Otherwise a child process, such as a web view helper or a
post-processing script, would keep the port bound after the server closes it, and new connections
would queue on a socket nobody accepts.
Before any JSON is parsed, `validate_request()` checks path (404), method (405), a `Host` of
`127.0.0.1:<port>` or `localhost:<port>` against DNS rebinding (403), a loopback `Origin` when one
is sent (403), the bearer token in constant time (401 with `WWW-Authenticate`), `Content-Type:
application/json` (415) and the size cap (413). No CORS headers are sent, so browser preflights fail.
`McpProtocol` picks one of two protocol eras for each message.
- **Handshake era.** `initialize` echoes the client's version if it is 2025-11-25 or 2025-06-18,
and answers 2025-11-25 otherwise. Then come `notifications/initialized`, `ping`, `tools/list`
and `tools/call`. A present `MCP-Protocol-Version` header must be supported (400).
- **2026-07-28.** A request whose `params._meta` carries
`io.modelcontextprotocol/protocolVersion` is served without a handshake. `server/discover`
lists versions, capabilities and instructions. The `MCP-Protocol-Version`, `Mcp-Method` and
`Mcp-Name` headers must match the body (400, `-32020`); `Mcp-Name` is needed for `tools/call`,
`prompts/get` and `resources/read`. An unsupported version gets 400 `-32022` with the supported
list. Results carry `resultType: "complete"`, and list results carry `ttlMs` and `cacheScope`.
A tool result is one compact JSON text block plus any image blocks; no tool declares an
`outputSchema`, so no `structuredContent` is sent. Tool failures, invalid arguments included, are
`isError` results the model can act on; an unknown tool is a JSON-RPC `-32602` error naming close
matches. `validate_arguments()` checks arguments against the tool's schema first. The server
`instructions` (under the 4096 characters clients keep) give the workflow `get_state`, act, `wait`,
`screenshot`, and say to prefer typed tools over clicks and never retry a call that returned a job.
## Security, token and discovery
The bearer token is 32 random bytes as 64 hex characters in `<datadir>/mcp/token`: directory 0700
and file created 0600 with `O_CREAT|O_EXCL` on POSIX, the per-user ACL of `%APPDATA%` on Windows.
It stays out of AppConfig, whose writes and backups use default permissions. `ORCA_MCP_TOKEN`
(preferred, as it stays out of the process list) or `--mcp-token` overrides it for one run. While
serving, `<datadir>/mcp/server.json` holds `{url, port, pid, version, token}` with the token in
use, so the stdio bridge and the harness connect without the launch environment. It is written
owner-only via an exclusive temporary file and a rename (`write_private_file()`), and removed on
stop.
## Lifecycle
`GUI_App::on_init_inner()` starts the service once AppConfig is loaded. That is before the first
startup dialog, such as the TLS prompt or the setup wizard, so an agent can answer those dialogs.
`--mcp` or the `mcp_enabled` preference opens the endpoint, while `--mcp-script` alone only builds
the catalog. `get_state.ready` stays false until `post_init()` calls `mark_ready()`, and tools that
need the main window fail with "still starting". `mark_ready()` also starts a command-line script.
The service stops, idempotently, at the start of `MainFrame::shutdown()` when the app closes
(before panels are destroyed), after a failed initialization (which never reaches `OnExit()`), on
`wxEVT_END_SESSION` (after which macOS calls `exit()`) and in `OnExit()`. Stopping first wakes every
waiting call with "shutting down" (`UiInvoker::shutdown()`, `JobRegistry::wake_all()`), then joins
job threads and stops the HTTP server with time limits, removes the discovery file and turns ImGui
recording off. A language change runs `MainFrame::shutdown()` from `recreate_GUI()`, which only
suspends the service: the transport stays up, the UI generation is bumped so every GUI ref goes
stale, UI calls fail with a request to retry, and `ready` is false until `recreate_GUI()` resumes
it.
Preferences turns the server on with `GUI_App::start_mcp_service()` and off with
`McpService::stop_serving()`, which closes only the endpoint and removes the discovery file. The
catalog, running jobs and a launch script carry on, because the call that opened Preferences may
itself be an MCP call still on the stack. A new port or token reopens the endpoint through
`GUI_App::restart_mcp_endpoint()`, and a port set in Preferences replaces `--mcp-port` for the rest
of the session. Closing the endpoint from the UI thread doesn't wait for in-flight requests, which
may be waiting on that thread; their replies are dropped. A bind failure is logged, shown as a
notification and in Preferences, and a start from Preferences never reruns a command-line script.
## Threading
Tool handlers never run on the UI thread. Anything that touches wx goes through
`ToolContext::run_ui()`. It posts a closure through `UiInvoker` to a `UiDispatcher`, then waits.
The dispatcher is `wxApp::CallAfter` in the app and a queue the test drains in tests. The closure
holds only shared state, never the caller's stack, so it can run safely after the caller gives up.
A closure still queued after 10 s is abandoned without running, and the call fails saying it was
not run and is safe to retry.
`GuardClass` decides what may run when:
| Class | Tools | Runs behind a modal or inside another call |
|---|---|---|
| `Inspect` | get_state, wait, get_log, list tools, get_settings, screenshot, ui_snapshot | yes |
| `Recover` | dialog_respond, dialog_auto_answer, GUI input aimed at the topmost modal | yes |
| `Mutate` | everything else | no |
The closure checks the guards on the UI thread, since the app can change between posting and
running. A closing app or a stopped service fails the call with "shutting down". A frame being
recreated fails it with "retry". A mutate call is refused while a modal dialog is open, and the
refusal lists the dialogs. It is also refused when it would run inside another UI call's nested
event loop: a modal, `ProgressDialog::Update` or `wxYield`. The GUI input tools (`ui_click`,
`ui_input`, `ui_key`) and `dialog_respond` run as recover calls. Once a target resolves outside the
topmost modal, they apply the mutate checks themselves (`UiInvoker::require_mutate()`), along with
operation admission.
`ToolDef::inline_call` decides where a call runs. Pure observation tools run on the request
thread. Every tool that can activate UI runs as a job on its own thread, recover tools that click
in dialogs included, since a click can open another modal (Preferences, Keyboard shortcuts, Edit).
`JobRegistry` names jobs `j1`, `j2`, …, records each job's tool and parent, allows 64 running and
keeps the last 64 results. The request thread waits up to `ToolDef::budget_ms` (45 s, under
Codex's 60 s tool timeout); after that the reply is `{status: "running", job, tool, note}` and the
job keeps going until `wait {for: "job"}` (at most 50 s per call) returns its result. The server
never retries a mutating call, and every envelope tells the model not to either.
**blocked_by_dialog.** A handler that opens a modal blocks in its nested loop, so every 1.5 s the
request thread posts a probe closure, which runs inside that loop and returns the `ModalTracker`
snapshot as JSON; no `wxDialog*` crosses threads. With a modal open, the reply is
`{status: "blocked_by_dialog", job, dialogs}`. A probe unanswered within 1 s changes nothing.
**Blocking slots.** A request that may block (an inline call, or a job call within its budget)
first takes one of 32 slots. Without one, a job call returns its `running` envelope at once and an
inline call returns `{status: "pending"}`, so at most 32 request threads ever block, well under the
64-connection cap.
### Operations
Slicing and G-code export finish in the background process. Their handlers call
`ToolContext::begin_operation()` and start the work in one short UI closure. `poll_ui()` then checks
on it from a UI closure every 200 ms, until the work ends or the deadline passes. The deadline is
`slice.timeout_s` (default 30 minutes) for a slice and 10 minutes for an export.
**Admission.** While an operation job runs, every other `Mutate` call is refused ("Busy: job j12 (a
slice or export) is running"), whichever client or script sends it. So an agent can't change the
project under its own operation. Inline tools, recover tools and `allowed_during_operation` tools
(`cancel`) still run.
**Identity.** An operation must never take another's completion for its own. `Plater` numbers
slice requests (`slice_request_seq`, bumped through `request_slice()` by every user-facing slice
entry point, not by internal restarts) and background runs (`slice_run_seq`), keeping a
`SliceRunRecord` per run with the project revision and request sequence at its finish.
`Plater::project_revision()` rises with every undoable model edit, undo/redo, load, new project and
config change. A slice ticket ends once nothing slices and it either saw slicing run or waited
1.5 s with nothing scheduled. It is `superseded` when another request or a revision change came
during its own runs (or, with none, by the final poll); otherwise each plate is `ok`, `error`,
`cancelled`, `empty` or `skipped`. An export is numbered in `export_seq` once scheduled, so an
unchanged number means it never started; otherwise its `ExportRecord` ends `ok`, `failed`,
`cancelled` or `superseded`. A G-code export with a path is refused while slicing runs. The
decision logic is in `McpOperations`, which uses neither wx nor `Plater`.
**Idle.** `wait {for: "idle"}` holds when no modal is open, nothing slices and the UI job worker
(arrange, orient) is idle. It also needs no job running other than the caller and its ancestors,
so a script waiting for idle doesn't wait on itself. Only the job registry, the `ModalTracker`
snapshot and the journal are shared between threads, each behind a mutex. All app state is read on
the UI thread.
## Tool catalog
| Group | Tool | Purpose |
|---|---|---|
| App | `get_state` | version, platform and display backend, ready, tab, mode, project, presets, plates, objects, slicing, dialogs, notifications, jobs, window |
| | `wait` | `ready`, `idle`, `dialog`, `no_dialog` or a `job`; `timeout_s` up to 50 |
| | `get_log` | end of the current log file, filtered by minimum level |
| Speed Dial | `list_actions` | search the action catalog, paged |
| | `run_action` | run an action by id, with its optional `param` |
| Project | `open_files` | load models, a project or G-code by absolute path, with no dialog |
| | `new_project` | start an empty project (`discard_changes` if it has unsaved changes) |
| | `save_project` | save the project as `.3mf` to a path |
| | `export` | `gcode`, `sliced_3mf`, `3mf` or `stl` to a path; `gcode` is an export operation |
| Presets | `list_presets` | printer, process or filament presets with flags, paged |
| | `select_preset` | select by name through the selector (filament per slot) |
| | `get_settings` | values and metadata of a preset, or of an object's or part's overrides |
| | `set_settings` | set values the way the settings tab does, all or none; object and part overrides |
| Objects | `list_objects` | objects, instances, parts, bounding boxes, overrides, paged |
| | `select` | select objects, instances or parts, all, or none |
| | `transform` | translate, rotate or scale one instance, relative or absolute |
| Slice | `slice` | current, one or all plates; outcome and stats for each plate |
| | `cancel` | stop the running slice or G-code export; allowed during an operation |
| View | `set_view` | tab, camera, preview layers and color scheme, window size |
| | `screenshot` | window, 3D canvas or topmost dialog: a downscaled image and a full-size PNG |
| GUI | `ui_snapshot` | widgets, menus, GL toolbar items, gizmos and ImGui items, with refs |
| | `ui_click` | activate a ref or locator |
| | `ui_input` | set a control's text, value, selection or checked state |
| | `ui_key` | send a key chord to a target or the focused window |
| | `ui_mouse` | canvas gestures: move, down, up, click, drag, wheel |
| | `dialog_respond` | press a button of the topmost wx dialog |
| | `dialog_auto_answer` | answer matching modals before they show, and one already open |
| | `webview_eval` | run JavaScript in a web view and return the result |
| Scripts | `run_script` | run a script file or inline script, with results per step |
| | `export_script` | write the session journal as a script that can be replayed |
| CAD | `cad_call` | forward to the Design tab's control surface (CAD builds, Design tab enabled) |
Each tool family registers itself from its own `McpTools*.cpp` through `register_*_tools()`.
List tools take `limit` and `offset` and report `total` and `next_offset`. `McpPaths.hpp` requires
absolute paths, since a relative one would resolve against `<datadir>/log`, the GUI's working
directory; an output's directory must exist, and an existing file is replaced only with
`overwrite: true`.
## Speed Dial catalog
`list_actions` and `run_action` serve the Speed Dial's `ActionRegistry`: built-in commands, plates,
recent projects, plugin scripts and pages, and, on request, settings. Built-in commands are
`NativeCommand`s in `NativeCommands.cpp`, with three fields for automation that the palette never
shows: `description` (English, for agents), `param` (a `CommandParam {type, help}`, typed `None`,
`Percent`, `Tab`, `Path`, `Index` or `Text`) and `completion` (`Export` when the effect finishes in
the background after `run()` returns). `describe_commands()` fills them from one table, with a
key-prefix rule for calibration wizards, camera views and primitives, and `CommandAction` copies
them into the `AppAction`. The palette keeps `input` for its picker and never passes a path.
`ActionRegistry::describe(Query)` searches id, title, group, source and description, including the
English aliases. It can filter by group, lists settings only when asked, sorts by group and title,
and returns one page. Each entry has `id`, the English `title` and `group`, `kind`, `description`,
`param {type, help}`, and `completes: "export"` for exports. Built-in ids look like
`orca_command:<key>:orca`. `run_action` calls `ActionRegistry::run(id, param, record_stats=false)`,
so agent runs never reorder the palette. An unknown id returns up to three close ids. An action
with `completes_in_background` that gets a path runs as an export operation and completes when the
file is written.
Given a path, a command with a `Path` param skips its file dialog and calls an entry point that has
none. Without a param, it behaves as it does in the palette. The param is an absolute path, or, for
outputs, a JSON object string `{"path": "...", "overwrite": true}`. `path_param()` resolves it and
turns a bad path into an Error result.
| Command | Takes | Entry point |
|---|---|---|
| `load_project` | `.3mf` | `Plater::load_project(path)`; still asks about unsaved changes |
| `import_file` | model file | `Plater::load_files({path})` |
| `import_configs` | `.ini` or `.json` | `MainFrame::load_config_file(path)` |
| `save_project_as` | output `.3mf` | `Plater::save_project(true, path)` |
| `export_gcode` | output `.gcode` | `Plater::export_gcode_to(path)`; completion `Export` |
| `export_sliced_file`, `export_all_sliced_file` | output `.gcode.3mf` | `Plater::export_gcode_3mf(all, path)` |
| `export_stl` | output `.stl` | `Plater::export_stl(..., path)` |
| `export_3mf` | output `.3mf` | `Plater::export_core_3mf(path)` |
| `export_stl_multi` | existing directory | `Plater::export_stl(..., multiple, dir)` |
Commands that still open a dialog, such as `export_config` or `plate_rename`, return
`blocked_by_dialog`, and the agent answers the dialog.
### Making a feature reachable
Most features need only a Speed Dial command:
1. Add it to `build_command_catalog()` with a key, title, group and runner. Give it a row in
`describe_commands()` with an English description of what it does and what it returns.
2. If it opens a file dialog, give it a `Path` param with help text. Given a param, the runner
resolves it with `path_param()` and calls an entry point that shows no dialog. It must not
prompt; it returns an Error result instead.
3. If the effect finishes in the background after `run()` returns, set
`CommandCompletion::Export` so that `run_action` waits for the file.
The command then appears in the palette, in `list_actions` and `run_action`, and in scripts.
When an agent needs structured arguments or results, or has to wait for the effect, add a typed
tool to the matching `McpTools*.cpp`. Use `inspect_tool()` for pure observation, which runs inline,
read-only and unjournaled. Use `mutate_tool()` for anything that changes the app; it runs as a
journaled job under the mutate guard and may be marked `destructive`. Build the schema with
`object_schema()`, `prop()`, `enum_prop()` and `array_prop()`. It is validated before the handler
runs, so `arg_string()` and its siblings can read the arguments. Do all wx work in `ctx.run_ui()`,
and get the plater with `ui_plater()`, which fails until the main window is up. Throw `ToolFailure`
with a message the model can act on. Call `settle()` after a change so queued events are handled
before the reply, and page lists with `page()`. For work that finishes later, call
`ctx.begin_operation()`, wait with `poll_ui()`, and give the work an identity, as slicing and
export do. Describe the tool in English, including what the reply holds and when it is a job.
## GUI automation
`ui_snapshot` (`UiInspector`) returns a compact text tree of the shown top-level windows, the
menus, the GL toolbar items and gizmos, and each canvas's last-frame ImGui items, capped by
`max_nodes` and filtered by `query`. The tree is a second text block of the result. Refs (`w`, `m`,
`t`, `z`, `g` plus a number) are never reused and carry the UI generation and a liveness check, so a
ref to a destroyed or rebuilt widget is reported stale. A field is named by the setting it edits:
its option key is read from the "parameter name" line of its tooltip, and its label comes from the
option's definition. Failing that, the label to its left on the same row names it, then its
tooltip.
Input tools take a `target`: a ref, or a locator, which is stable across runs and is what the
journal stores. A locator is one of:
- `{option: "layer_height"}` for a setting field;
- `{label, class, name, within, index}` for other widgets;
- `{menu: "File>Export>Export G-code"}`, `{gltoolbar: "arrange"}` or `{gizmo: "Move"}`;
- `{imgui: "label", window, canvas}` for an ImGui item.
A label that matches both a row's label and the one field it names resolves to the field. Before
acting, a widget is scrolled into view, as a person would. On GTK this goes through the scrolled
window's adjustment, as the mouse wheel does, because `wxScrollHelper::Scroll()` leaves native
labels unpainted.
Activation prefers a widget's own dispatch: `wxEVT_MENU`, `GLToolbar::force_left_action()`,
`GLGizmosManager::open_gizmo()`, a native control's semantic event, or a custom widget's public API.
Canvas gestures and ImGui items get synthesized wx events with a render between steps.
`ImGuiWrapper::set_item_recording()` supplies the ImGui items with their rectangles and checked
state. `SyntheticInput` holds a gesture's keys, buttons and pointer for canvas code that reads
hardware state through `get_key_state()` and `get_mouse_state()`. Keys without a target go to the
focused window inside the topmost modal, else that modal, else the focused window, else the 3D
canvas.
`ModalTracker`, a `wxModalDialogHook`, sees every `ShowModal()`, native dialogs included, and
publishes the snapshot `[{title, message, class, native, buttons}]`. `dialog_respond` presses the
topmost wx dialog's button, so the dialog's own handler runs, or ends the dialog with that id when
no such button exists. A native dialog can only be answered ahead with a `dialog_auto_answer` rule:
a regex over title and message, and a button. `Enter()` then returns that button's id without
showing the dialog, and logs it; file dialogs can only be cancelled. A new rule also answers a
matching wx dialog that is already open. A prompt posted around the same time, such as the restore
prompt after startup, is handled whether it opens before or after the rule. A script's rules end
with the script, a client's call replaces its earlier rules, and `get_state` lists the rules in
force. `webview_eval` runs JavaScript with `RunScriptAsync` and waits for the result event, up to
`timeout_s` (default 10); a JSON result comes back parsed.
## Screenshots
`screenshot` captures on the UI thread and encodes off it. It has three targets.
- `canvas`: the visible 3D view, exactly as drawn, toolbars and ImGui panels included, on every
platform. `GLCanvas3D::render_and_capture()` forces a frame and reads the back buffer just before
the swap; it fails, saying why, when the canvas is hidden or mid-frame.
- `window`: the main window's own pixels, never the screen, from `capture_native_window()`, with
every visible 3D canvas composited in from its canvas capture, since window capture loses OpenGL
content on several platforms.
- `dialog`: the topmost modal, captured like a window.
When the capture may differ from the screen, the result carries `approximate: true` and a `note`.
| Platform | Window capture | Approximate when |
|---|---|---|
| Windows | `PrintWindow(PW_CLIENTONLY \| PW_RENDERFULLCONTENT)` | `PrintWindow` fails and the screen is copied instead |
| macOS | `cacheDisplayInRect:toBitmapImageRep:` on the content view | always: web views may be blank |
| Linux X11, Xvfb, XWayland | `XGetImage` of the top-level X window | part of it is off-screen or under another application's window |
| Linux Wayland | `gtk_widget_draw()` of the top-level window | always: web views may be blank |
On every platform, a canvas that can't be captured keeps whatever the window capture drew, and the
result is approximate. Minimized and hidden windows fail. X11 keeps no backing store, so a part
covered by another window reads back black. OrcaSlicer's own popups and tooltips stacked above the
window are read and drawn in, as they appear on screen; another application's window leaves the
hole, and the result is approximate. The full-size PNG goes to `save_path` or `<datadir>/mcp/out/screenshot-<timestamp>.png`. The image
block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–2000).
`include_image: false` returns only the path.
## Scripts and the journal
```jsonc
{ "orca_script": 1, "name": "repro #12345",
"vars": {"model": "${script_dir}/part.stl"},
"steps": [
{"tool": "open_files", "args": {"paths": ["${vars.model}"]}},
{"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}},
{"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca"}, "await": false, "save_as": "prefs"},
{"tool": "dialog_respond", "args": {"dialog": {"title": "Preferences"}, "button": "close"}},
{"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}},
{"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}}
]}
```
A script is JSON with comments allowed. `run_script` runs a file or an inline script as a job whose
steps call tools as its children (`ToolContext::call_child()`), so steps are not journaled and a
script's `wait {for: "idle"}` doesn't wait for the script. Every string is substituted recursively
with `${script_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and `${jobs.NAME}`; a string that
is just one placeholder becomes the referenced JSON value. A step that returns a job is awaited,
up to `timeout_s` (default 120), before its `expect` is checked. `"await": false` returns the job
at once and stores it under `save_as`, so later steps can answer a dialog it opened and then
`wait` for it. `expect` maps JSON pointers into the result to matchers (`eq ne gt ge lt le contains
regex exists empty`). A failed step or expectation stops the run unless the step is `optional`.
Auto-answer rules registered by a script end with it. `vars` passed to `run_script` override the
script's. A step naming an unknown tool makes the script invalid before anything runs. The result,
also written to `<out_dir>/result.json`, is
`{passed, name, failed_step, steps: [{index, tool, args, ok, result | error, expect_failure}],
out_dir, result_file}`. A script file's `out_dir` defaults to `<script name>.out` beside it. An
inline script's defaults to `<datadir>/mcp/out/script-<timestamp>`, which is also its
`${script_dir}`.
`orca-slicer --mcp-script FILE [--mcp-script-out DIR]` runs a script once the GUI is ready. It
doesn't open the endpoint unless `--mcp` is also given. It writes `result.json` and screenshots to
the output directory, which defaults to `<script name>.out` next to the script. Then it closes the
app without prompting and exits 0 if the script passed, 1 if a step failed, and 2 if the script is
invalid. `OrcaSlicer.cpp` resolves both paths against the original working directory, since the
GUI changes it. wx ignores `OnExit()`'s return value, so `GUI_Run()` returns
`McpService::script_exit_code()` after `wxEntry()`.
The session journal records client calls to journaled tools in order: every mutate tool, plus
`wait` and `screenshot`, which a replay needs. GUI tools record locators instead of refs through
`ToolContext::set_journal_args()`. `export_script` returns it, and with `path` writes it, through `Journal::to_script()`; `clear`
starts a new recording. `Journal::to_script()`
drops failed calls, turns a call that returned a job into a step with `"await": false` and
`"save_as": "jobN"`, points the `wait {for: "job"}` that followed at `${jobs.jobN}` (dropping waits
on jobs it never saw start) and rewrites screenshot paths to `${out_dir}/<file name>`.
## stdio bridge
`orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]` serves clients that speak only stdio,
such as Claude Desktop; `main` handles it before any GUI or CLI processing (`McpStdioBridge.cpp`).
It POSTs each line of JSON-RPC from stdin to the instance in the discovery file (or `--mcp-port`)
with the token and the headers `bridge_headers()` derives: `MCP-Protocol-Version` (negotiated, or
from `_meta`), `Mcp-Method`, and `Mcp-Name` for `tools/call`, `prompts/get` and `resources/read`.
Replies go to stdout; a 202 writes nothing. When nothing answers, it starts `orca-slicer --mcp`
detached and waits up to 60 s. If that process exits within seconds, a running instance without
MCP took the launch over, and every request is answered with an error saying to turn the server
on in Preferences. A request that could not be sent, or was refused with 401 because the token
changed, is sent once more to the endpoint the discovery file names now: the app restarted, or its
port or token changed in Preferences. A request that was sent but lost its reply is never sent
again, since it may have run. The client gets an error saying so, and later requests go to the new
endpoint.
## Configuration
The CLI options are in `CLIMiscConfigDef`, so the GUI still starts: `--mcp`, `--mcp-port N`,
`--mcp-token T`, `--mcp-script FILE`, `--mcp-script-out DIR` and `--mcp-stdio`. The AppConfig `app`
section holds `mcp_enabled` (false) and `mcp_port` (13619). Preferences › General › Features has
three rows:
- **"MCP server for AI agents"**: checked while the server runs, with its URL or the reason it
could not start.
- **"MCP server port"**.
- **"Connect an AI agent"**, with two buttons. "Copy setup command" copies
`claude mcp add --scope user orcaslicer -- "<executable>" --mcp-stdio`, which uses the AppImage's
own path inside an AppImage. It holds no token, so it keeps working after port and token
changes. "New token" renews the token and reopens the endpoint.
## Testing
Unit tests are Catch2 cases tagged `[Mcp]` in `tests/slic3rutils/test_mcp_*.cpp`, run with
`slic3rutils_tests "[Mcp]"`. `test_mcp_protocol` covers both eras and argument validation;
`test_mcp_http` the endpoint rules and a live server (deadlines, eviction, stop); `test_mcp_core`
`UiInvoker`, `McpCore` and `JobRegistry` on a hand-stepped dispatcher (guards, abandoned calls,
jobs, blocked_by_dialog, admission, slots, idle, journal); `test_mcp_operations` the slice and
export outcomes; `test_mcp_script` parsing, substitution, matchers and await; `test_mcp_ui` labels,
snapshot text, ref liveness and synthetic key state. End to end, `tools/mcp/orca_mcp.py` launches
the app on a private Xvfb display (with `-noreset`, and the pointer parked in a corner so no tooltip
lands in a screenshot) and runs `tools/mcp/smoke_test.json`. `tools/mcp/tests/script_basic.json`
checks `--mcp-script` headless, and `tools/mcp/test_stdio_bridge.py` the stdio bridge. See `tools/mcp/README.md` and the `orca-mcp` skill.
+78
View File
@@ -0,0 +1,78 @@
# MCP harness
`orca_mcp.py` launches OrcaSlicer with its MCP server and talks to it, from a shell or from
Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the server, and
`.claude/skills/orca-mcp/SKILL.md` covers the agent workflow.
## Commands
| Command | What it does |
|---|---|
| `launch [--xvfb] [--printer "<model>@<nozzle>"] [--vendor V] [--filament F] [--datadir DIR] [--port N] [--bin PATH] [--print-config] [-- app args]` | Start OrcaSlicer with `--mcp`, wait until it is ready, print the session |
| `call TOOL ['<json args>'] [--wait]` | Call a tool and print its JSON result; `--wait` follows a returned job to its result |
| `tools` | List the tools, with the first line of each description |
| `snapshot ['<json args>']` | Print the `ui_snapshot` tree |
| `screenshot OUT [--target window\|canvas\|dialog]` | Save a full-size PNG, replacing `OUT` if it exists |
| `run-script FILE [--out DIR]` | Run a script in the launched instance and print the result; exit 0 when it passes |
| `stop` | Stop the app and its Xvfb, and remove the session |
`launch` creates a fresh temporary datadir unless you pass `--datadir`. It seeds the datadir with
an `OrcaSlicer.conf` that has a finished setup wizard and one printer and filament (Bambu Lab X1
Carbon 0.4 by default), with update checks and daily tips turned off. The token comes from
`ORCA_MCP_TOKEN` or is generated, and it reaches the app through the environment, not the command
line. On Linux, `launch` also sets `SSL_CERT_FILE`, so a fresh datadir doesn't prompt for a CA
bundle. `--xvfb` starts Xvfb on a free display between `:90` and `:119`, with
`--width`×`--height` (default 1600×1000), and sets `GDK_BACKEND=x11`. Xvfb runs with `-noreset`,
and its pointer is parked in the bottom-right corner. In the middle of the screen, the pointer would
raise tooltips over whatever opens there, and they would show in screenshots. The app's output goes to
`<datadir>/mcp-launch.log`. `--timeout` (default 120 s) limits how long `launch` waits for
`ready`.
## Session file
`launch` writes `{port, token, pid, datadir, xvfb_pid, display}` to `$ORCA_MCP_SESSION`, or to
`~/.cache/orca-mcp/session.json` if that is unset. The file is mode 0600, and every other command
reads it. To run several instances at once, give each its own `ORCA_MCP_SESSION` and `--port`.
## From Python
```python
import os, sys
sys.path.insert(0, "tools/mcp")
from orca_mcp import OrcaMcp, McpError
orca = OrcaMcp(port=13619, token=os.environ["ORCA_MCP_TOKEN"])
orca.call("open_files", paths=["/abs/path/part.stl"])
result = orca.await_job(orca.call("slice")) # follows a job envelope to the end
orca.call("wait", **{"for": "idle"}) # "for" is a Python keyword
info, pngs = orca.images("screenshot", target="canvas")
```
`call()` returns the tool's JSON result and raises `McpError` when the tool reports an error.
`call_with_text()` also returns the text blocks after the JSON one, such as `ui_snapshot`'s tree.
`images()` also returns the PNG bytes of the image blocks. `call_raw()` returns the MCP result
unchanged.
## Smoke test
`smoke_test.json` is an end-to-end script that exercises the main paths against a fresh datadir:
- an auto-answered startup or unsaved-changes prompt;
- loading, a setting change, slicing and a G-code export;
- a dialog that an action opens and the script answers;
- screenshots of the dialog and the preview.
```bash
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/orca_mcp.py run-script tools/mcp/smoke_test.json --out /tmp/orca-smoke
tools/mcp/orca_mcp.py stop
```
Without the harness, `orca-slicer --datadir DIR --mcp-script tools/mcp/smoke_test.json
--mcp-script-out /tmp/orca-smoke` runs the script and exits. The exit code is 0 when it passes, 1
when a step fails and 2 when the script is invalid. The run leaves `result.json` and the
screenshots in the output directory. `tests/script_basic.json` is the smallest such check: load,
change a setting, slice and capture.
`test_stdio_bridge.py [--bin PATH]` checks `orca-slicer --mcp-stdio` against the launched instance:
the handshake, notifications, tool calls in both protocol eras, and errors.
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Checks `orca-slicer --mcp-stdio` against an instance started with `orca_mcp.py launch`.
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/test_stdio_bridge.py [--bin build/src/Release/orca-slicer]
The bridge finds the instance through the discovery file in the launch's datadir, so this also
checks that file. Exits 0 when every check passes.
"""
import argparse
import json
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import orca_mcp # noqa: E402
def bridge(binary, datadir, lines, env):
"""Feeds `lines` to one bridge process and returns its replies by id."""
proc = subprocess.run([binary, "--mcp-stdio", "--datadir", datadir], input="\n".join(lines) + "\n",
capture_output=True, text=True, timeout=120, env=env)
replies = {}
for line in proc.stdout.splitlines():
msg = json.loads(line)
replies[msg.get("id")] = msg
return replies
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--bin", help="orca-slicer binary (default: the one launch found)")
args = parser.parse_args()
_, session = orca_mcp.session_client()
binary = orca_mcp.find_binary(args.bin)
# The bridge must find the token on its own, in the discovery file.
env = {k: v for k, v in os.environ.items() if k != "ORCA_MCP_TOKEN"}
env.setdefault("DISPLAY", session.get("display") or "")
legacy = "2025-06-18"
modern = "2026-07-28"
replies = bridge(binary, session["datadir"], [
json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": legacy, "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}}}),
json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}),
json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "get_state", "arguments": {}}}),
"{not json",
json.dumps({"jsonrpc": "2.0", "id": 4, "method": "tools/call",
"params": {"name": "get_state", "arguments": {},
"_meta": {"io.modelcontextprotocol/protocolVersion": modern}}}),
json.dumps({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "no_such_tool", "arguments": {}}}),
], env)
failures = []
def check(name, ok, detail=""):
print(("ok " if ok else "FAIL ") + name + ("" if ok else f": {detail}"))
if not ok:
failures.append(name)
init = replies.get(1, {}).get("result", {})
check("initialize negotiates the client's version", init.get("protocolVersion") == legacy, replies.get(1))
check("the notification gets no reply", set(replies) <= {1, 2, 3, 4, 5, None}, sorted(map(str, replies)))
names = [t["name"] for t in replies.get(2, {}).get("result", {}).get("tools", [])]
check("tools/list lists get_state and ui_snapshot", "get_state" in names and "ui_snapshot" in names, names[:5])
state = json.loads(replies.get(3, {}).get("result", {}).get("content", [{}])[0].get("text", "{}"))
check("get_state answers through the bridge", state.get("ready") is True, state)
check("malformed input is a parse error", replies.get(None, {}).get("error", {}).get("code") == -32700, replies.get(None))
modern_result = replies.get(4, {}).get("result", {})
check("a 2026-07-28 request is served without a handshake", modern_result.get("resultType") == "complete", replies.get(4))
check("an unknown tool is a JSON-RPC error", replies.get(5, {}).get("error", {}).get("code") == -32602, replies.get(5))
print("passed" if not failures else f"{len(failures)} failed")
return 0 if not failures else 1
if __name__ == "__main__":
sys.exit(main())