Skip to main content
Glama
README.md
# desktop-automation

[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
[![Platform: Windows 10/11](https://img.shields.io/badge/platform-Windows%2010%2F11-0078D6.svg)](#requirements)
[![MCP: 24 Tools](https://img.shields.io/badge/MCP-24%20tools%20%28zero--dep%20server%29-7C3AED.svg)](tools.json)

**Safety-first, OS-native Windows desktop automation skill & MCP server for AI agents.**

Give your AI agent verified mouse control, API-first keyboard input, Windows UI Automation (UIA) semantic element snapshots, numbered Set-of-Mark screenshots, pre-action perception guards, and Recycle Bin–only file safety — **without injecting scripts into web pages or relying on fragile visual coordinate guessing**.

Works out of the box with **Antigravity**, **Claude Desktop / Claude Code**, **Cursor**, **WorkBuddy**, or standalone Python scripts. See [SKILL.md](SKILL.md) for the agent-facing rules; this README is for humans setting it up.

---

## Why `desktop-automation`?

| Principle | How it works |
|---|---|
| **OS-native, zero script injection** | Operates real Windows apps and browsers at the OS / UIA accessibility layer (`RootWebArea` DOM scoping), never injecting scripts into pages. |
| **Hybrid UIA + Pixel grounding** | Semantic Windows UIA tree + Pillow numbered **Set-of-Mark** screenshots (`uia_inspector.py`), backed by programmatic pixel detection (`ui_detect.py`). |
| **Pre-Action Perception Guards** | `ui_click_element` re-verifies foreground window ownership, control enabled state, and aborts (`drift_detected=true`) if a live element moved beyond `max_drift_px`. |
| **API-first typing & clipboard safety** | Prefers `WM_SETTEXT` via `SendMessageTimeoutW` (focus-independent, verified by read-back); auto-falls back to clipboard paste with save/verify/restore without wiping non-text clipboards. |
| **Zero-dependency MCP server** | `mcp_server.py` speaks JSON-RPC 2.0 over stdio using pure Python stdlib (24 tools declared in `tools.json`) with lazy imports and structured `isError` responses. |
| **Hard safety boundaries** | Failsafe corner `(0, 0)` rejection, 2px mouse landing verification, `allowed_apps` allowlist, redacted JSONL audit trail, Recycle Bin–only `trash` (no symlinks, batch ≤ 10), and mandatory human handoff for logins / 2FA / CAPTCHAs. |

---

## Architecture

```text
Agent Host (Antigravity / Claude / Cursor / WorkBuddy)
   │
   ├── MCP stdio (mcp_server.py — 24 tools, pure stdlib, audit log)
   └── CLI / Skill (SKILL.md + references/)
          │
          ├── uia_inspector.py      Windows UIA tree, --browser-dom, Set-of-Mark, drift-guarded click
          ├── ui_detect.py          Window activate/probe, pixel verify_region, highlight, grid, wait
          ├── keyboard_input.py     WM_SETTEXT (2s timeout), clipboard fallback, UTF-16LE SendInput, safe hotkey
          ├── mouse_controller.py   Multi-monitor virtual screen, (0,0) failsafe, <=2px landing retry
          ├── desktop_automation.py doctor, scan (read-only), screenshot, clipboard, sysinfo, safe trash
          ├── detached_launcher.py  GUI process launcher & liveness check (--pid / name)
          ├── dpi_utils.py          Per-Monitor V2 DPI awareness & virtual screen bounds
          └── config.py             Optional config.json loader, allowed_apps policy, JSONL audit trail
```

---

## Requirements

- **OS**: Windows 10 / 11 (pure logic tests and `mcp_server.py` `tools/list` also run on Linux/macOS)
- **Python**: >= 3.10
- **Core dependencies** (`requirements.txt`): `pyautogui`, `pyperclip`, `Pillow`, `psutil`, `openpyxl`, `watchdog`, `requests`, `send2trash`
- **Optional extras** (`pyproject.toml`):
  - `uia`: `uiautomation>=2.0.18` (Apache-2.0) — enables `uia_inspector.py` (`ui_snapshot` / `ui_click_element`)
  - `fast-vision`: `numpy>=1.26.0` — vectorized pixel detection in `ui_detect.py`

---

## Install

### (a) MCP Server (Antigravity / Claude Desktop / Cursor)

1. Clone the repository and create a virtual environment:

```powershell
git clone https://github.com/kingsleyW-png/desktop-automation.git
cd desktop-automation
python -m venv .venv
.venv\Scripts\pip install -r requirements.txt
.venv\Scripts\pip install uiautomation   # optional: enables UIA snapshot & browser DOM
```

2. Add `desktop-automation` to your MCP config (e.g. `~/.gemini/config/mcp_config.json` for Antigravity, `claude_desktop_config.json` for Claude Desktop, or Cursor MCP settings — see [mcp.example.json](mcp.example.json)):

```json
{
  "mcpServers": {
    "desktop-automation": {
      "command": "C:/path/to/desktop-automation/.venv/Scripts/python.exe",
      "args": ["C:/path/to/desktop-automation/mcp_server.py"]
    }
  }
}
```

### (b) WorkBuddy / Skill Host (PowerShell)

From the repository root:

```powershell
./install.ps1
```

This copies the skill into `~/.workbuddy/skills/desktop-automation/` and creates a `.venv` inside it. Without `-Force` it refuses to overwrite an existing install; with `-Force` it backs up the existing directory first. Pass `-TargetDir <path>` to install into another skill host (e.g. `~/.claude/skills/desktop-automation`).

### (c) Environment Self-Check

```powershell
.venv\Scripts\python desktop_automation.py doctor
```

---

## Quick Start

```powershell
# 1. Semantic UIA snapshot + browser DOM extraction + Set-of-Mark screenshot
.venv/Scripts/python uia_inspector.py snapshot --window Chrome --browser-dom --annotate shot_som.png
.venv/Scripts/python uia_inspector.py click --window Chrome --id 12 --dry-run

# 2. Mouse control (virtual-screen validated, landing verified <= 2px)
.venv/Scripts/python mouse_controller.py move 100 200 --dry-run
.venv/Scripts/python mouse_controller.py click 100 200

# 3. Keyboard (API direct write first; auto-fallback; safe hotkeys)
.venv/Scripts/python keyboard_input.py api "Notepad" "text to type"
.venv/Scripts/python keyboard_input.py write "My App" "hello" --focus 1100 580
.venv/Scripts/python keyboard_input.py hotkey ctrl l --window Chrome --dry-run
.venv/Scripts/python keyboard_input.py read "Notepad"

# 4. Programmatic UI detection & pre-send check
.venv/Scripts/python ui_detect.py window Notepad
.venv/Scripts/python ui_detect.py activate Notepad
.venv/Scripts/python ui_detect.py check shot.png 878,524,1438,634
.venv/Scripts/python ui_detect.py wait 558,34,1454,682 --timeout 6

# 5. Read-only scan, screenshot, system info, doctor
.venv/Scripts/python desktop_automation.py scan <directory>
.venv/Scripts/python desktop_automation.py screenshot shot.png
.venv/Scripts/python desktop_automation.py sysinfo
.venv/Scripts/python desktop_automation.py doctor
```

---

## Configuration (`config.json`)

Copy [config.example.json](config.example.json) to `config.json` next to the scripts to customize:

- **`allowed_apps`**: non-empty allowlist of window title substrings (e.g. `["Chrome", "Notepad"]`); operations targeting windows outside the list are refused.
- **`audit`**: `{"enabled": true, "path": null}` enables redacted JSONL action logging (default `~/.desktop-automation/audit.jsonl`).
- **`protected_dirs` / `trash.batch_limit`**: customize protected paths and max batch size for `trash`.
- **`colour_thresholds` / `verify_region.min_proportion`**: tune pixel detection for dark themes or other apps.

---

## Safety Rules

- **Programmatic coordinates only**: click targets come from UIA snapshots or programmatic pixel / Win32 data — never visually estimated off a screenshot.
- **Verify before sending**: before any submit/send action, verify window/conversation title and input content (`ui_check`); stop if verification fails.
- **Human handoff for auth & challenges**: never enter credentials without explicit user approval; logins, 2FA, device verification, and CAPTCHAs are always completed by the user.
- **Recycle Bin only**: `trash` refuses symlinks and directories, requires `--yes`, caps batches at 10, and protects `Desktop / Downloads / Documents` subtrees plus top-level home files.
- **Blocked dangerous hotkeys**: `keyboard_hotkey` blocks OS lock/interrupt combos (`Ctrl+Alt+Del`, `Win+L`).

---

## Testing

Unit tests live in `tests/` (`tests/test_precision.py` and `tests/test_public.py`) and run cleanly on both **Windows** and **Linux**:

```bash
python -m unittest discover -s tests -v
```

See [TEST_REPORT.md](TEST_REPORT.md) for the end-to-end verification record and [CHANGELOG.md](CHANGELOG.md) for release notes.

## License

[MIT](LICENSE)