macos-computer-use-mcp
by tinhobe159
README.md
# macos-computer-use-mcp
Local macOS Computer Use MCP server built with **TypeScript** (`@modelcontextprotocol/sdk` + `zod`) and a **native Swift CLI bridge** (`CoreGraphics`, `AppKit`, `screencapture`) — with zero third-party GUI control dependencies.
## Architecture
```text
macos-computer-use-mcp/
├── .agents/
│ ├── rules/ # Reusable computer-use safety rules
│ └── skills/ # Agent runbook skill for macos-computer-use
├── native/
│ └── MacosControlBridge.swift # Native Swift CLI (windows, capture, focus, mouse, keyboard, observe, ax-action)
├── src/
│ ├── index.ts # MCP stdio entrypoint
│ ├── server.ts # MCP tool registration (12 tools)
│ ├── cdp.ts # Isolated background Chrome CDP manager
│ ├── receipt.ts # Unified Action Receipt normalization & secret redaction
│ ├── security.ts # Allowlist, sensitive-app blocklist, input mode policy, coordinates
│ ├── native-bridge.ts # Subprocess wrapper & structured error mapping
│ └── schemas.ts # Zod input validation schemas
├── test/
│ ├── bridge.integration.test.ts # Native Swift bridge integration tests
│ ├── cdp.test.ts # CDP unit & full MCP client E2E tests
│ ├── schemas.test.ts # Unit tests for Zod schemas
│ ├── security.test.ts # Unit tests for allowlist, blocklist, coordinates, input mode
│ └── e2e/ # Manual/interactive E2E acceptance scripts
├── scripts/
│ └── build-native.sh # Compiles Swift binary to bin/macos-control-bridge
├── bin/ # Compiled Swift binary (gitignored)
└── dist/ # Compiled TypeScript output (gitignored)
```
## Input Modes (`background_strict` vs `foreground`)
The server enforces a trusted `MACOS_CONTROL_INPUT_MODE` environment variable (agents cannot elevate to `foreground` via tool arguments):
- **`background_strict` (default):** Zero hardware mouse movement, zero focus stealing, zero `activate`/`AXRaise`, zero clipboard usage, and zero automatic foreground fallback. Routes native macOS apps via `AXUIElement` (`observe_window` + `ax_action`) + `ScreenCaptureKit` (`capture_window`), and managed browsers via `cdp_*` tools.
- **`background_compatible`:** Reserved (returns `BACKGROUND_INPUT_UNSUPPORTED` in P0/P2).
- **`foreground`:** Opt-in via trusted config `MACOS_CONTROL_INPUT_MODE=foreground`. Enables `focus_app`, `mouse_action`, `keyboard_action`, and `ax_action` `coordinateFallback: true`.
## Supported Capability Matrix
| Target Type | Backend | Background-Safe | Supported Actions | Limitations |
| :--- | :--- | :---: | :--- | :--- |
| **Native macOS apps** (AppKit/Cocoa) | `AXUIElement` + `ScreenCaptureKit` | Yes | `observe_window`, `capture_window`, `ax_action` (`press`, `set_value`, `focus`, `increment`, `decrement`, `show_menu`, `confirm`, `cancel`) | Elements without AX support return `AX_ACTION_UNSUPPORTED` in `background_strict` |
| **Managed Browser** (isolated Chrome via `cdp_*`) | Chrome DevTools Protocol (`127.0.0.1` ephemeral port, `headless: true` default) | Yes | `cdp_session`, `cdp_navigate`, `cdp_observe`, `cdp_screenshot`, `cdp_action` (`click`, `double_click`, `text_input`, `key_press`, `scroll`, `drag_and_drop`), tab management | Uses isolated temp profile; `file://` disabled by default (`MACOS_CONTROL_CDP_ALLOW_FILE_URLS=1` to opt in); never attaches to user's real Chrome profile |
| **Non-AX / Non-CDP apps** (unmanaged Chrome/Electron, custom canvas, games) | None in `background_strict` | No | Observation only (`capture_window`) unless `MACOS_CONTROL_INPUT_MODE=foreground` is explicitly configured | Background pixel input is unsupported without foreground opt-in |
## Tools (12)
1. `list_windows` — Lists visible windows belonging to allowlisted apps (`windowId`, `appName`, `bundleId`, `title`, `bounds`, `isFrontmost`).
2. `capture_window` — Captures a specific window by `windowId` in-memory via `ScreenCaptureKit` (`SCScreenshotManager`) and returns a PNG image along with `bounds` (in macOS points), `scaleFactor`, `imageWidth`, `imageHeight`, and `coordinateUnit: "points"`.
3. `focus_app` — Brings an allowlisted app to the foreground by `windowId`, `appName`, or `bundleId` (using `AXRaise` when `windowId` is provided). Blocked in `background_strict`.
4. `mouse_action` — `click`, `double_click`, `move`, `drag`, `scroll` via `CGEvent`. Supports `coordinateSpace: "window"` (macOS points), `"image_pixels"` (raw PNG pixels from `capture_window`, automatically divided by `scaleFactor`), and `"screen"`. Blocked in `background_strict`.
5. `keyboard_action` — `type_text` (prefers direct Accessibility `kAXSelectedTextAttribute` injection with read-back verification, falling back to `CGEvent` Unicode keystrokes only when the focused element does not support AX; returns `method` and `verified`), `paste_text` (clipboard-safe `NSPasteboard` + `Cmd+V` preserving all item types and checking `changeCount`), and `key_press`. Blocked in `background_strict`.
6. `observe_window` — Traverses the native `AXUIElement` tree of an allowlisted window (`maxDepth`, `maxNodes`, `maxPayloadBytes` bounded) and returns a `snapshotId`, UI state, and elements (`elementId`, `role`, `label`, `value`, `bounds`, `actions`).
7. `ax_action` — Performs semantic AX actions (`press`, `focus`, `set_value`, `increment`, `decrement`, `show_menu`, `confirm`, `cancel`) by `snapshotId` + `elementId` with stale-target protection, read-back verification, and Unified Action Receipt (`executionStatus`, `verificationStatus`, `resultCode`, `actionId`, `backend`, `target`, `durationMs`, `evidence`, advisory `safeToRetry`).
8. `cdp_session` — Manages an isolated background Chrome CDP session (`start`, `close`, `status`, `list_tabs`, `new_tab`, `select_tab`, `close_tab`) using a temp `--user-data-dir` and `127.0.0.1` ephemeral port (`headless: true` default; `headless: false` requires `MACOS_CONTROL_CDP_ALLOW_HEADFUL=1`). In `background_strict`, requires `chrome-headless-shell` (or explicit `MACOS_CONTROL_CDP_BROWSER_PATH` / `MACOS_CONTROL_CDP_ALLOW_CHROME_FALLBACK=1`).
9. `cdp_navigate` — Navigates a managed CDP tab to `http://`, `https://`, or `about:` URLs (`file://` disabled unless `MACOS_CONTROL_CDP_ALLOW_FILE_URLS=1`) without activating or bringing it to front; supports optional `expectedOutcome` verification.
10. `cdp_observe` — Inspects interactive DOM elements (`elementId`, `tag`, `role`, `label`, `value`, `selector`, `bounds`) in a managed CDP tab.
11. `cdp_screenshot` — Captures a PNG screenshot of a managed CDP tab via `Page.captureScreenshot` (works even when headless or occluded).
12. `cdp_action` — Performs background CDP input (`click`, `double_click`, `text_input`, `key_press`, `scroll`, `drag_and_drop`) on a managed Chrome tab with zero OS mouse/focus/clipboard interference and optional `expectedOutcome` verification (`element_visible`, `element_hidden`, `text_equals`, `value_equals`, `url_matches`, `element_count` in `final_state` or `state_transition` mode).
## Safe Rollback
Distinguish **safely preserving local development changes** from **rolling back a published release**:
- **Preserve local uncommitted work** (note: `git diff` only captures tracked changes and excludes untracked files; `git checkout <branch>` does not guarantee removal of uncommitted changes):
```bash
git status -u # inspect both modified and untracked files
git stash push -u -m "wip-backup" # safely save tracked + untracked changes
# or for tracked diffs only:
git diff > /tmp/local-backup.patch
git checkout -p -- src/ native/ test/ README.md
npm run build
```
- **Roll back a published release** (after committing/releasing on `main`):
```bash
git checkout main
git revert <release-commit-sha> # non-destructive history-preserving rollback
# or inspect/pin the previous release tag directly:
git checkout v0.1.0
```
## Known Limitations & Untested Scenarios
- **`CGEvent` fallback focus race & `virtualKey: 49` (observed keyboard leakage):** When `type_text` (foreground-only mode) falls back to `cgevent_unicode` on elements that do not support `kAXSelectedTextAttribute`, `CGEvent` is posted asynchronously to the HID queue using `virtualKey: 49` (Space keyCode) with `keyboardSetUnicodeString` attached. Although the bridge re-verifies the frontmost app and `AXFocusedWindow` before every keystroke (aborting with `FOCUS_LOST`), a concurrent window switch during the ~6–24ms in-flight window of a single keystroke has been observed to deliver **1 leaked character** to the newly focused window. This remains an inherent limitation of the `CGEvent` fallback path in `foreground` mode. The primary `ax_selected_text` path (`background_strict` / `ax_action` `set_value`) and `cdp_action` do not use `CGEvent` and have 0 leaked characters. Do not use `CGEvent` fallback for sensitive targets (terminals, chats, or password fields — `Terminal`, `iTerm2`, `Warp`, `Alacritty`, `Kitty`, `Ghostty`, `WezTerm`, `Hyper`, and `Keychain Access` are hardcoded in `SENSITIVE_APP_BLOCKED`).
- **Occlusion guard TOCTOU race & `move` scope:** Coordinate actions (`mouse_action` `click`/`double_click`/`drag`/`scroll` and `ax_action` `coordinateFallback`) verify `CGWindowListCopyWindowInfo` z-order right before posting `CGEvent` (requiring `windowId`). `mouse_action` `move` intentionally does **not** run the `verifyWindowTopmostAt` occlusion guard. Because the z-order check and the HID event dispatch are not atomic in macOS, a window appearing during the few milliseconds between `verifyWindowTopmostAt` and `CGEvent.post` is an inherent TOCTOU race.
- **`verified: false` does not auto-fallback:** When `type_text` succeeds via `ax_selected_text` (`kAXSelectedTextAttribute` is settable and returns success) but read-back verification cannot confirm the text (`verified: false`), the bridge intentionally returns `{ method: "ax_selected_text", verified: false }` **without** falling back to `cgevent_unicode` so text is never double-typed.
- **Headless Chrome `.app` focus handoff (strictly opt-in since v0.1.1):** Launching `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --headless=new` while another `Google Chrome` instance is already running can cause macOS LaunchServices to activate the existing `Google Chrome` window. In `background_strict` mode, `cdp_session` refuses to fall back to `Google Chrome.app` automatically (and also blocks `MACOS_CONTROL_CDP_BROWSER_PATH` if it resolves to a non-`chrome-headless-shell` binary such as `Google Chrome.app`), returning `CDP_BROWSER_NOT_FOUND` or `FOREGROUND_PERMISSION_REQUIRED`. To opt into `Google Chrome.app` fallback with reduced non-interference guarantees, explicitly set `MACOS_CONTROL_CDP_ALLOW_CHROME_FALLBACK=1` (or `MACOS_CONTROL_INPUT_MODE=foreground`). Native AX tools (`observe_window`, `ax_action`, `list_windows`, `capture_window`) continue working normally when the CDP backend is unavailable.
- **Untested scenarios:**
- **Telex IME active:** E2E tests ran with the `ABC` keyboard layout (`20/20` pass); `cgevent_unicode` with macOS Telex IME enabled has not been tested.
- **Secondary / external displays:** `capture_window` + `mouse_action` (`image_pixels`) has been tested on the built-in Retina display (`1680x1050 @ 2.0x`); multi-monitor / external display scaling has not been tested.
- **Heavy Electron apps under `paste_text`:** Clipboard PNG preservation was verified on TextEdit; slow Electron apps have not been tested.
## Security (Least Privilege)
- **Mandatory Allowlist (`MACOS_CONTROL_ALLOWLIST`)**: Comma-separated app names or bundle IDs (e.g. `Simulator,TextEdit,com.apple.iphonesimulator`). If empty or unset, **all** operations are rejected (`ALLOWLIST_EMPTY`).
- **Sensitive App Blocklist**: `Terminal`, `iTerm2`, `Warp`, `Alacritty`, `Kitty`, `Ghostty`, `WezTerm`, `Hyper`, `Keychain Access`, and `System Settings` (`System Preferences`) are always blocked (`SENSITIVE_APP_BLOCKED`), even if added to `MACOS_CONTROL_ALLOWLIST`.
- **Window-Relative Coordinates & Active App Guard**: `mouse_action` defaults to `coordinateSpace: "window"` (rejecting out-of-bounds coordinates), and both `mouse_action` and `keyboard_action` verify that the frontmost active app is allowlisted and matches the target `windowId`.
- **Dual-Layer Enforcement**: Security checks are enforced in both the TypeScript MCP layer and the native Swift binary.
## Requirements
- **macOS 14.0+ (Sonoma or later)** — required for `ScreenCaptureKit` (`SCScreenshotManager`).
- **Node.js >= 22.0.0** — required for built-in global `WebSocket` and `fetch`.
- **Swift toolchain** (`xcode-select --install` or Xcode) — required to compile `native/MacosControlBridge.swift`.
- **`chrome-headless-shell` / Google Chrome** (optional, for `cdp_*` tools; native AX tools work without it) — discovers executable `chrome-headless-shell` on `PATH`, `/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`, `~/bin`, `~/.local/share/chrome-headless-shell`, `/Applications/chrome-headless-shell`, or optional Puppeteer/Playwright caches (validating symlinks via `realpath`). `MACOS_CONTROL_CDP_BROWSER_PATH` selects a binary path only and does **not** implicitly authorize non-`chrome-headless-shell` binaries in `background_strict`; `MACOS_CONTROL_CDP_ALLOW_CHROME_FALLBACK=1` (or `MACOS_CONTROL_INPUT_MODE=foreground`) is required to permit `Google Chrome.app` fallback.
## Build & Test
```bash
npm install
npm run build
npm run test:ci # Permission-independent unit & validation tests (also runs in CI)
npm test # Full local suite (includes macOS Accessibility/GUI & Chrome CDP E2E tests; keep desktop idle)
```
## Register Globally in Antigravity
Add the following entry to your global Antigravity `mcp_config.json` (typically `~/.gemini/antigravity/mcp_config.json`):
```json
{
"mcpServers": {
"macos-computer-use": {
"command": "node",
"args": [
"/path/to/macos-computer-use-mcp/dist/index.js"
],
"env": {
"MACOS_CONTROL_ALLOWLIST": "Simulator,TextEdit"
}
}
}
}
```
> Adjust `MACOS_CONTROL_ALLOWLIST` to only the specific apps you want to automate.
## Required macOS Permissions
Grant both permissions in **System Settings → Privacy & Security** to the host application/process running the MCP server (e.g., Antigravity / Node):
1. **Screen Recording** — required for `capture_window` (`screencapture -l`).
2. **Accessibility** — required for `mouse_action` and `keyboard_action` (`CGEvent` posting).
If either permission is missing, the server returns a clear `SCREEN_RECORDING_DENIED` or `ACCESSIBILITY_DENIED` error.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues