Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): make Claude MCP cleanup path-owned
umutcagandcf31fc1e0a61
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.pyindex 6097f21196..953af9816d 100644--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py@@ -1,9 +1,4 @@-"""Claude MCP scrubbing in the release uninstaller.--`cua-driver mcp-config --client claude` registers the server as-`cua-computer-use`, so an uninstaller that only matched `cua-driver-rs` left a-live registration behind while reporting a clean uninstall.-"""+"""Ownership-safe Claude MCP cleanup in the release uninstaller."""from __future__ import annotations@@ -19,47 +14,67 @@ REPO_ROOT = Path(__file__).resolve().parents[4]UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"-def _executable(path: Path, body: str) -> None:+def _executable(path: Path, body: str = "exit 0") -> None:path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(f"#!/bin/sh\n{body}", encoding="utf-8")+ path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")path.chmod(0o755)+def _expand(value, *, home: Path, tmp_path: Path):+ if isinstance(value, str):+ return value.format(home=home, tmp=tmp_path)+ if isinstance(value, list):+ return [_expand(item, home=home, tmp_path=tmp_path) for item in value]+ if isinstance(value, dict):+ return {+ key: _expand(item, home=home, tmp_path=tmp_path)+ for key, item in value.items()+ }+ return value++def _run(tmp_path: Path,- servers: dict,+ config: dict,*,rust_marker: bool,with_claude_cli: bool = False,+ create_canonical_launcher: bool = True,+ custom_release_launchers: tuple[str, ...] = (),) -> tuple[dict, str]:- """Uninstall against a fake HOME and return the surviving servers."""+ """Run the real release uninstaller against a fake HOME."""home = tmp_path / "home"fake_bin = tmp_path / "fake-bin"- (home / ".local/bin").mkdir(parents=True)+ (home / ".local/bin").mkdir(parents=True, exist_ok=True)++ release_binary = home / ".cua-driver/packages/current/cua-driver"if rust_marker:- (home / ".cua-driver/packages/current").mkdir(parents=True)+ _executable(release_binary)+ if create_canonical_launcher:+ (home / ".local/bin/cua-driver").symlink_to(release_binary)+ for raw_path in custom_release_launchers:+ launcher = Path(raw_path.format(home=home, tmp=tmp_path))+ launcher.parent.mkdir(parents=True, exist_ok=True)+ launcher.symlink_to(release_binary)claude_json = home / ".claude.json"-_executable(fake_bin / "uname", "printf 'Linux\\n'")- _executable(fake_bin / "pkill", "exit 0")- _executable(fake_bin / "systemctl", "exit 0")+ _executable(fake_bin / "pkill")+ _executable(fake_bin / "systemctl")+if with_claude_cli:- # `claude mcp remove` matches on the name alone, so the stub has to- # mutate the config the way the real CLI does — a stub that only- # records its arguments cannot show an entry being deleted after the- # scrub deliberately kept it._executable(fake_bin / "claude",f'echo "$@" >> "{tmp_path / "claude-calls"}"\n'f'[ "$1" = mcp ] && [ "$2" = remove ] || exit 1\n'f'exec {shlex.quote(sys.executable)} 'f'{shlex.quote(str(Path(__file__).with_name("_fake_claude_remove.py")))} '- f'"{claude_json}" "$3"\n',+ f'"{claude_json}" "$3"',)- claude_json.write_text(json.dumps(servers), encoding="utf-8")+ expanded = _expand(config, home=home, tmp_path=tmp_path)+ claude_json.write_text(json.dumps(expanded), encoding="utf-8")env = os.environ.copy()env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})@@ -75,19 +90,30 @@ def _run(return json.loads(claude_json.read_text(encoding="utf-8")), result.stdout-def _user_servers(config: dict) -> set:+def _user_servers(config: dict) -> set[str]:return set(config["mcpServers"])-def test_registered_claude_server_is_removed(tmp_path: Path) -> None:- """The reported bug: the name the CLI actually registers survived."""+def _project_servers(config: dict, project: str = "/work/repo") -> set[str]:+ return set(config["projects"][project]["mcpServers"])++def _claude_removals(tmp_path: Path) -> set[str]:+ calls = (tmp_path / "claude-calls").read_text(encoding="utf-8").splitlines()+ return {+ parts[2]+ for parts in (call.split() for call in calls)+ if parts[:2] == ["mcp", "remove"]+ }+++def test_release_registration_is_removed(tmp_path: Path) -> None:config, stdout = _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver",+ "command": "{home}/.local/bin/cua-driver","args": ["mcp"],},"unrelated": {"command": "/usr/bin/other", "args": ["mcp"]},@@ -100,7 +126,7 @@ def test_registered_claude_server_is_removed(tmp_path: Path) -> None:assert "removed Claude MCP registration(s): user:cua-computer-use" in stdout-def test_project_scoped_registrations_are_scrubbed_too(tmp_path: Path) -> None:+def test_project_release_registration_is_removed(tmp_path: Path) -> None:config, _ = _run(tmp_path,{@@ -109,7 +135,7 @@ def test_project_scoped_registrations_are_scrubbed_too(tmp_path: Path) -> None:"/work/repo": {"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver",+ "command": "{home}/.local/bin/cua-driver","args": ["mcp"],},"unrelated": {"command": "/usr/bin/other"},@@ -120,15 +146,18 @@ def test_project_scoped_registrations_are_scrubbed_too(tmp_path: Path) -> None:rust_marker=True,)- assert set(config["projects"]["/work/repo"]["mcpServers"]) == {"unrelated"}+ assert _project_servers(config) == {"unrelated"}-def test_a_renamed_key_still_matches_on_the_launcher(tmp_path: Path) -> None:+def test_renamed_key_is_removed_when_target_is_release_owned(tmp_path: Path) -> None:config, _ = _run(tmp_path,{"mcpServers": {- "my-driver": {"command": "/home/u/.local/bin/cua-driver", "args": ["mcp"]}+ "my-driver": {+ "command": "{home}/.local/bin/cua-driver",+ "args": ["mcp"],+ }}},rust_marker=True,@@ -137,37 +166,40 @@ def test_a_renamed_key_still_matches_on_the_launcher(tmp_path: Path) -> None:assert _user_servers(config) == set()-def test_a_name_without_a_readable_command_is_still_removed(tmp_path: Path) -> None:+def test_shared_name_without_command_is_preserved(tmp_path: Path) -> None:config, _ = _run(tmp_path,{"mcpServers": {"cua-computer-use": {"args": ["mcp"]}}},rust_marker=True,)- assert _user_servers(config) == set()-+ assert _user_servers(config) == {"cua-computer-use"}-def test_the_legacy_name_is_removed_without_a_marker(tmp_path: Path) -> None:- """`cua-driver-rs` was only ever ours, so it needs no disambiguation."""+def test_legacy_name_is_removed_without_a_marker(tmp_path: Path) -> None:config, _ = _run(tmp_path,- {"mcpServers": {"cua-driver-rs": {"command": "/x/cua-driver-rs", "args": ["mcp"]}}},+ {+ "mcpServers": {+ "cua-driver-rs": {+ "command": "/x/cua-driver-rs",+ "args": ["mcp"],+ }+ }+ },rust_marker=False,)assert _user_servers(config) == set()-def test_shared_names_are_kept_without_a_rust_marker(tmp_path: Path) -> None:- """A Swift-only Mac used the same names; leave its registrations alone."""-- config, stdout = _run(+def test_shared_release_name_is_kept_without_rust_marker(tmp_path: Path) -> None:+ config, _ = _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver",+ "command": "{home}/.local/bin/cua-driver","args": ["mcp"],}}@@ -176,18 +208,19 @@ def test_shared_names_are_kept_without_a_rust_marker(tmp_path: Path) -> None:)assert _user_servers(config) == {"cua-computer-use"}- assert "no Claude MCP registrations for cua-driver found" in stdout-def test_another_installs_launcher_is_left_to_its_own_uninstaller(tmp_path: Path) -> None:- """A side-by-side launcher registers under the same name and owns its entry."""+def test_reported_cua_driver_local_registration_is_preserved(tmp_path: Path) -> None:+ """The release uninstaller must not claim the source-built local product."""- config, _ = _run(+ local_launcher = tmp_path / "home/.local/bin/cua-driver-local"+ _executable(local_launcher)+ config, stdout = _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver-sidecar",+ "command": "{home}/.local/bin/cua-driver-local","args": ["mcp"],}}@@ -196,73 +229,115 @@ def test_another_installs_launcher_is_left_to_its_own_uninstaller(tmp_path: Path)assert _user_servers(config) == {"cua-computer-use"}+ assert "preserved local Claude MCP registration(s): user:cua-computer-use" in stdout+ assert "uninstall-local.sh" in stdout-def _claude_removals(tmp_path: Path) -> set:- """Server names the uninstaller asked the `claude` CLI to remove."""-- calls = (tmp_path / "claude-calls").read_text(encoding="utf-8").splitlines()- return {parts[2] for parts in (call.split() for call in calls) if parts[:2] == ["mcp", "remove"]}+def test_same_filename_at_unrelated_path_is_preserved(tmp_path: Path) -> None:+ other_launcher = tmp_path / "other/bin/cua-driver"+ _executable(other_launcher)+ config, _ = _run(+ tmp_path,+ {+ "mcpServers": {+ "cua-computer-use": {+ "command": "{tmp}/other/bin/cua-driver",+ "args": ["mcp"],+ }+ }+ },+ rust_marker=True,+ )+ assert _user_servers(config) == {"cua-computer-use"}-def test_cli_fallback_asks_for_a_name_the_scrub_vouched_for(tmp_path: Path) -> None:- """Ownership established, so the CLI may clear the name from other scopes."""- _run(+def test_custom_bin_launcher_is_removed_when_it_resolves_into_release(tmp_path: Path) -> None:+ config, _ = _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver",+ "command": "{tmp}/custom-bin/cua-driver","args": ["mcp"],}}},rust_marker=True,- with_claude_cli=True,+ custom_release_launchers=("{tmp}/custom-bin/cua-driver",),)- assert _claude_removals(tmp_path) == {"cua-driver-rs", "cua-computer-use"}-+ assert _user_servers(config) == set()-def test_cli_fallback_asks_only_for_the_unambiguous_name_without_evidence(- tmp_path: Path,-) -> None:- """Nothing in the config vouches for a shared name, so do not guess."""- _run(tmp_path, {"mcpServers": {}}, rust_marker=True, with_claude_cli=True)+def test_missing_canonical_launcher_is_safe_fallback(tmp_path: Path) -> None:+ config, _ = _run(+ tmp_path,+ {+ "mcpServers": {+ "cua-computer-use": {+ "command": "{home}/.local/bin/cua-driver",+ "args": ["mcp"],+ }+ }+ },+ rust_marker=True,+ create_canonical_launcher=False,+ )- assert _claude_removals(tmp_path) == {"cua-driver-rs"}+ assert _user_servers(config) == set()-def test_cli_fallback_keeps_shared_names_without_a_rust_marker(tmp_path: Path) -> None:+def test_scope_ownership_does_not_leak_to_same_name_in_project(tmp_path: Path) -> None:+ other_launcher = tmp_path / "other/bin/cua-driver"+ _executable(other_launcher)config, _ = _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver",+ "command": "{home}/.local/bin/cua-driver","args": ["mcp"],}- }+ },+ "projects": {+ "/work/repo": {+ "mcpServers": {+ "cua-computer-use": {+ "command": "{tmp}/other/bin/cua-driver",+ "args": ["mcp"],+ }+ }+ }+ },},- rust_marker=False,+ rust_marker=True,with_claude_cli=True,)+ assert _user_servers(config) == set()+ assert _project_servers(config) == {"cua-computer-use"}assert _claude_removals(tmp_path) == {"cua-driver-rs"}- assert _user_servers(config) == {"cua-computer-use"}-def test_cli_fallback_does_not_delete_another_installs_registration(tmp_path: Path) -> None:- """The scrub keeps this entry; the name-only CLI pass must not undo that."""+def test_cli_fallback_only_uses_unambiguous_legacy_name(tmp_path: Path) -> None:+ _run(+ tmp_path,+ {"mcpServers": {}},+ rust_marker=True,+ with_claude_cli=True,+ )- config, _ = _run(+ assert _claude_removals(tmp_path) == {"cua-driver-rs"}+++def test_shared_name_never_enters_cli_fallback_after_json_scrub(tmp_path: Path) -> None:+ _run(tmp_path,{"mcpServers": {"cua-computer-use": {- "command": "/home/u/.local/bin/cua-driver-sidecar",+ "command": "{home}/.local/bin/cua-driver","args": ["mcp"],}}@@ -271,17 +346,13 @@ def test_cli_fallback_does_not_delete_another_installs_registration(tmp_path: Pawith_claude_cli=True,)- assert "cua-computer-use" not in _claude_removals(tmp_path)- assert _user_servers(config) == {"cua-computer-use"}-+ assert _claude_removals(tmp_path) == {"cua-driver-rs"}-def test_windows_guidance_names_the_registered_server() -> None:- """Windows does not auto-edit the config, so the printed command must be right."""+def test_windows_guidance_uses_registered_user_scope() -> None:script = (REPO_ROOT / "libs/cua-driver/scripts/uninstall.ps1").read_text(encoding="utf-8-sig")- assert "claude mcp remove cua-computer-use" in script- # The legacy name stays for installs that registered under it.- assert "claude mcp remove cua-driver-rs" in script+ assert "claude mcp remove cua-computer-use -s user" in script+ assert "claude mcp remove cua-driver-rs -s user" in scriptdiff --git a/libs/cua-driver/scripts/uninstall.ps1 b/libs/cua-driver/scripts/uninstall.ps1index eba49e8845..79caa4a27e 100644--- a/libs/cua-driver/scripts/uninstall.ps1+++ b/libs/cua-driver/scripts/uninstall.ps1@@ -502,11 +502,11 @@ Write-Host " We don't auto-edit ~/.claude.json on Windows. If you registered cuWrite-Host " with Claude Code, remove it manually. mcp-config --client claude registers"Write-Host " the server under the name cua-computer-use:"Write-Host ""-Write-Host " claude mcp remove cua-computer-use"+Write-Host " claude mcp remove cua-computer-use -s user"Write-Host ""Write-Host " Installs from v0.2.13 and earlier used the name cua-driver-rs:"Write-Host ""-Write-Host " claude mcp remove cua-driver-rs"+Write-Host " claude mcp remove cua-driver-rs -s user"Write-Host ""Write-Host " Or edit ~/.claude.json directly and delete entries whose 'command' points at"Write-Host " cua-driver.exe under %LOCALAPPDATA%\Programs\Cua\cua-driver\bin\"diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.shindex fbdde3a0b1..6d35cf80ee 100755--- a/libs/cua-driver/scripts/uninstall.sh+++ b/libs/cua-driver/scripts/uninstall.sh@@ -48,9 +48,9 @@# (~/.cua-driver/packages/, legacy ~/.cua-driver-rs/, CuaDriverRs.app,# the LaunchAgent/systemd unit, or current Rust telemetry state).#-# Also scrubs Claude MCP registrations in ~/.claude.json (cua-driver /-# cua-computer-use / legacy cua-driver-rs), gated on the same Rust marker-# for the names the retired Swift driver also used.+# Also scrubs release-owned Claude MCP registrations in ~/.claude.json.+# Shared names are removed only when their command resolves into this release+# package home/app bundle. Local, Swift, and side-by-side entries are kept.## Revokes TCC grants on macOS by default (Accessibility + Screen Recording)# so the next install prompts cleanly under the new signing identity. Pass@@ -570,6 +570,213 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenlog "no Rust install marker; leaving any running cua-driver process untouched"fi+ # --- Claude Code MCP registrations ---+ # Inspect registrations before deleting the launcher/package tree. Claude+ # allows the same server name in multiple scopes, so a name is not proof+ # of ownership. Resolve each command while its target still exists and+ # remove only entries whose command belongs to this selected release.+ CLAUDE_JSON="$HOME/.claude.json"+ if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then+ PY_OUTPUT="$(+ CLAUDE_JSON="$CLAUDE_JSON" \+ HOME_DIR="$HOME_DIR" \+ LEGACY_HOME_DIR="$LEGACY_HOME_DIR" \+ APP_BUNDLE="$APP_BUNDLE" \+ LEGACY_APP_BUNDLE="$LEGACY_APP_BUNDLE" \+ USER_BIN_LINK="$USER_BIN_LINK" \+ RUST_INSTALL_PRESENT="$RUST_INSTALL_PRESENT" \+ python3 <<'PYCLAUDE'+import json+import os+import shutil+import sys+import tempfile+import time++path = os.environ["CLAUDE_JSON"]+home_dir = os.path.abspath(os.environ["HOME_DIR"])+legacy_home_dir = os.path.abspath(os.environ["LEGACY_HOME_DIR"])+app_bundle = os.path.abspath(os.environ["APP_BUNDLE"])+legacy_app_bundle = os.path.abspath(os.environ["LEGACY_APP_BUNDLE"])+canonical_launcher = os.path.abspath(os.environ["USER_BIN_LINK"])+rust_install_present = os.environ.get("RUST_INSTALL_PRESENT", "0") == "1"++try:+ with open(path, "r", encoding="utf-8") as handle:+ data = json.load(handle)+except Exception as exc:+ print(f"could not read Claude config {path}: {exc}", file=sys.stderr)+ raise SystemExit(0)++removed = []+preserved_local = []+++def normalize(value):+ return os.path.abspath(os.path.expanduser(value))+++def is_under(candidate, root):+ try:+ return os.path.commonpath((candidate, root)) == root+ except (ValueError, OSError):+ return False+++def text_parts(value):+ if isinstance(value, str):+ return [value]+ if isinstance(value, list):+ return [item for item in value if isinstance(item, str)]+ return []+++def invokes_unambiguous_legacy_rust(server):+ if not isinstance(server, dict):+ return False+ parts = []+ parts.extend(text_parts(server.get("command")))+ parts.extend(text_parts(server.get("args")))+ joined = " ".join(parts)+ return (+ "CuaDriverRs.app" in joined+ or ".cua-driver-rs" in joined+ or "cua-driver-rs" in joined+ )+++def release_owned_command(server):+ if not isinstance(server, dict):+ return False+ command = server.get("command")+ if not isinstance(command, str) or not command:+ return False++ command_path = normalize(command)+ resolved = os.path.realpath(command_path)+ candidates = (command_path, resolved)++ legacy_roots = (+ os.path.join(legacy_home_dir, "packages"),+ legacy_app_bundle,+ )+ if any(+ is_under(candidate, root)+ for candidate in candidates+ for root in legacy_roots+ ):+ return True++ if not rust_install_present:+ return False++ release_roots = (+ os.path.join(home_dir, "packages"),+ app_bundle,+ )+ if any(+ is_under(candidate, root)+ for candidate in candidates+ for root in release_roots+ ):+ return True++ # The canonical launcher is the only safe path-only fallback, and only+ # when it no longer resolves to a live target. A live launcher at the same+ # filename but pointing elsewhere belongs to that other installation.+ return command_path == canonical_launcher and not os.path.exists(command_path)+++def is_local_launcher(server):+ if not isinstance(server, dict):+ return False+ command = server.get("command")+ if not isinstance(command, str) or not command:+ return False+ return os.path.basename(normalize(command)) == "cua-driver-local"+++def should_remove(name, server):+ if name == "cua-driver-rs" or invokes_unambiguous_legacy_rust(server):+ return True+ return release_owned_command(server)+++def scrub_servers(servers, scope):+ if not isinstance(servers, dict):+ return+ for name in list(servers):+ server = servers[name]+ if should_remove(name, server):+ del servers[name]+ removed.append(f"{scope}:{name}")+ elif is_local_launcher(server):+ preserved_local.append(f"{scope}:{name}")+++scrub_servers(data.get("mcpServers"), "user")+projects = data.get("projects")+if isinstance(projects, dict):+ for project_name, project in projects.items():+ if isinstance(project, dict):+ scrub_servers(project.get("mcpServers"), f"project:{project_name}")++if removed:+ backup = f"{path}.bak-cua-driver-rs-uninstall-{int(time.time())}"+ shutil.copy2(path, backup)+ directory = os.path.dirname(path) or "."+ fd, tmp_path = tempfile.mkstemp(+ prefix=".claude.json.",+ suffix=".tmp",+ dir=directory,+ text=True,+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(data, handle, indent=2, ensure_ascii=False)+ handle.write("\n")+ os.replace(tmp_path, path)+ except Exception:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+ raise+ print(f"removed Claude MCP registration(s): {', '.join(removed)}")+ print(f"backed up Claude config to {backup}")++if preserved_local:+ print(+ "preserved local Claude MCP registration(s): "+ + ", ".join(preserved_local)+ + "; remove cua-driver-local with libs/cua-driver/scripts/uninstall-local.sh from the source checkout"+ )+PYCLAUDE+ )"+ if [[ -n "$PY_OUTPUT" ]]; then+ while IFS= read -r line; do+ log "$line"+ done <<< "$PY_OUTPUT"+ else+ log "no release-owned Claude MCP registrations found in $CLAUDE_JSON"+ fi+ else+ log "no Claude config cleanup via python3 (missing $CLAUDE_JSON or python3)"+ fi++ # `cua-driver-rs` was release-only, so its legacy name-based fallback is+ # safe. Do not feed cua-driver/cua-computer-use through every scope: owning+ # one scope says nothing about a same-named entry in another scope.+ if command -v claude >/dev/null 2>&1; then+ for SCOPE in local project user; do+ if claude mcp remove cua-driver-rs -s "$SCOPE" >/dev/null 2>&1; then+ log "removed Claude MCP server cua-driver-rs from $SCOPE scope"+ fi+ done+ else+ log "claude CLI not found (skipping legacy Claude MCP CLI cleanup)"+ fi+# --- CLI symlink ---# Only remove ~/.local/bin/cua-driver when it resolves into a# cua-driver-rs install. Pre-rename installs at@@ -770,199 +977,6 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenlog "no Rust install marker; leaving agent skill symlinks untouched"fi- # --- Claude Code MCP registrations ---- # Keyed on the names the CLI registers (`cua-driver`,- # `cua-computer-use`, legacy `cua-driver-rs`) plus the per-platform- # install paths. Unrelated MCP servers are left alone, and the names- # shared with the retired Swift driver need a Rust marker on disk.- CLAUDE_JSON="$HOME/.claude.json"- CLAUDE_OWNED_NAMES=()- if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then- PY_OUTPUT="$(- CLAUDE_JSON="$CLAUDE_JSON" HOME_DIR="$HOME_DIR" RUST_INSTALL_PRESENT="$RUST_INSTALL_PRESENT" python3 <<'PY'-import json-import os-import shutil-import sys-import tempfile-import time--path = os.environ["CLAUDE_JSON"]-home_dir = os.environ.get("HOME_DIR", "")-rust_install_present = os.environ.get("RUST_INSTALL_PRESENT", "0") == "1"--try:- with open(path, "r", encoding="utf-8") as f:- data = json.load(f)-except Exception as exc:- print(f"could not read Claude config {path}: {exc}", file=sys.stderr)- raise SystemExit(0)--removed = []-# Names this scrub established are ours. `claude mcp remove` matches on the-# name alone, so the CLI cleanup below can only be trusted with a name once-# the ownership check here has vouched for it.-owned = set()--def text_parts(value):- if isinstance(value, str):- return [value]- if isinstance(value, list):- return [item for item in value if isinstance(item, str)]- return []--def invokes_cua_driver_rs(server):- if not isinstance(server, dict):- return False- parts = []- parts.extend(text_parts(server.get("command")))- parts.extend(text_parts(server.get("args")))- joined = " ".join(parts)- # Match the Rust-port-specific anchors: bundle name, package home,- # explicit ".cua-driver-rs" segment. Plain "cua-driver" alone is- # ambiguous (the Swift binary uses the same filename). The shared- # /Applications/CuaDriver.app path is ALSO ambiguous (Rust took- # over the Swift bundle id) — only count it as Rust when a Rust- # install marker is on disk; otherwise it is almost certainly a- # Swift registration we should not scrub.- if home_dir and home_dir in joined:- return True- if "CuaDriverRs.app" in joined or ".cua-driver-rs" in joined or "cua-driver-rs" in joined:- return True- if rust_install_present and "/Applications/CuaDriver.app" in joined:- return True- return False--# The names the CLI actually registers. `cua-driver mcp-config --client-# claude` emits `claude mcp add-json --scope user cua-computer-use`, so-# `cua-driver-rs` alone never matched a current registration. Both names-# were also the retired Swift driver's, so they are gated on the same Rust-# marker as every other shared-path removal.-RELEASE_SERVER_NAMES = {"cua-driver", "cua-computer-use"}--def launcher_name(server):- # The launcher filename this registration runs, compared exactly rather- # than by substring: a side-by-side install ships a differently-named- # launcher and owns its own registration through its own uninstaller.- # A substring test would reach into it.- if not isinstance(server, dict):- return ""- command = server.get("command")- if not isinstance(command, str):- return ""- return os.path.basename(command)--def should_remove(name, server):- if name == "cua-driver-rs" or invokes_cua_driver_rs(server):- return True- # Everything below is a name or path the retired Swift driver used too,- # so a Swift-only Mac that runs this script by mistake keeps its- # registrations.- if not rust_install_present:- return False- launcher = launcher_name(server)- if launcher == "cua-driver":- return True- # Name-only match, for an entry whose command we cannot read. When the- # command does name a launcher and it is not ours, the entry belongs to- # whatever installed it — leave it to that uninstaller.- return name in RELEASE_SERVER_NAMES and not launcher--def scrub_servers(servers, scope):- if not isinstance(servers, dict):- return- for name in list(servers.keys()):- if should_remove(name, servers[name]):- owned.add(name)- del servers[name]- removed.append(f"{scope}:{name}")--scrub_servers(data.get("mcpServers"), "user")--projects = data.get("projects")-if isinstance(projects, dict):- for project in projects.values():- if isinstance(project, dict):- scrub_servers(project.get("mcpServers"), "project")--for name in sorted(owned):- print(f"owned-server-name: {name}")--if not removed:- raise SystemExit(0)--backup = f"{path}.bak-cua-driver-rs-uninstall-{int(time.time())}"-shutil.copy2(path, backup)--directory = os.path.dirname(path) or "."-fd, tmp_path = tempfile.mkstemp(- prefix=".claude.json.",- suffix=".tmp",- dir=directory,- text=True,-)-try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, ensure_ascii=False)- f.write("\n")- os.replace(tmp_path, path)-except Exception:- try:- os.unlink(tmp_path)- except OSError:- pass- raise--print(f"removed Claude MCP registration(s): {', '.join(removed)}")-print(f"backed up Claude config to {backup}")-PY- )"- CLAUDE_SCRUB_REPORTED=0- while IFS= read -r line; do- [[ -z "$line" ]] && continue- if [[ "$line" == "owned-server-name: "* ]]; then- CLAUDE_OWNED_NAMES+=("${line#owned-server-name: }")- else- log "$line"- CLAUDE_SCRUB_REPORTED=1- fi- done <<< "$PY_OUTPUT"- if [[ "$CLAUDE_SCRUB_REPORTED" == "0" ]]; then- log "no Claude MCP registrations for cua-driver found in $CLAUDE_JSON"- fi- else- log "no Claude config cleanup via python3 (missing $CLAUDE_JSON or python3)"- fi-- # Best-effort CLI cleanup. `claude mcp remove` only touches the- # active project / user scopes — fine to run; it's a no-op when the- # entries were already scrubbed above.- if command -v claude >/dev/null 2>&1; then- # `cua-driver-rs` was only ever ours, so it is always safe to remove- # by name. The current names are shared with the retired Swift driver- # and with any side-by-side launcher, and `claude mcp remove` matches- # on the name alone — it cannot repeat the ownership check the scrub- # above made. So only ask for the names that scrub vouched for.- # Without that evidence (no python3, no config, or a registration- # bound to someone else's launcher) leaving an ambiguous entry is- # safer than deleting one we do not own.- CLAUDE_MCP_SERVERS=(cua-driver-rs)- for OWNED_NAME in ${CLAUDE_OWNED_NAMES+"${CLAUDE_OWNED_NAMES[@]}"}; do- if [[ "$OWNED_NAME" != "cua-driver-rs" ]]; then- CLAUDE_MCP_SERVERS+=("$OWNED_NAME")- fi- done- for SERVER in "${CLAUDE_MCP_SERVERS[@]}"; do- for SCOPE in local project user; do- if claude mcp remove "$SERVER" -s "$SCOPE" >/dev/null 2>&1; then- log "removed Claude MCP server $SERVER from $SCOPE scope"- fi- done- done- else- log "claude CLI not found (skipping Claude MCP CLI cleanup)"- fi-# --- Closing message ---# TCC grants were already revoked above, before the app was removed, so# the reset could still resolve the bundle id through LaunchServices.