Launch MCP harness instances on a private headless desktop on Linux, falling back to Xvfb

This commit is contained in:
SoftFever committed 2026-11-11 17:32:05 +08:00
1 parent 693b018dd3
commit ef301e132d
7 files changed
+182 -45

No files matched your search

+4 -2
View File
@@ -3408,8 +3408,10 @@ per-variant entries and their writes, preset comparison, `changed`, which unsave
flushing multipliers and matrix, and the plate scope's filament orders and layer ranges and
`list_plates`' layer numbers and layer G-codes, the preferences scope's keys, and `generate_calibration_test`'s arguments,
defaults, the dialogs' shared rules, VFA's auto-adjust and the parameters the journal records. End to end, `tools/mcp/orca_mcp.py` launches
the app on a private Xvfb display on Linux (with `-noreset`, and the pointer parked in a corner so no
tooltip lands in a screenshot), or on the desktop on macOS and Windows, and runs
the app on Linux on the XWayland of a private headless compositor (KWin, else mutter, which is not
tested yet), which gives it the GPU's OpenGL and a window manager, or, on a machine without a desktop,
on a private Xvfb display (with `-noreset`, and the pointer parked in a corner so no tooltip lands in
a screenshot); on macOS and Windows it opens the app on the desktop. It runs
`tools/mcp/smoke_test.json`. `tools/mcp/tests/replay_basic.json`
checks `--mcp-run` headless, `tools/mcp/tests/gizmos.json` every gizmo through the GUI tools,
`tools/mcp/tests/multicolor.json` object and part filaments and the project scope, `tools/mcp/tests/presets.json` saving,
+29 -13
View File
@@ -7,13 +7,13 @@ Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the
| Command | What it does |
|---|---|
| `launch [--xvfb] [--cad] [--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 |
| `launch [--headless [kwin\|mutter] \| --xvfb] [--cad] [--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 |
| `widgets ['<json args>']` | Print the `list_widgets` tree |
| `screenshot OUT [--target window\|canvas\|dialog]` | Save a full-size PNG, replacing `OUT` if it exists |
| `run-replay FILE [--out DIR]` | Run a replay in the launched instance and print the result; exit 0 when it passes |
| `stop` | Stop the app and its Xvfb, and remove the session |
| `stop` | Stop the app and its private display, 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
@@ -27,18 +27,34 @@ your own OrcaSlicer uses, and finds `build-clang\src\Release\orca-slicer.exe` as
commands as `python tools/mcp/orca_mcp.py …`. On macOS, it finds the app bundle's binary under
`build/arm64`, `build/x86_64`, `build/universal` or `build`: the bundle the CMake target builds in
`src/Release`, or the one `build_release_macos.sh` assembles in `OrcaSlicer`. The app opens on the
desktop and takes focus while it starts, and needs no CA-bundle setting. `--xvfb` is Linux only. It
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`.
desktop and takes focus while it starts, and needs no CA-bundle setting.
On Linux, `--headless` and `--xvfb` keep the app off your desktop, on a private screen of
`--width`×`--height` (default 1600×1000), and run it as an X11 client (`GDK_BACKEND=x11`). Use
`--headless` on a machine with a desktop. It starts a headless Wayland compositor on a session bus of
its own and runs the app on that compositor's XWayland. The app draws with the GPU's OpenGL driver,
as on your desktop, and the compositor is a window manager, so focus, stacking and popup lists
behave as they do there; dialogs show in screenshots and recordings, and the private bus keeps the
D-Bus services the app starts, such as the desktop portals, out of your session. It takes KWin
(`kwin_wayland --virtual`), else mutter (`mutter --headless`; test required: not yet run on a GNOME
machine, so check the window, input, screenshots and the OpenGL driver the app's log reports before
relying on it); `--headless kwin` or `--headless mutter` names one. The compositor's output goes to
`<datadir>/mcp-display.log`. When neither is installed or starts, `--headless` says so and falls
back to Xvfb. `--xvfb` is for a machine without a desktop, such as a CI runner or a server. It
starts Xvfb on a free display between `:90` and `:119`, which draws OpenGL in software and runs no
window manager, so a popup list, such as a combo box's drop-down or the Print button's menu, closes
as soon as it opens. 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
`launch` writes `{port, token, pid, datadir, display_server, display_server_pid, display_env,
display}` to `$ORCA_MCP_SESSION`, or to `~/.cache/orca-mcp/session.json` if that is unset.
`display_server` is `kwin`, `mutter`, `xvfb` or null (your desktop), and `display_env` holds the
variables the app was started with to reach it (null for one removed), which `app_env()` applies to
another process. 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
@@ -100,7 +116,7 @@ arguments.
- screenshots of the dialog and the preview.
```bash
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/orca_mcp.py launch --headless
tools/mcp/orca_mcp.py run-replay tools/mcp/smoke_test.json --out /tmp/orca-smoke
tools/mcp/orca_mcp.py stop
```
@@ -363,7 +379,7 @@ with nobody pressing Escape.
`tests/rows.json` drives rows and popups: object list rows (plates, an object and its parts, Ctrl
to add a row, the Printable column, a double click), the object's and a part's menus run from their
rows, Compare presets' rows, the object settings table, the print button's popup and the plate type
drop-down list.
drop-down list. On Linux run it with `--headless`: under Xvfb those popups close as soon as they open.
`tests/plate_icons.json` clicks the Prepare view's plate icons by `{plate_icon, plate}`: lock twice,
Plate Settings opened and cancelled, arrange of a second plate's two cubes (the reply waits for the
+143 -24
View File
@@ -7,7 +7,8 @@ Standard library only. Two halves:
``OrcaMcp.from_datadir()`` attaches to an OrcaSlicer already running with the server on.
* A command line that launches OrcaSlicer for an agent or a test and talks to it::
tools/mcp/orca_mcp.py launch --xvfb # fresh datadir, wait until ready, print client config
tools/mcp/orca_mcp.py launch --headless # fresh datadir on a private headless desktop (Linux), wait until ready
tools/mcp/orca_mcp.py launch --xvfb # on a private Xvfb display, for a Linux machine without a desktop
tools/mcp/orca_mcp.py launch --cad # with the Design (CAD) tab on, for the CAD tools (list_cad_tools, call_cad_tool)
tools/mcp/orca_mcp.py call get_app_state
tools/mcp/orca_mcp.py call open_files '{"paths": ["/abs/model.stl"]}'
@@ -25,6 +26,7 @@ import base64
import json
import os
import platform
import shlex
import shutil
import signal
import subprocess
@@ -277,6 +279,115 @@ def seed_datadir(datadir, printer, cad=False):
"app": app})
# The headless compositors --headless tries, in order, by the binary each needs.
COMPOSITORS = {"kwin": "kwin_wayland", "mutter": "mutter"}
def start_headless(compositor, width, height, datadir):
"""Start `compositor` headless with XWayland on a private session bus, and return the variables
the app needs to run on it as an X11 client and the process group to stop, or None when it did
not come up (its output is in <datadir>/mcp-display.log).
Unlike Xvfb, the app draws with the GPU's OpenGL driver, and a window manager runs, so focus and
stacking behave as on a desktop and popup lists stay open; with no window manager, GDK moves the
focus to a drop-down list itself, which deactivates the main window and closes the list. The private bus keeps the D-Bus services the app starts, such as
the desktop portals, out of the person's session. Only the compositor knows its XWayland display,
so it starts a command that writes its environment to a file.
Headless mutter is not tested yet: its command line and whether it renders on the GPU still need
checking on a GNOME machine."""
env_file = os.path.join(datadir, "mcp-display.env")
if os.path.exists(env_file):
os.remove(env_file)
keys = ("DISPLAY", "WAYLAND_DISPLAY", "DBUS_SESSION_BUS_ADDRESS", "XAUTHORITY")
report = 'printf "%s\\n" ' + " ".join(f'"{k}=${k}"' for k in keys) + ' > "$0.tmp" && mv "$0.tmp" "$0"'
socket = f"orca-mcp-{os.getpid()}"
if compositor == "kwin":
# KWin starts the command detached, outside the process group stop() ends, so the command
# exits once it has written the file; XWayland stays up without it.
cmd = ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height), "--socket", socket,
"--xwayland", shlex.join(["sh", "-c", report, env_file])]
else:
# mutter quits when its command exits, so the command stays, in mutter's process group.
cmd = ["mutter", "--headless", "--wayland", "--virtual-monitor", f"{width}x{height}", "--wayland-display", socket,
"--", "sh", "-c", report + "; exec sleep infinity", env_file]
with open(os.path.join(datadir, "mcp-display.log"), "w") as log:
proc = subprocess.Popen(["dbus-run-session", "--"] + cmd, stdout=log, stderr=subprocess.STDOUT,
start_new_session=True)
deadline = time.time() + 30
while not os.path.exists(env_file) and proc.poll() is None and time.time() < deadline:
time.sleep(0.1)
if os.path.exists(env_file):
with open(env_file) as f:
env = {k: v or None for k, _, v in (line.partition("=") for line in f.read().splitlines())}
os.remove(env_file)
if env.get("DISPLAY"):
return dict(env, GDK_BACKEND="x11"), proc.pid
stop_group(proc.pid)
return None
def start_display(args, datadir):
"""The private display `launch` runs the app on, as (server name, variables for the app, process
group to stop), or (None, None, None) for the desktop the harness runs in.
--headless takes the first headless compositor that is installed and starts, and falls back to
Xvfb when none does, as on a machine without a desktop; --xvfb takes Xvfb."""
if (args.headless or args.xvfb) and not sys.platform.startswith("linux"):
sys.exit("--headless and --xvfb run only on Linux; elsewhere the app opens on the desktop")
if args.headless:
explicit = args.headless != "auto"
for name in [args.headless] if explicit else list(COMPOSITORS):
missing = [b for b in (COMPOSITORS[name], "dbus-run-session") if not shutil.which(b)]
if missing:
if explicit:
sys.exit(f"--headless {name} needs {' and '.join(missing)}, which is not installed")
continue
if name == "mutter":
print("headless mutter is not tested yet (test required): check the window, input, screenshots "
"and that get_log reports the GPU's OpenGL driver", file=sys.stderr)
started = start_headless(name, args.width, args.height, datadir)
if started:
return (name,) + started
message = f"{COMPOSITORS[name]} did not start; see {os.path.join(datadir, 'mcp-display.log')}"
if explicit:
sys.exit(message)
print(message, file=sys.stderr)
print("no headless compositor started, so the app runs on Xvfb: software OpenGL, no window manager",
file=sys.stderr)
if args.headless or args.xvfb:
if not shutil.which("Xvfb"):
sys.exit("Xvfb is not installed")
display, pid = start_xvfb(args.width, args.height)
return "xvfb", {"DISPLAY": display, "GDK_BACKEND": "x11", "WAYLAND_DISPLAY": None}, pid
return None, None, None
def stop_group(pid, timeout=5, force=True):
"""End the process group `pid` leads: SIGTERM, then wait up to `timeout` s for it to go, and
SIGKILL what is left when `force`."""
try:
os.killpg(pid, signal.SIGTERM)
except OSError: # already gone
return
deadline = time.time() + timeout
while time.time() < deadline:
try:
os.waitpid(pid, os.WNOHANG) # reaps the leader when this process started it
except ChildProcessError:
pass
try:
os.killpg(pid, 0)
except OSError:
return
time.sleep(0.1)
if force:
try:
os.killpg(pid, signal.SIGKILL)
except OSError:
pass
def start_xvfb(width, height):
for display in range(90, 120):
if not os.path.exists(f"/tmp/.X11-unix/X{display}") and not os.path.exists(f"/tmp/.X{display}-lock"):
@@ -321,12 +432,15 @@ def park_pointer(display, width, height):
pass
def app_env(env, datadir, xvfb_display=None):
"""Adds to `env` what OrcaSlicer needs to start unattended with `datadir`: the Xvfb display when
given one, the CA bundle on Linux and a WebView2 profile of its own on Windows."""
if xvfb_display:
env.pop("WAYLAND_DISPLAY", None)
env.update(DISPLAY=xvfb_display, GDK_BACKEND="x11")
def app_env(env, datadir, display_env=None):
"""Adds to `env` what OrcaSlicer needs to start unattended with `datadir`: the variables of the
private display start_display() gave (None removes one), the CA bundle on Linux and a WebView2
profile of its own on Windows."""
for key, value in (display_env or {}).items():
if value is None:
env.pop(key, None)
else:
env[key] = value
if sys.platform.startswith("linux"):
# A static OpenSSL asks at startup which CA bundle to trust unless told.
for bundle in ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt"):
@@ -340,8 +454,6 @@ def app_env(env, datadir, xvfb_display=None):
def launch(args):
if args.xvfb and not sys.platform.startswith("linux"):
sys.exit("--xvfb runs only on Linux; elsewhere the app opens on the desktop")
token = os.environ.get("ORCA_MCP_TOKEN") or base64.b16encode(os.urandom(32)).decode().lower()
datadir = os.path.abspath(args.datadir or tempfile.mkdtemp(prefix="orca-mcp-"))
printer = DEFAULT_PRINTER
@@ -351,16 +463,16 @@ def launch(args):
seed_datadir(datadir, printer, args.cad)
env = dict(os.environ, ORCA_MCP_TOKEN=token)
display = xvfb_pid = None
if args.xvfb:
display, xvfb_pid = start_xvfb(args.width, args.height)
app_env(env, datadir, display)
cmd = [find_binary(args.bin), "--datadir", datadir, "--mcp", "--mcp-port", str(args.port)] + args.extra
binary = find_binary(args.bin)
server, display_env, server_pid = start_display(args, datadir)
app_env(env, datadir, display_env)
cmd = [binary, "--datadir", datadir, "--mcp", "--mcp-port", str(args.port)] + args.extra
log = open(os.path.join(datadir, "mcp-launch.log"), "w")
proc = subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
session = {"port": args.port, "token": token, "pid": proc.pid, "datadir": datadir,
"xvfb_pid": xvfb_pid, "display": env.get("DISPLAY")}
"display_server": server, "display_server_pid": server_pid, "display_env": display_env,
"display": env.get("DISPLAY")}
os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)
with open(SESSION_FILE, "w") as f:
json.dump(session, f)
@@ -387,14 +499,16 @@ def session_client():
def stop(_args):
_, s = session_client()
kill = os.kill if os.name == "nt" else os.killpg # Windows has no process groups to signal
for key in ("pid", "xvfb_pid"):
pid = s.get(key)
if pid:
try:
kill(pid, signal.SIGTERM)
except OSError: # already gone
pass
if os.name == "nt": # Windows has no process groups to signal
try:
os.kill(s["pid"], signal.SIGTERM)
except OSError: # already gone
pass
else:
# The app goes first and is given time to close before its display does.
stop_group(s["pid"], timeout=10, force=False)
if s.get("display_server_pid"):
stop_group(s["display_server_pid"])
os.remove(SESSION_FILE)
@@ -406,7 +520,12 @@ def main():
p.add_argument("--bin")
p.add_argument("--datadir", help="data directory (default: a fresh temporary one)")
p.add_argument("--port", type=int, default=DEFAULT_PORT)
p.add_argument("--xvfb", action="store_true", help="run on a private Xvfb display (Linux)")
display = p.add_mutually_exclusive_group()
display.add_argument("--headless", nargs="?", const="auto", choices=("auto", *COMPOSITORS),
help="run on a private headless desktop with XWayland (Linux): KWin, else mutter (not tested "
"yet), else Xvfb")
display.add_argument("--xvfb", action="store_true",
help="run on a private Xvfb display (Linux), for a machine without a desktop")
p.add_argument("--width", type=int, default=1600)
p.add_argument("--height", type=int, default=1000)
p.add_argument("--printer", help="\"<model>@<nozzle>\" for a fresh datadir, e.g. \"Bambu Lab X1 Carbon@0.4\"")
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Checks that a cancel stops a slice that is still waiting to start.
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/orca_mcp.py launch --headless
tools/mcp/test_cancel_pending_slice.py
A slice requested right after a setting change first waits for the update the change scheduled
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Checks that a dialog can still be answered when stalled clients hold every connection.
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/orca_mcp.py launch --headless
tools/mcp/test_recovery_under_load.py
With Preferences open in a running job, 32 `wait` calls block on it (every blocking slot) and 32
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Checks that a session using ImGui refs whose items changed exports a replay that runs.
tools/mcp/orca_mcp.py launch --xvfb
tools/mcp/orca_mcp.py launch --headless
tools/mcp/test_ref_locator_export.py
Two refs outlive a change to what they were taken by. The Text gizmo's font button shows the font,
+3 -3
View File
@@ -1,7 +1,7 @@
#!/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/orca_mcp.py launch --headless
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
@@ -163,10 +163,10 @@ def main():
fresh = tempfile.mkdtemp(prefix="orca-bridge-launch-")
port = free_port()
orca_mcp.seed_datadir(fresh, orca_mcp.DEFAULT_PRINTER)
# The app the bridge starts gets what an instance from launch gets: the session's Xvfb display
# The app the bridge starts gets what an instance from launch gets: the session's private display
# when it has one, and a WebView2 profile in its own datadir.
launch_env = {k: v for k, v in env.items() if k != "WEBVIEW2_USER_DATA_FOLDER"}
orca_mcp.app_env(launch_env, fresh, session.get("display") if session.get("xvfb_pid") else None)
orca_mcp.app_env(launch_env, fresh, session.get("display_env"))
try:
launched = bridge(binary, fresh, [
json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize",