Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(platform-macos): TCC auto-relaunch for cua-driver-rs mcp (#1525) (#1530)

Francesco Bonacci7bf090894660
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.yml
index a8c0fc8b0a..87784e0148 100644
--- a/.github/workflows/cd-rust-cua-driver.yml
+++ b/.github/workflows/cd-rust-cua-driver.yml
@@ -176,6 +176,43 @@ jobs:
mkdir -p release/universal
lipo -create "$ARM64" "$X86" -output release/universal/cua-driver
lipo -info release/universal/cua-driver
+ - name: Assemble CuaDriverRs.app bundle
+ working-directory: libs/cua-driver-rs
+ run: |
+ # Copy the bundle skeleton (Info.plist) from scripts/ and drop
+ # the universal binary into Contents/MacOS/cua-driver. The
+ # assembled bundle goes into every directory tarball so
+ # install.sh can `ditto` it to /Applications/CuaDriverRs.app
+ # for the TCC auto-relaunch path.
+ #
+ # No codesigning at this layer — the bundle ships ad-hoc
+ # signed (the bare binary inherits whatever signature was
+ # applied at build/notarize time, currently none for the
+ # Rust port). TCC keys grants on the cdhash of the binary
+ # the user grants permission to, so ad-hoc is fine for the
+ # BETA release; production signing will land in a separate
+ # change that wires up the notarization script the way the
+ # Swift driver does.
+ VERSION="${{ steps.version.outputs.version }}"
+ mkdir -p release/CuaDriverRs.app
+ cp -R scripts/CuaDriverRs.app/Contents release/CuaDriverRs.app/Contents
+ cp release/universal/cua-driver \
+ release/CuaDriverRs.app/Contents/MacOS/cua-driver
+ chmod +x release/CuaDriverRs.app/Contents/MacOS/cua-driver
+ # Stamp the release version into Info.plist so the bundle
+ # version tracks the tag instead of whatever was last
+ # checked in. Without this the in-tree Info.plist's
+ # CFBundleShortVersionString drifts from the release tag on
+ # every cut. CodeRabbit #4.
+ plutil -replace CFBundleShortVersionString -string "$VERSION" \
+ release/CuaDriverRs.app/Contents/Info.plist
+ plutil -replace CFBundleVersion -string "$VERSION" \
+ release/CuaDriverRs.app/Contents/Info.plist
+ # Remove the .gitkeep we use in source control — it's not
+ # part of the runtime bundle.
+ rm -f release/CuaDriverRs.app/Contents/MacOS/.gitkeep
+ ls -la release/CuaDriverRs.app/Contents/MacOS
+ plutil -p release/CuaDriverRs.app/Contents/Info.plist | grep -E 'CFBundle(Short)?Version'
- name: Package
working-directory: libs/cua-driver-rs
run: |
@@ -187,11 +224,18 @@ jobs:
# that download by arch still get the universal slice
# (matches the Swift `cd-swift-cua-driver.yml` convention).
cp release/universal/cua-driver "release/${STAGE}/"
+ # Ship the .app bundle in every macOS tarball so install.sh
+ # can drop it into /Applications/CuaDriverRs.app for TCC
+ # attribution (issue #1525). Tarball callers that want only
+ # the bare binary can grab the *-binary.tar.gz below.
+ cp -R release/CuaDriverRs.app "release/${STAGE}/CuaDriverRs.app"
cp ../../LICENSE.md "release/${STAGE}/LICENSE" 2>/dev/null || true
(cd release && tar -czf "${STAGE}.tar.gz" "${STAGE}")
done
# Bare universal binary — single-file tarball matching Swift's
- # `cua-driver-${VERSION}-darwin-universal-binary.tar.gz`.
+ # `cua-driver-${VERSION}-darwin-universal-binary.tar.gz`. NO
+ # bundle here: callers that fetch the bare tarball deliberately
+ # skipped the .app workflow.
tar -czf "release/cua-driver-rs-${VERSION}-darwin-universal-binary.tar.gz" \
-C release/universal cua-driver
ls -lh release/*.tar.gz
@@ -311,10 +355,10 @@ jobs:
### Artifacts
**macOS (universal — arm64 + x86_64 in one binary, like the Swift cua-driver)**
- - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-universal.tar.gz` — directory tarball with LICENSE
- - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-arm64.tar.gz` — same universal binary, named for arm64 callers
- - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-x86_64.tar.gz` — same universal binary, named for x86_64 callers
- - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-universal-binary.tar.gz` — bare universal binary (single file at archive root)
+ - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-universal.tar.gz` — directory tarball with LICENSE + `CuaDriverRs.app` bundle (install.sh expects this layout)
+ - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-arm64.tar.gz` — same payload, named for arm64 callers
+ - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-x86_64.tar.gz` — same payload, named for x86_64 callers
+ - `cua-driver-rs-${{ steps.version.outputs.version }}-darwin-universal-binary.tar.gz` — bare universal binary (single file at archive root; **no** .app — bypasses the TCC auto-relaunch path)
**Linux**
- `cua-driver-rs-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz` — directory tarball
diff --git a/libs/cua-driver-rs/Cargo.lock b/libs/cua-driver-rs/Cargo.lock
index cd1f8638d5..519df2af36 100644
--- a/libs/cua-driver-rs/Cargo.lock
+++ b/libs/cua-driver-rs/Cargo.lock
@@ -220,6 +220,7 @@ dependencies = [
"base64",
"cursor-overlay",
"image",
+ "libc",
"mcp-server",
"platform-linux",
"platform-macos",
diff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.md
index 29a952f2f3..7a3c8d16c7 100644
--- a/libs/cua-driver-rs/PARITY.md
+++ b/libs/cua-driver-rs/PARITY.md
@@ -1149,6 +1149,161 @@ Swift.
---
+## CLI subcommand: `mcp` (TCC auto-relaunch / daemon proxy)
+- Swift:
+ - `libs/cua-driver/Sources/CuaDriverCLI/CuaDriverCommand.swift` —
+ `MCPCommand`, `shouldUseDaemonProxy`, `runViaDaemonProxy`,
+ `launchDaemonViaOpen`, `waitForDaemon`.
+ - `libs/cua-driver/Sources/CuaDriverCLI/BundleHelpers.swift` —
+ `isExecutableInsideCuaDriverApp()`.
+ - `libs/cua-driver/Sources/CuaDriverServer/CuaDriverMCPServer.swift` —
+ `makeProxy` (the actor that re-implements `ListTools` /
+ `CallTool` over the daemon UDS).
+- Rust:
+ - `libs/cua-driver-rs/crates/cua-driver/src/bundle.rs` —
+ `is_executable_inside_cuadriverrs_app`,
+ `parent_is_not_launchd`, `is_env_truthy`.
+ - `libs/cua-driver-rs/crates/cua-driver/src/cli.rs` —
+ `should_use_daemon_proxy`, `launch_daemon_and_wait`,
+ `run_mcp_via_daemon_proxy`.
+ - `libs/cua-driver-rs/crates/cua-driver/src/proxy.rs` —
+ `run_proxy` (the stdio loop forwarding `tools/list` and
+ `tools/call` through the daemon socket).
+ - `libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/Info.plist` —
+ the bundle the auto-relaunch path lands in.
+ - `libs/cua-driver-rs/scripts/install.sh` — drops the bundle to
+ `/Applications/CuaDriverRs.app` and symlinks the bin into it.
+- Status: implemented on macOS (issue #1525); smoke-tested manually
+ before merge.
+
+### Why this exists
+When `cua-driver-rs mcp` is invoked from an IDE terminal (Claude
+Code, Cursor, VS Code, Warp), macOS attributes the spawned process
+to the parent terminal's TCC responsibility chain — *not* to
+`com.trycua.cuadriverrs`. AX probes against the process silently
+fail because the user granted Accessibility to the bundle, not to
+the IDE terminal. The Swift driver hit the same pathology and fixed
+it in PR #1479; the Rust port hit it on the macOS GA flip path and
+fixed it here. See issue #1525 for the full background.
+
+### Bundle id divergence (intentional)
+Swift `CuaDriver.app` → `com.trycua.driver`.
+Rust `CuaDriverRs.app` → `com.trycua.cuadriverrs`.
+The two bundles coexist on disk and in TCC; a user can grant
+Accessibility + Screen Recording to each independently. The Rust
+port has its own bundle name + identifier so:
+ - `open -n -g -a CuaDriverRs --args serve` never accidentally
+ relaunches into the Swift bundle (and vice versa).
+ - TCC grants are per-cdhash, so granting one doesn't carry into
+ the other — users explicitly opt in to each binary.
+
+### Escape hatches
+- `--no-daemon-relaunch` flag — same flag Swift exposes.
+- `CUA_DRIVER_RS_MCP_NO_RELAUNCH=1` env var — Rust-specific name
+ (Swift uses `CUA_DRIVER_MCP_NO_RELAUNCH`).
+- `--socket <path>` flag — override the daemon UDS path used by the
+ proxy.
+- `CUA_DRIVER_RS_MCP_FORCE_PROXY=1` env var (Rust-only) — force
+ proxy mode without the bundle-context check. Useful when wrapping
+ the binary in a custom .app, or for manual smoke-testing of the
+ proxy path against a daemon you've already started by hand. Skips
+ the `open -a` step entirely; caller must supply a daemon on
+ `--socket`.
+
+### Daemon protocol divergence
+The daemon's `list` method now returns full `ToolDef`
+(`input_schema` + annotation hints), not just `{name, description}`.
+The proxy uses this to build a complete `tools/list` from one
+round-trip instead of N+1 list+describe calls. Backwards compatible:
+older clients that only read name/description still work.
+
+### Manual smoke test (macOS)
+1. `cua-driver serve --socket /tmp/test.sock &`
+2. `CUA_DRIVER_RS_MCP_FORCE_PROXY=1 cua-driver mcp --socket /tmp/test.sock`
+3. From an MCP client, run the standard initialize → tools/list →
+ tools/call get_screen_size handshake. Expect identical envelope
+ shape to the in-process path. Concretely:
+
+ `tools/list` response (the daemon caches and returns it once at
+ proxy startup — same shape as the in-process server's `tools/list`):
+
+ ```json
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {
+ "tools": [
+ { "name": "browser_eval", "description": "…", "inputSchema": {…}, "annotations": {…} },
+ { "name": "check_permissions", "description": "…", "inputSchema": {…}, "annotations": {…} },
+ { "name": "click", "description": "…", "inputSchema": {…}, "annotations": {…} },
+ { "name": "double_click", "…": "…" },
+ { "name": "drag", "…": "…" },
+ { "name": "get_accessibility_tree", "…": "…" },
+ { "name": "get_config", "…": "…" },
+ { "name": "get_cursor_position", "…": "…" },
+ { "name": "get_recording_state", "…": "…" },
+ { "name": "get_screen_size", "…": "…" },
+ { "name": "get_window_state", "…": "…" },
+ { "name": "hotkey", "…": "…" },
+ { "name": "launch_app", "…": "…" },
+ { "name": "list_apps", "…": "…" },
+ { "name": "list_windows", "…": "…" },
+ { "name": "page", "…": "…" },
+ { "name": "press_key", "…": "…" },
+ { "name": "replay_trajectory", "…": "…" },
+ { "name": "right_click", "…": "…" },
+ { "name": "screenshot", "…": "…" },
+ { "name": "scroll", "…": "…" },
+ { "name": "set_config", "…": "…" },
+ { "name": "set_recording", "…": "…" },
+ { "name": "set_value", "…": "…" },
+ { "name": "type_text", "…": "…" },
+ { "name": "zoom", "…": "…" }
+ // …plus the agent_cursor.* family when overlay is enabled.
+ // For an exact snapshot run: `cua-driver list-tools`
+ ]
+ }
+ }
+ ```
+
+ `tools/call get_screen_size` request + response:
+
+ ```json
+ // → stdin
+ {"jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"get_screen_size","arguments":{}}}
+
+ // ← stdout
+ {"jsonrpc":"2.0","id":2,"result":{
+ "content":[{"type":"text","text":"{\"width\":1920,\"height\":1080}"}],
+ "structuredContent":{"width":1920,"height":1080},
+ "isError":false
+ }}
+ ```
+
+ The `result` envelope is identical to the in-process path —
+ structuredContent + text mirror, no proxy-specific wrapping.
+
+4. Without spawning the daemon first, repeat step 2. Expect
+ non-zero exit and a "daemon not reachable" diagnostic on stderr
+ (the fail-fast contract that matches Swift `makeProxy`). Exact
+ stderr text emitted by `main.rs`'s proxy-error branch (wrapping
+ `proxy::run_proxy`'s pre-check):
+
+ ```
+ cua-driver-rs: cua-driver-rs daemon not reachable on /tmp/test.sock. Start it with `open -n -g -a CuaDriverRs --args serve` and retry.
+ ```
+
+ Process exits with status `1` before reading any MCP request on
+ stdin. With `CUA_DRIVER_RS_MCP_FORCE_PROXY=1` set, `cli.rs`'s
+ `run_mcp_via_daemon_proxy` emits the more specific:
+
+ ```
+ cua-driver-rs: CUA_DRIVER_RS_MCP_FORCE_PROXY=1 but no daemon listening on /tmp/test.sock. Start one with `cua-driver serve --socket /tmp/test.sock` and retry.
+ ```
+
+---
+
## CLI subcommands: `status` + `stop`
- Swift: `libs/cua-driver/Sources/CuaDriverCLI/ServeCommand.swift:368-470`
- Rust: `libs/cua-driver-rs/crates/cua-driver/src/serve.rs::run_status_cmd, run_stop_cmd`
diff --git a/libs/cua-driver-rs/crates/cua-driver/Cargo.toml b/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
index a7c31f469d..34cc6461cf 100644
--- a/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
@@ -21,6 +21,12 @@ cursor-overlay = { path = "../cursor-overlay" }
async-trait = "0.1"
base64 = { workspace = true }
+# Used by crate::bundle::parent_is_not_launchd() for the TCC
+# auto-relaunch detection path on Unix (only the macOS heuristic
+# actually fires, but the crate compiles on Linux too).
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
[target.'cfg(target_os = "macos")'.dependencies]
platform-macos = { path = "../platform-macos" }
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs b/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs
new file mode 100644
index 0000000000..02cc841bcd
--- /dev/null
+++ b/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs
@@ -0,0 +1,143 @@
+//! macOS bundle-context detection for the TCC auto-relaunch path.
+//!
+//! Mirrors `libs/cua-driver/Sources/CuaDriverCLI/BundleHelpers.swift`'s
+//! `isExecutableInsideCuaDriverApp()` — the heuristic that decides
+//! whether `cua-driver-rs mcp` was spawned from an IDE terminal as a
+//! bare CLI symlinked into our .app bundle. When true and the parent
+//! isn't launchd, we re-launch the daemon via `open -n -g -a
+//! CuaDriverRs --args serve` so it picks up the bundle's TCC grants,
+//! then proxy stdio MCP traffic through the daemon's Unix socket.
+//!
+//! Non-macOS targets compile to no-ops so the cross-platform call
+//! sites stay tidy.
+
+/// Returns `true` when the currently-running binary resolves into an
+/// installed `CuaDriverRs.app` bundle (Rust port). The check is the
+/// same shape as the Swift driver's `isExecutableInsideCuaDriverApp`
+/// (`/CuaDriver.app/Contents/MacOS/`) but keyed on the Rust port's
+/// distinct bundle name so the two installs don't collide.
+///
+/// `false` for raw `cargo run` / `target/release/cua-driver` dev
+/// invocations — there's no installed bundle to relaunch into, so the
+/// caller should stay in-process.
+///
+/// Implementation:
+/// 1. Resolve `std::env::current_exe()` (preferred; absolute path
+/// to the running image).
+/// 2. Walk symlinks via `std::fs::canonicalize` — the install layout
+/// is `~/.local/bin/cua-driver` → `/Applications/CuaDriverRs.app/
+/// Contents/MacOS/cua-driver`, so without the canonicalize step
+/// we'd see the bare symlink path and miss the bundle.
+/// 3. Substring-match the canonical path for the bundle marker.
+#[cfg(target_os = "macos")]
+pub fn is_executable_inside_cuadriverrs_app() -> bool {
+ let exe = match std::env::current_exe() {
+ Ok(p) => p,
+ Err(_) => return false,
+ };
+ let canonical = match std::fs::canonicalize(&exe) {
+ Ok(p) => p,
+ Err(_) => return false,
+ };
+ let s = match canonical.to_str() {
+ Some(s) => s,
+ None => return false,
+ };
+ s.contains("/CuaDriverRs.app/Contents/MacOS/")
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn is_executable_inside_cuadriverrs_app() -> bool {
+ false
+}
+
+/// Returns `true` when the parent process is *not* `launchd` (pid 1).
+/// Combined with [`is_executable_inside_cuadriverrs_app`], a `true`
+/// here means the binary was spawned from a shell / IDE terminal that
+/// inherits the wrong TCC responsibility — i.e. the case we want to
+/// auto-relaunch from.
+///
+/// `ppid == 1` means launchd reparented us (we're already running as
+/// the LaunchServices-spawned daemon). In that case we stay
+/// in-process: TCC grants are already correct, and relaunching would
+/// fork-bomb the daemon back into existence on every `mcp` startup.
+///
+/// Mirrors Swift's `if getppid() == 1 { return false }` gate in
+/// `MCPCommand.shouldUseDaemonProxy()`.
+#[cfg(unix)]
+pub fn parent_is_not_launchd() -> bool {
+ // SAFETY: `libc::getppid` is a thread-safe POSIX getter that
+ // takes no args and returns the parent pid. No invariants to
+ // uphold, no UB to risk.
+ let ppid = unsafe { libc::getppid() };
+ ppid != 1
+}
+
+#[cfg(not(unix))]
+pub fn parent_is_not_launchd() -> bool {
+ // No launchd on non-Unix; the heuristic is macOS-only anyway.
+ // Returning false keeps the caller in-process on unsupported
+ // platforms (same effective outcome as the macOS check failing).
+ false
+}
+
+/// Returns `true` when the env var is one of `1|true|yes|on`
+/// (case-insensitive). Anything else, including unset, is falsy.
+///
+/// Mirrors Swift's `isEnvTruthy` helper on `MCPCommand`.
+pub fn is_env_truthy(name: &str) -> bool {
+ match std::env::var(name) {
+ Ok(v) => matches!(
+ v.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ ),
+ Err(_) => false,
+ }
+}
+
+// ─── Tests ───────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cargo_run_is_not_inside_bundle() {
+ // The unit-test runner image lives under `target/<config>/
+ // deps/`, never inside a .app bundle. Should always return
+ // false in CI / local dev, which is exactly the behavior we
+ // want so `cargo run` callers stay in-process.
+ assert!(!is_executable_inside_cuadriverrs_app());
+ }
+
+ #[test]
+ fn unset_env_is_falsy() {
+ // Use a deliberately unlikely name so we don't depend on the
+ // surrounding shell environment.
+ std::env::remove_var("CUA_DRIVER_RS_TEST_UNSET_NAME");
+ assert!(!is_env_truthy("CUA_DRIVER_RS_TEST_UNSET_NAME"));
+ }
+
+ #[test]
+ fn truthy_env_values_recognized() {
+ let name = "CUA_DRIVER_RS_TEST_TRUTHY";
+ for v in ["1", "true", "TRUE", "Yes", "on", " 1 "] {
+ std::env::set_var(name, v);
+ assert!(is_env_truthy(name), "expected truthy for {v:?}");
+ }
+ for v in ["0", "false", "no", "off", ""] {
+ std::env::set_var(name, v);
+ assert!(!is_env_truthy(name), "expected falsy for {v:?}");
+ }
+ std::env::remove_var(name);
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn parent_is_not_launchd_in_tests() {
+ // The cargo test harness is reparented under whatever
+ // launched it (cargo / IDE / shell), not directly under
+ // launchd. The helper should report true.
+ assert!(parent_is_not_launchd());
+ }
+}
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
index c22e324a03..b476174c72 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
@@ -17,7 +17,19 @@ use mcp_server::{protocol::Content, tool::ToolRegistry};
/// Which CLI command was requested.
pub enum Command {
- Mcp,
+ Mcp {
+ /// Force in-process MCP execution — skip the TCC auto-relaunch
+ /// path that would spawn a daemon via `open -n -g -a CuaDriverRs
+ /// --args serve` and proxy stdio MCP requests through its Unix
+ /// socket. Useful when the calling context already has the right
+ /// TCC grants (CuaDriverRs.app launched us directly), or when
+ /// diagnosing in-process failures. Also toggleable via
+ /// `CUA_DRIVER_RS_MCP_NO_RELAUNCH=1`.
+ no_daemon_relaunch: bool,
+ /// Override the daemon Unix socket path used by the proxy
+ /// fallback. Defaults to `serve::default_socket_path()`.
+ socket: Option<String>,
+ },
ListTools,
Describe(String),
Call { tool: String, json_args: Option<serde_json::Value>, screenshot_out_file: Option<String> },
@@ -72,6 +84,11 @@ pub fn parse_command() -> Command {
println!("cua-driver {} — cross-platform computer-use automation driver", env!("CARGO_PKG_VERSION"));
println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");
println!("Subcommands: mcp, list-tools, describe, call, serve, stop, status, config, recording, update, doctor, diagnose");
+ println!();
+ println!("mcp options (macOS):");
+ println!(" --no-daemon-relaunch Stay in-process; skip auto-launching the CuaDriverRs daemon.");
+ println!(" Also: CUA_DRIVER_RS_MCP_NO_RELAUNCH=1");
+ println!(" --socket <path> Override the daemon UDS path used by the proxy fallback.");
std::process::exit(0);
}
@@ -95,9 +112,14 @@ pub fn parse_command() -> Command {
}
}
+ let no_daemon_relaunch = args.iter().any(|a| a == "--no-daemon-relaunch");
+
let mut pos = positionals.into_iter();
match pos.next() {
- None | Some("mcp") => Command::Mcp,
+ None | Some("mcp") => Command::Mcp {
+ no_daemon_relaunch,
+ socket: socket.clone(),
+ },
Some("list-tools") => Command::ListTools,
Some("mcp-config") => Command::McpConfig { client: mcp_client },
Some("serve") => Command::Serve {
@@ -214,6 +236,168 @@ pub fn run_describe(registry: &ToolRegistry, name: &str) {
}
}
+/// Decide whether `mcp` should auto-launch a daemon and proxy MCP
+/// requests through its Unix socket instead of running in-process.
+///
+/// Mirrors Swift `MCPCommand.shouldUseDaemonProxy` in spirit:
+/// the trigger is "shell-spawned bare binary that resolves into an
+/// installed `CuaDriverRs.app` bundle, with a non-launchd parent".
+/// When any of those conditions fails — explicit opt-out, dev-mode
+/// `cargo run` invocation, already-relaunched-via-launchd — we stay
+/// in-process. The proxy path is purely additive.
+///
+/// `false` on non-macOS targets: TCC is a macOS-only concern and
+/// there's no `open -a` equivalent on Linux / Windows.
+#[cfg(target_os = "macos")]
+pub fn should_use_daemon_proxy(no_daemon_relaunch: bool) -> bool {
+ use crate::bundle::{is_env_truthy, is_executable_inside_cuadriverrs_app, parent_is_not_launchd};
+ if no_daemon_relaunch {
+ return false;
+ }
+ if is_env_truthy("CUA_DRIVER_RS_MCP_NO_RELAUNCH") {
+ return false;
+ }
+ // Hidden test/escape hook: force proxy mode without requiring the
+ // executable to live inside CuaDriverRs.app. Used by the
+ // integration test (which spawns a daemon manually) and by users
+ // who've wrapped the binary in a custom bundle. Skips the
+ // launch_daemon_and_wait `open -a` step too — caller is expected
+ // to have a daemon already running on the chosen socket.
+ if is_env_truthy("CUA_DRIVER_RS_MCP_FORCE_PROXY") {
+ return true;
+ }
+ if !is_executable_inside_cuadriverrs_app() {
+ // Raw `cargo run` / dev binary — no installed bundle to land
+ // in, so relaunching would fail. Stay in-process.
+ return false;
+ }
+ if !parent_is_not_launchd() {
+ // ppid == 1 — already running as the LaunchServices-spawned
+ // daemon. TCC context is already correct.
+ return false;
+ }
+ true
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn should_use_daemon_proxy(_no_daemon_relaunch: bool) -> bool {
+ false
+}
+
+/// Spawn `/usr/bin/open -n -g -a CuaDriverRs --args serve` to launch
+/// the daemon under `LaunchServices` (so it inherits the bundle's
+/// TCC attribution), then poll the socket for up to `timeout_secs`
+/// seconds. Returns Err with a diagnostic message if `open` failed
+/// or the daemon never came up.
+///
+/// Mirror of Swift `MCPCommand.launchDaemonViaOpen` +
+/// `waitForDaemon`. Split into one Rust function because we don't
+/// need the post-launch probe separation Swift has.
+#[cfg(target_os = "macos")]
+pub fn launch_daemon_and_wait(socket_path: &str, timeout_secs: u64) -> anyhow::Result<()> {
+ use std::process::{Command as Cmd, Stdio};
+ use std::time::{Duration, Instant};
+
+ // Forward `--socket <path>` to the relaunched daemon when the caller
+ // passed a non-default socket via `cua-driver mcp --socket /path`.
+ // Without this the daemon would listen on `default_socket_path()`,
+ // and the proxy would block forever waiting for a daemon on the
+ // user-supplied path that never comes up. Only added when the path
+ // actually differs from the default, so the common case keeps the
+ // shorter `open` argv (and matches Swift's invocation byte-for-byte).
+ let pass_socket = socket_path != crate::serve::default_socket_path();
+ let mut open_args: Vec<&str> = vec!["-n", "-g", "-a", "CuaDriverRs", "--args", "serve"];
+ if pass_socket {
+ open_args.push("--socket");
+ open_args.push(socket_path);
+ }
+
+ let status = Cmd::new("/usr/bin/open")
+ // `-n` forces a new instance: CuaDriverRs.app might already be
+ // running from a previous MCP session, and without `-n`, `open
+ // -a` would re-use it and drop our `--args serve`, leaving no
+ // daemon up. `-g` keeps the new instance backgrounded —
+ // LSUIElement=true in Info.plist already does this but the
+ // flag makes it explicit and matches Swift's invocation.
+ .args(&open_args)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+
+ let status = status.map_err(|e| {
+ anyhow::anyhow!(
+ "failed to exec `/usr/bin/open`: {e}. Pass --no-daemon-relaunch to bypass."
+ )
+ })?;
+
+ if !status.success() {
+ anyhow::bail!(
+ "`open -n -g -a CuaDriverRs --args serve{}` exited {:?}. \
+ Check that `/Applications/CuaDriverRs.app` is installed, or \
+ pass --no-daemon-relaunch to bypass.",
+ if pass_socket { format!(" --socket {socket_path}") } else { String::new() },
+ status.code()
+ );
+ }
+
+ // Poll the UDS until the daemon answers a probe or we time out.
+ // 100ms tick matches Swift's `usleep(100_000)`.
+ let deadline = Instant::now() + Duration::from_secs(timeout_secs);
+ while Instant::now() < deadline {
+ if crate::serve::is_daemon_listening(socket_path) {
+ return Ok(());
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+
+ anyhow::bail!(
+ "daemon did not appear on {socket_path} within {timeout_secs}s. If this \
+ is the first launch, grant Accessibility + Screen Recording to \
+ CuaDriverRs.app in System Settings and retry. Pass --no-daemon-relaunch \
+ to stay in-process."
+ );
+}
+
+/// Run the MCP proxy path: ensure a daemon is up (spawning via
+/// `open` if needed), then `crate::proxy::run_proxy` against its
+/// socket. Builds its own tokio runtime — same shape as the other
+/// `run_*` helpers in this file that own their event loop.
+#[cfg(target_os = "macos")]
+pub fn run_mcp_via_daemon_proxy(socket: Option<String>) -> anyhow::Result<()> {
+ let socket_path = socket.unwrap_or_else(crate::serve::default_socket_path);
+
+ if !crate::serve::is_daemon_listening(&socket_path) {
+ // CUA_DRIVER_RS_MCP_FORCE_PROXY callers (test harness, custom
+ // bundle setups) supply their own daemon — skip the `open -a`
+ // step, since they don't have an installed CuaDriverRs.app to
+ // relaunch into. Fail fast if no daemon is up at this point.
+ if crate::bundle::is_env_truthy("CUA_DRIVER_RS_MCP_FORCE_PROXY") {
+ anyhow::bail!(
+ "CUA_DRIVER_RS_MCP_FORCE_PROXY=1 but no daemon listening on \
+ {socket_path}. Start one with `cua-driver serve --socket {socket_path}` \
+ and retry."
+ );
+ }
+ let socket_suffix = if socket_path != crate::serve::default_socket_path() {
+ format!(" --socket {socket_path}")
+ } else {
+ String::new()
+ };
+ eprintln!(
+ "cua-driver-rs: mcp launched without CuaDriverRs.app's TCC grants; \
+ auto-launching the daemon via `open -n -g -a CuaDriverRs --args serve{socket_suffix}` \
+ and proxying MCP requests through it. Pass --no-daemon-relaunch to stay in-process."
+ );
+ launch_daemon_and_wait(&socket_path, 10)?;
+ }
+
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ rt.block_on(crate::proxy::run_proxy(socket_path))
+}
+
/// Print the MCP server config snippet or a client-specific install command.
///
/// `--client <name>` selects one of: claude, codex, cursor, hermes, openclaw,
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/main.rs b/libs/cua-driver-rs/crates/cua-driver/src/main.rs
index a6c629ea01..5a986b47db 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/main.rs
@@ -24,7 +24,9 @@
//!
//! On all other platforms `#[tokio::main]` is used directly.
+mod bundle;
mod cli;
+mod proxy;
mod serve;
use std::sync::Arc;
@@ -162,7 +164,25 @@ fn main() {
cli::run_config_cmd(reg, subcommand.as_deref(), key.as_deref(), value.as_deref(), socket.as_deref());
return;
}
- cli::Command::Mcp => {} // fall through to MCP server startup below
+ cli::Command::Mcp { no_daemon_relaunch, socket } => {
+ // TCC sidestep: if we're a shell-spawned bare binary that
+ // resolves into /Applications/CuaDriverRs.app, run the
+ // proxy path instead of the in-process MCP server. The
+ // proxy ensures a daemon is up under the bundle's TCC
+ // attribution and forwards stdio MCP through its socket.
+ // Issue #1525 / mirror of Swift PR #1479.
+ if cli::should_use_daemon_proxy(no_daemon_relaunch) {
+ if let Err(e) = cli::run_mcp_via_daemon_proxy(socket) {
+ eprintln!("cua-driver-rs: {e}");
+ std::process::exit(1);
+ }
+ return;
+ }
+ // Fall through to the in-process MCP server below. The
+ // `socket` flag is daemon-proxy-only; it has no meaning
+ // in the in-process path, so we drop it on the floor.
+ let _ = socket;
+ }
}
let cursor_cfg = cursor_overlay::CursorConfig::from_args();
@@ -327,7 +347,12 @@ fn main() -> anyhow::Result<()> {
}).join().ok();
return Ok(());
}
- cli::Command::Mcp => {} // fall through to MCP server startup below
+ cli::Command::Mcp { no_daemon_relaunch, socket } => {
+ // Non-macOS: TCC doesn't exist, no daemon proxy path. The
+ // flags parse cleanly so cross-platform MCP config
+ // snippets work, but we ignore them and run in-process.
+ let _ = (no_daemon_relaunch, socket);
+ }
}
// MCP server mode: this needs a full async tokio runtime.
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/proxy.rs b/libs/cua-driver-rs/crates/cua-driver/src/proxy.rs
new file mode 100644
index 0000000000..09be4ee832
--- /dev/null
+++ b/libs/cua-driver-rs/crates/cua-driver/src/proxy.rs
@@ -0,0 +1,363 @@
+//! Stdio MCP proxy that forwards `tools/list` and `tools/call` through
+//! the running `cua-driver-rs serve` daemon over its Unix socket.
+//!
+//! This is the runtime half of the TCC auto-relaunch path (issue #1525,
+//! mirror of Swift PR #1479). When `cua-driver-rs mcp` is invoked from
+//! an IDE terminal — Claude Code, Cursor, VS Code, Warp — macOS TCC
+//! attributes the process to the calling terminal, not to
+//! `CuaDriverRs.app`. The MCP client side sees a normal stdio server,
+//! but every AX probe silently fails because the binary is running
+//! against the wrong bundle id.
+//!
+//! The fix: detect that context (see `crate::bundle`), ensure a daemon
+//! is running under `LaunchServices` (which gives it the right TCC
+//! attribution), then proxy every MCP request through the daemon's
+//! socket. The MCP client never sees the redirection — same JSON-RPC
+//! envelope, same tool semantics.
+//!
+//! Why this lives in `cua-driver` and not `mcp-server`:
+//! `mcp_server::server::run` already speaks JSON-RPC over stdio
+//! against an in-process `ToolRegistry`. The proxy speaks the same
+//! protocol on the client side but the server side is the daemon's
+//! line-delimited JSON UDS protocol, owned by `crate::serve`.
+//! Putting the proxy here avoids `mcp-server → cua-driver` reverse
+//! coupling.
+
+use std::sync::Arc;
+
+use mcp_server::protocol::{initialize_result, Request, Response};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tracing::{debug, error, warn};
+
+use crate::serve::{is_daemon_listening, send_request, DaemonRequest};
+
+/// Run the MCP stdio proxy. Reads JSON-RPC lines from stdin, forwards
+/// the body of each `tools/list` / `tools/call` to the daemon at
+/// `socket_path`, and writes the daemon's response back as a proper
+/// JSON-RPC envelope.
+///
+/// Mirrors `mcp_server::server::run`'s control flow exactly — same
+/// EOF + parse-error + notification handling — only the per-method
+/// branches change.
+///
+/// Fails fast if the daemon isn't reachable, so MCP clients see a
+/// clear startup error instead of a "successful" handshake that
+/// advertises zero tools and then errors on every call. Matches
+/// Swift `makeProxy`'s `fetchProxyToolList` pre-check.
+pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
+ if !is_daemon_listening(&socket_path) {
+ anyhow::bail!(
+ "cua-driver-rs daemon not reachable on {socket_path}. Start it \
+ with `open -n -g -a CuaDriverRs --args serve` and retry."
+ );
+ }
+
+ // Cache the tool list once at startup. The daemon's registry is
+ // static for the lifetime of the daemon, so polling on every
+ // `tools/list` would waste a round-trip per call. Swift does the
+ // same caching in `fetchProxyToolList`.
+ let cached_tools_list = fetch_tools_list_from_daemon(&socket_path)?;
+ let cached_tools_list = Arc::new(cached_tools_list);
+
+ let stdin = tokio::io::stdin();
+ let stdout = tokio::io::stdout();
+ let mut reader = BufReader::new(stdin);
+ let mut writer = tokio::io::BufWriter::new(stdout);
+ let mut line = String::new();
+
+ loop {
+ line.clear();
+ let n = reader.read_line(&mut line).await?;
+ if n == 0 {
+ break; // EOF
+ }
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ debug!(raw = trimmed, "→ proxy request");
+
+ let response = match serde_json::from_str::<Request>(trimmed) {
+ Err(e) => {
+ error!("JSON parse error: {e}");
+ Response::parse_error()
+ }
+ Ok(req) if req.is_notification() => {
+ // Notifications get dropped, same as `server::run`.
+ continue;
+ }
+ Ok(req) => {
+ let id = req.id.clone().unwrap_or(serde_json::Value::Null);
+ handle_proxy_request(req, id, &socket_path, &cached_tools_list).await
+ }
+ };
+
+ let serialized = serde_json::to_string(&response).unwrap_or_else(|e| {
+ format!(
+ r#"{{"jsonrpc":"2.0","id":null,"error":{{"code":-32603,"message":"serialize error: {e}"}}}}"#
+ )
+ });
+ debug!(raw = %serialized, "← proxy response");
+
+ writer.write_all(serialized.as_bytes()).await?;
+ writer.write_all(b"\n").await?;
+ writer.flush().await?;
+ }
+
+ Ok(())
+}
+
+/// One-shot daemon `list` over the UDS, reshaped into a MCP
+/// `tools/list` result. The daemon now returns the full ToolDef
+/// (`name`, `description`, `input_schema`, annotation hints) per
+/// commit 3's `serve.rs` change.
+fn fetch_tools_list_from_daemon(socket_path: &str) -> anyhow::Result<serde_json::Value> {
+ let req = DaemonRequest { method: "list".into(), name: None, args: None };
+ let resp = send_request(socket_path, &req)?;
+ if !resp.ok {
+ anyhow::bail!(
+ "daemon refused tool list on {socket_path}: {}",
+ resp.error.unwrap_or_else(|| "(no error message)".into())
+ );
+ }
+ let result = resp.result.ok_or_else(|| {
+ anyhow::anyhow!("daemon list response missing `result` field")
+ })?;
+ let tools_array = result
+ .get("tools")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| {
+ anyhow::anyhow!("daemon list response missing `tools` array")
+ })?;
+
+ // Reshape the daemon's `{name, description, input_schema, read_only,
+ // ...}` envelope into MCP's `{name, description, inputSchema,
+ // annotations: {...}}` shape. Same translation
+ // `ToolDef::to_list_entry` does for the in-process path so MCP
+ // clients see identical tools/list output either way.
+ let mcp_tools: Vec<serde_json::Value> = tools_array
+ .iter()
+ .map(|t| {
+ let name = t.get("name").cloned().unwrap_or(serde_json::Value::Null);
+ let description = t
+ .get("description")
+ .cloned()
+ .unwrap_or(serde_json::Value::String(String::new()));
+ let input_schema = t.get("input_schema").cloned().unwrap_or_else(
+ || serde_json::json!({"type": "object", "properties": {}}),
+ );
+ let read_only = t.get("read_only").and_then(|v| v.as_bool()).unwrap_or(false);
+ let destructive =
+ t.get("destructive").and_then(|v| v.as_bool()).unwrap_or(false);
+ let idempotent =
+ t.get("idempotent").and_then(|v| v.as_bool()).unwrap_or(false);
+ let open_world =
+ t.get("open_world").and_then(|v| v.as_bool()).unwrap_or(false);
+ serde_json::json!({
+ "name": name,
+ "description": description,
+ "inputSchema": input_schema,
+ "annotations": {
+ "readOnlyHint": read_only,
+ "destructiveHint": destructive,
+ "idempotentHint": idempotent,
+ "openWorldHint": open_world,
+ }
+ })
+ })
+ .collect();
+
+ Ok(serde_json::json!({ "tools": mcp_tools }))
+}
+
+/// JSON-RPC method dispatcher for the proxy. Mirrors
+/// `mcp_server::server::handle_request`:
+/// - `initialize` → static `initialize_result()` (same envelope
+/// the in-process path returns; the daemon's
+/// identity is hidden from the MCP client).
+/// - `tools/list` → return the cached daemon tool list.
+/// - `tools/call` → forward to the daemon and reshape the
+/// response into MCP's `CallTool.Result`.
+/// - other → method-not-found, same as in-process.
+async fn handle_proxy_request(
+ req: Request,
+ id: serde_json::Value,
+ socket_path: &str,
+ cached_tools_list: &Arc<serde_json::Value>,
+) -> Response {
+ match req.method.as_str() {
+ "initialize" => Response::ok(id, initialize_result()),
+
+ "tools/list" => Response::ok(id, (**cached_tools_list).clone()),
+
+ "tools/call" => match req.tool_call() {
+ Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
+ Ok(call) => forward_tool_call(id, call.name, call.args, socket_path).await,
+ },
+
+ other => {
+ warn!(method = other, "unknown method");
+ Response::method_not_found(id, other)
+ }
+ }
+}
+
+/// Forward a single MCP `tools/call` to the daemon as a `call`
+/// request, then translate the `DaemonResponse` back into an MCP
+/// `CallTool.Result` envelope.
+///
+/// Error mapping:
+/// - Tool ran and reported failure (`!resp.ok`, including unknown
+/// tool / bad params) → JSON-RPC success with `result.isError =
+/// true`. Mirrors the in-process `mcp_server::server` path so
+/// MCP clients see identical envelopes either way.
+/// - Transport failure (UDS unreachable, decode error, blocking
+/// task panic) → JSON-RPC error (`-32603`), because the MCP
+/// client really does need to distinguish "tool said no" from
+/// "I couldn't reach the tool at all."
+async fn forward_tool_call(
+ id: serde_json::Value,
+ name: String,
+ args: serde_json::Value,
+ socket_path: &str,
+) -> Response {
+ let req = DaemonRequest {
+ method: "call".into(),
+ name: Some(name.clone()),
+ args: Some(args),
+ };
+
+ // The daemon client is sync, so jump to a blocking thread to keep
+ // the tokio reactor responsive while the AX-heavy call (e.g.
+ // `screenshot`, `get_window_state`) does its thing on the daemon
+ // side.
+ let socket = socket_path.to_owned();
+ let blocking = tokio::task::spawn_blocking(move || send_request(&socket, &req)).await;
+
+ let resp = match blocking {
+ Err(join_err) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("internal join error forwarding to daemon: {join_err}"),
+ );
+ }
+ Ok(Err(e)) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("daemon transport error forwarding `{name}`: {e}"),
+ );
+ }
+ Ok(Ok(r)) => r,
+ };
+
+ if !resp.ok {
+ // MCP separates two failure modes:
+ // - JSON-RPC errors → `Response::error(...)`, used for
+ // transport / protocol failures (unknown method, bad
+ // params shape, server crash).
+ // - Tool-level errors → `Response::ok(...)` carrying a
+ // `CallTool.Result` with `isError: true` and the error
+ // message in `content[]`. The tool ran, returned a
+ // well-formed result that says "I failed."
+ //
+ // A non-`ok` daemon response means the tool call reached the
+ // daemon and the daemon decided the tool returned an error
+ // (or rejected the call). That's tool-level, not transport-
+ // level, so the in-process `mcp_server::server` would surface
+ // it as `Response::ok` with `isError: true`. Mirror that
+ // shape here so MCP clients see identical envelopes either
+ // way — CodeRabbit #2.
+ let msg = resp.error.unwrap_or_else(|| "daemon reported failure".into());
+ let exit_code = resp.exit_code.unwrap_or(1);
+ let result = serde_json::json!({
+ "content": [{ "type": "text", "text": msg }],
+ "isError": true,
+ "structuredContent": { "exit_code": exit_code }
+ });
+ return Response::ok(id, result);
+ }
+
+ let result = resp.result.unwrap_or_else(|| {
+ serde_json::json!({
+ "content": [],
+ "isError": false
+ })
+ });
+ Response::ok(id, result)
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+//
+// Unit-test only the JSON shape of the proxy's tool-error envelope.
+// The full proxy loop is exercised by the macOS integration test
+// (CUA_DRIVER_RS_MCP_FORCE_PROXY harness in PARITY.md §"Manual smoke
+// test"); these tests just lock in the per-branch reshape so a
+// regression to `Response::error` for tool-level failures would fail
+// fast in CI on every platform.
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::serve::DaemonResponse;
+
+ /// Reconstruct the `!resp.ok` branch in isolation so we can assert
+ /// on the serialized shape without spinning up a real daemon /
+ /// tokio runtime. Keep this in sync with `forward_tool_call`.
+ fn build_tool_error_response(
+ id: serde_json::Value,
+ resp: DaemonResponse,
+ ) -> Response {
+ let msg = resp.error.unwrap_or_else(|| "daemon reported failure".into());
+ let exit_code = resp.exit_code.unwrap_or(1);
+ let result = serde_json::json!({
+ "content": [{ "type": "text", "text": msg }],
+ "isError": true,
+ "structuredContent": { "exit_code": exit_code }
+ });
+ Response::ok(id, result)
+ }
+
+ #[test]
+ fn daemon_tool_failure_wraps_as_jsonrpc_success_with_iserror_true() {
+ let daemon_resp = DaemonResponse {
+ ok: false,
+ result: None,
+ error: Some("missing required field `pid`".into()),
+ exit_code: Some(64),
+ };
+ let resp = build_tool_error_response(serde_json::json!(7), daemon_resp);
+ let value = serde_json::to_value(&resp).expect("serialize");
+
+ // Top-level JSON-RPC envelope: success (`result`), not error.
+ assert_eq!(value["jsonrpc"], "2.0");
+ assert_eq!(value["id"], serde_json::json!(7));
+ assert!(value.get("error").is_none(),
+ "tool-level failure must NOT surface as JSON-RPC error: got {value}");
+ assert!(value.get("result").is_some(),
+ "tool-level failure must carry a `result` payload: got {value}");
+
+ // CallTool.Result inside `result`: isError + content text.
+ let result = &value["result"];
+ assert_eq!(result["isError"], serde_json::json!(true));
+ assert_eq!(result["content"][0]["type"], "text");
+ assert_eq!(result["content"][0]["text"], "missing required field `pid`");
+ assert_eq!(result["structuredContent"]["exit_code"], 64);
+ }
+
+ #[test]
+ fn daemon_failure_with_no_error_message_uses_fallback_text() {
+ let daemon_resp = DaemonResponse {
+ ok: false,
+ result: None,
+ error: None,
+ exit_code: None,
+ };
+ let resp = build_tool_error_response(serde_json::json!("abc"), daemon_resp);
+ let value = serde_json::to_value(&resp).expect("serialize");
+ assert_eq!(value["result"]["isError"], serde_json::json!(true));
+ assert_eq!(value["result"]["content"][0]["text"], "daemon reported failure");
+ assert_eq!(value["result"]["structuredContent"]["exit_code"], 1);
+ }
+}
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/serve.rs b/libs/cua-driver-rs/crates/cua-driver/src/serve.rs
index 34a69a8886..e6c0198bfb 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/serve.rs
@@ -264,10 +264,20 @@ pub async fn run_serve(
return;
}
"list" => {
+ // Include full ToolDef (input_schema + annotation
+ // hints) so MCP proxy callers can build a complete
+ // `tools/list` response from one daemon round-trip.
+ // Older clients that only read name/description
+ // still work — the extra fields are ignored.
let tools: Vec<serde_json::Value> = reg.iter_defs()
.map(|(name, def)| serde_json::json!({
"name": name,
- "description": def.description
+ "description": def.description,
+ "input_schema": def.input_schema,
+ "read_only": def.read_only,
+ "destructive": def.destructive,
+ "idempotent": def.idempotent,
+ "open_world": def.open_world,
}))
.collect();
let resp = DaemonResponse::ok(serde_json::json!({"tools": tools}));
@@ -441,8 +451,20 @@ pub async fn run_serve(
return;
}
"list" => {
+ // Include full ToolDef so MCP proxy callers can
+ // build a complete `tools/list` response from
+ // one daemon round-trip. See the unix branch
+ // above for rationale.
let tools: Vec<serde_json::Value> = reg.iter_defs()
- .map(|(name, def)| serde_json::json!({"name": name, "description": def.description}))
+ .map(|(name, def)| serde_json::json!({
+ "name": name,
+ "description": def.description,
+ "input_schema": def.input_schema,
+ "read_only": def.read_only,
+ "destructive": def.destructive,
+ "idempotent": def.idempotent,
+ "open_world": def.open_world,
+ }))
.collect();
let resp = DaemonResponse::ok(serde_json::json!({"tools": tools}));
let _ = writer.write_all(
diff --git a/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/Info.plist b/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/Info.plist
new file mode 100644
index 0000000000..552dad462e
--- /dev/null
+++ b/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/Info.plist
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!--
+ Minimal .app bundle for cua-driver-rs.
+
+ Exists solely so the Rust port can use the same TCC-attribution
+ trick as the Swift cua-driver: `open -n -g -a CuaDriverRs --args serve`
+ relaunches into a process attributed to `com.trycua.cuadriverrs` (a
+ stable bundle identifier TCC keys grants against), instead of
+ inheriting the calling shell/IDE-terminal's TCC responsibility.
+
+ Bundle id intentionally distinct from the Swift driver's
+ `com.trycua.driver` so the two installs do NOT collide on TCC
+ grants — a user can have both installed and grant Accessibility +
+ Screen Recording to each independently.
+
+ LSUIElement=true keeps the bundle headless (no Dock icon, no menu
+ bar) so the daemon-spawn path doesn't flash any UI.
+-->
+<plist version="1.0">
+<dict>
+ <key>CFBundleIdentifier</key>
+ <string>com.trycua.cuadriverrs</string>
+ <key>CFBundleName</key>
+ <string>Cua Driver RS</string>
+ <key>CFBundleDisplayName</key>
+ <string>Cua Driver RS</string>
+ <key>CFBundleExecutable</key>
+ <string>cua-driver</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.1.3</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>13.0</string>
+ <key>LSUIElement</key>
+ <true/>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>NSSupportsAutomaticTermination</key>
+ <true/>
+</dict>
+</plist>
diff --git a/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/MacOS/.gitkeep b/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/MacOS/.gitkeep
new file mode 100644
index 0000000000..32cec09275
--- /dev/null
+++ b/libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/MacOS/.gitkeep
@@ -0,0 +1,14 @@
+# Placeholder so the empty MacOS/ directory is tracked in git.
+#
+# At build / install time the cua-driver release binary (universal
+# macOS slice — arm64 + x86_64 lipo'd together) is copied into this
+# directory as `cua-driver`. The Info.plist's CFBundleExecutable
+# points at that name.
+#
+# See:
+# - libs/cua-driver-rs/scripts/install.sh (downloads the binary
+# from GitHub Releases, copies it into Contents/MacOS, installs
+# the bundle to /Applications/CuaDriverRs.app, and creates the
+# ~/.local/bin/cua-driver symlink pointing into the bundle)
+# - .github/workflows/cd-rust-cua-driver.yml (bakes the assembled
+# .app into the darwin release tarball at CD time)
diff --git a/libs/cua-driver-rs/scripts/install.sh b/libs/cua-driver-rs/scripts/install.sh
index 55a050bf38..60877fec60 100644
--- a/libs/cua-driver-rs/scripts/install.sh
+++ b/libs/cua-driver-rs/scripts/install.sh
@@ -32,6 +32,16 @@ TAG_PREFIX="cua-driver-rs-v"
BIN_DIR="${CUA_DRIVER_RS_BIN_DIR:-$HOME/.local/bin}"
NO_MODIFY_PATH="${CUA_DRIVER_RS_NO_MODIFY_PATH:-0}"
+# macOS-only: name and install location of the .app bundle that wraps
+# the bare binary so the TCC auto-relaunch path in `cua-driver-rs mcp`
+# has a stable bundle id (com.trycua.cuadriverrs) to attribute the
+# daemon to. See libs/cua-driver-rs/scripts/CuaDriverRs.app/Contents/
+# Info.plist and the matching docs on `cua-driver-rs mcp`'s auto-
+# relaunch behavior. Distinct from the Swift driver's CuaDriver.app
+# (com.trycua.driver) so the two installs coexist on the same machine.
+APP_NAME="CuaDriverRs.app"
+APP_DEST="/Applications/$APP_NAME"
+
while [[ $# -gt 0 ]]; do
case "$1" in
--bin-dir) BIN_DIR="$2"; shift 2 ;;
@@ -98,19 +108,21 @@ VERSION="${TAG#${TAG_PREFIX}}"
# --- Download bare-binary tarball ---------------------------------------
-# Prefer the bare-binary tarball (single `cua-driver` file at the root) —
-# the directory tarball would require unpacking and copying, but the bare
-# form is curl-pipe-able.
+# Tarball selection:
#
-# macOS: the release workflow publishes one universal binary (arm64 + x86_64
-# lipo'd together) named `darwin-universal-binary`. There are NO per-arch
-# bare-binary tarballs for macOS — only the directory tarballs are split
-# by arch (darwin-arm64 / darwin-x86_64). The universal binary works on
-# both Apple Silicon and Intel, so we always fetch it on macOS.
+# macOS — fetch the directory tarball (cua-driver-rs-vN-darwin-universal.tar.gz).
+# The directory layout includes `CuaDriverRs.app/` alongside the bare
+# binary, which we need to install into /Applications so the TCC
+# auto-relaunch path in `cua-driver-rs mcp` can resolve
+# `com.trycua.cuadriverrs` via `open -n -g -a CuaDriverRs`. The
+# directory variant carries the same universal binary as the
+# bare-binary tarball, so users on both Apple Silicon and Intel
+# get a working install from one download.
#
-# Linux: per-arch bare-binary tarballs exist (e.g. linux-x86_64-binary).
+# Linux / Windows-via-WSL — keep using the bare-binary tarball.
+# No bundle on these platforms, no TCC, no need to unpack a directory.
case "$LABEL" in
- darwin-*) TARBALL="cua-driver-rs-${VERSION}-darwin-universal-binary.tar.gz" ;;
+ darwin-*) TARBALL="cua-driver-rs-${VERSION}-darwin-universal.tar.gz" ;;
*) TARBALL="cua-driver-rs-${VERSION}-${LABEL}-binary.tar.gz" ;;
esac
URL="https://github.com/$REPO/releases/download/$TAG/$TARBALL"
@@ -124,8 +136,26 @@ fi
log "extracting"
tar -xzf "$TMP_DIR/$TARBALL" -C "$TMP_DIR"
-# The bare-binary tarball contains exactly `cua-driver` at the root.
-SRC="$TMP_DIR/$BINARY_NAME"
+# Layout detection:
+# macOS dir tarball expands to:
+# cua-driver-rs-${VERSION}-darwin-universal/
+# ├── cua-driver (bare universal binary)
+# ├── CuaDriverRs.app/ (minimal bundle; copy of the same binary
+# │ lives at Contents/MacOS/cua-driver)
+# └── LICENSE
+# Linux bare-binary tarball expands to:
+# cua-driver (single file at the archive root)
+case "$LABEL" in
+ darwin-*)
+ STAGE="cua-driver-rs-${VERSION}-darwin-universal"
+ SRC="$TMP_DIR/$STAGE/$BINARY_NAME"
+ SRC_APP="$TMP_DIR/$STAGE/$APP_NAME"
+ ;;
+ *)
+ SRC="$TMP_DIR/$BINARY_NAME"
+ SRC_APP=""
+ ;;
+esac
if [[ ! -f "$SRC" ]]; then
err "expected $BINARY_NAME in tarball but didn't find it"
ls -la "$TMP_DIR"
@@ -135,8 +165,54 @@ fi
# --- Install ------------------------------------------------------------
mkdir -p "$BIN_DIR"
-install -m 0755 "$SRC" "$BIN_LINK"
-log "installed $BIN_LINK (version $VERSION)"
+
+# macOS: install the .app to /Applications first, then symlink the
+# bin into the bundle so `~/.local/bin/cua-driver` resolves into
+# `/Applications/CuaDriverRs.app/Contents/MacOS/cua-driver`. The
+# `realpath` walk in `is_executable_inside_cuadriverrs_app()` keys on
+# that resolved path to know whether the auto-relaunch heuristic
+# should fire. Same shape as the Swift `cua-driver` install path —
+# different bundle id (com.trycua.cuadriverrs) so the two coexist.
+#
+# Linux / WSL: drop the bare binary directly into BIN_DIR (no .app).
+#
+# Fail fast on Darwin if the .app is missing — falling through to the
+# bare-binary install would silently produce a CLI that can never
+# auto-relaunch into a TCC-correct daemon. CodeRabbit #3.
+if [[ "$OS" == "Darwin" ]]; then
+ if [[ -z "${SRC_APP:-}" || ! -d "$SRC_APP" ]]; then
+ err "macOS install requires the .app bundle (SRC_APP not found at ${SRC_APP:-<unset>})"
+ err " This usually means the downloaded tarball is missing CuaDriverRs.app — re-run the installer or"
+ err " pin a known-good release via CUA_DRIVER_RS_VERSION=<version>."
+ exit 1
+ fi
+fi
+if [[ "$OS" == "Darwin" && -n "$SRC_APP" && -d "$SRC_APP" ]]; then
+ if [[ ! -w "/Applications" ]]; then
+ err "/Applications is not writable. Re-run this installer in a shell where it is, or grant write access."
+ err " Without the .app bundle, \`cua-driver-rs mcp\` from an IDE terminal will not auto-relaunch into a TCC-correct daemon."
+ exit 1
+ fi
+ if [[ -e "$APP_DEST" ]]; then
+ log "removing existing $APP_DEST"
+ rm -rf "$APP_DEST"
+ fi
+ log "installing $APP_DEST"
+ # `ditto` preserves the bundle's metadata + nested symlinks the way
+ # Apple's installer would. `cp -R` works but doesn't preserve as
+ # much, and ditto is always present on macOS.
+ ditto "$SRC_APP" "$APP_DEST"
+ APP_BINARY="$APP_DEST/Contents/MacOS/$BINARY_NAME"
+ if [[ ! -x "$APP_BINARY" ]]; then
+ err "binary missing at $APP_BINARY (refusing to create broken symlink)"
+ exit 1
+ fi
+ ln -sf "$APP_BINARY" "$BIN_LINK"
+ log "symlinked $BIN_LINK -> $APP_BINARY"
+else
+ install -m 0755 "$SRC" "$BIN_LINK"
+ log "installed $BIN_LINK (version $VERSION)"
+fi
# Auto-extend PATH for users whose shell doesn't already include BIN_DIR.
if [[ "$NO_MODIFY_PATH" != "1" ]] && [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then