tailscale-adb-mcp
# tailscale-adb-mcp
[](https://github.com/razin-core/tailscale-adb-mcp/actions/workflows/ci.yml)
[](https://www.python.org/downloads/)
[](LICENSE)
Local Python MCP server (`stdio`, Pydantic v2) for **safe, deterministic Android UI automation and read-only device diagnostics** over Tailscale + Android Wireless Debugging — no root, no Appium, and no raw `dumpsys`/base64 flooding LLM context.
## Why This Exists
Running an AI agent directly against a personal Android phone over raw `adb shell` is fragile and unsafe: a heads-up notification, incoming call, or banking app can steal focus mid-tap, while raw `dumpsys` and base64 screenshots burn tens of thousands of tokens.
`tailscale-adb-mcp` puts a **deterministic Safety Layer** and a **compact `@e1..@eN` UI harness** between the LLM and `adb`:
## Architecture Overview
```mermaid
flowchart TD
A["MCP Client (Antigravity / Claude / Cursor)\nstdio JSON-RPC · 12 Pydantic v2 tools"] --> B["Deterministic Safety Layer (safety/)\nAllowlist · Denylist · Display #0 Focus · Top-Bar · APK Manifest"]
B --> C["UI Harness (harness/)\n@e1..@eN RefCache (TTL 20s) · Assert · Logs · 720px JPEG"]
B --> D["Read-Only Doctor (doctor/)\nBattery · Radio (LTE/NR) · System (RAM/ZRAM/Thermals)"]
C --> E["UiBackend Protocol\nAdbUiAutomatorBackend (v0.1) | UiAutomator2Backend (--extra u2)"]
D --> F["SubprocessAdbRunner (transport/)\ncreate_subprocess_exec · asyncio.Lock · TailscaleResolver"]
E --> F
F --> G["Android Device (no root)\nTailscale + Wireless Debugging"]
```
### Safety Guarantees (Fail-Closed)
- **Two-tier package policy:** hardcoded `DENYLIST_PACKAGES` (non-overridable) + mandatory `TAILSCALE_ADB_ALLOWLIST_PACKAGES` (empty = all UI/install actions blocked).
- **Focus & heads-up guards:** `FOREGROUND_MISMATCH` scoped to `Display #0` (`dumpsys window displays`), controlled exceptions for `permissioncontroller` and IME `type`, plus `TOP_BAR_GUARD_PX` (`y < 140px`) on both tap and swipe endpoints.
- **No stale taps or raw dumps:** `@eN` refs expire after `20s` and invalidate immediately after every `act`; `android_logs` uses `logcat -T` + `<= 80` lines; `android_screenshot` writes `<= 720px` `0o600` JPEGs to disk (no base64).
- **Pure-Python APK & path checks:** bounded binary `AndroidManifest.xml` verification before `adb install -r` (no `aapt2`), strict allowlisted POSIX path normalization, and local/remote symlink + `realpath` checks for `android_push`.
### Threat Model & Limitations
- **Trust boundary:** the local host, Tailscale ACLs, and active ADB session form the trusted perimeter; `tailscale-adb-mcp` protects the phone from LLM agent mistakes, hallucinations, and prompt injection, but does not replace host hardening or Tailnet ACLs.
- **Physical TOCTOU limit:** `_action_lock`, `RefCache` focus binding, and post-tap focus re-verification in `type` eliminate software races, but a physical window (~20–50 ms) between `dumpsys window` and `adb shell input tap` is inherent to the ADB protocol.
- **Display density (`TAILSCALE_ADB_TOP_BAR_GUARD_PX`):** default `140` targets FHD+ (~1080p); lower to `~90` on 720p screens or raise to `~190` on QHD+ (1440p).
- **Context privacy:** screenshots stay on local disk (`0o600`, no base64 in LLM context), radio diagnostics omit IMEI/IMSI/CellID, and `logcat` lines apply **best-effort** heuristic redaction for `Bearer`/`Basic` headers, JWTs, and common KV/JSON secret keys (`api_key`, `access_token`, `client_secret`, `password`, `secret`) — this does not guarantee detection of arbitrary opaque tokens.
## MCP Tools (12 Total)
| Category | Tool | What It Does |
| :--- | :--- | :--- |
| **Session** | `android_connect` | Dynamically resolves phone IP via `tailscale status --json`, recovers stale `offline` state, connects ADB |
| | `android_disconnect` | Disconnects active/specified ADB serial, clears `@eN` ref cache, resets `uiautomator2` handle |
| **UI Harness** | `android_snapshot` | Dumps UI hierarchy into compact `@e1..@eN` nodes (`<= 60` nodes, default/empty fields omitted) + focus metadata |
| | `android_act` | Safety-checked `tap`, `type` (strict ASCII), `swipe`, `back`, `launch`, `force_stop`; invalidates `@eN` cache |
| | `android_assert` | Polls UI for target text/`resource_id` while watching `logcat` for `FATAL EXCEPTION` / `ANR` (`CRASH_DETECTED`) |
| | `android_logs` | Capped (`<= 80` lines, `<= 240` chars/line) package `logcat` with post-crash fallback when `pidof` is empty |
| | `android_screenshot` | Resizes `screencap` via Pillow to `<= 720px` JPEG (`0o600` in `/tmp/tailscale_adb_mcp/`), returns file metadata only |
| **Files & APK** | `android_install` | Parses binary `AndroidManifest.xml` in pure Python (no `aapt2`), checks allowlist/denylist, runs `adb install -r` |
| | `android_push` | Pushes a local file strictly inside `TAILSCALE_ADB_ALLOWLIST_PUSH_DIRS` (blocks `..`, symlinks, shell metachars) |
| **Doctor (RO)** | `android_doctor_battery` | Level %, SOH %, cycle count, temperature °C, voltage mV, charging/health, full vs design capacity |
| | `android_doctor_radio` | Anonymized LTE/NR metrics (bands, EARFCN, bandwidth, RSRP/RSRQ/SINR, CA) with Android 16 `mCellInfo=[]` fallback |
| | `android_doctor_system` | Uptime, RAM/ZRAM, top `<= 10` processes by PSS, thermal zones (`<= 12`), `/data` storage |
## Quick Start
### 1. Install
```bash
git clone https://github.com/razin-core/tailscale-adb-mcp.git
cd tailscale-adb-mcp
uv sync --extra dev # Core + offline test suite (no uiautomator2 required)
uv sync --extra dev --extra u2 # Optional Phase 3 uiautomator2 backend
```
### 2. Configure MCP Client (`mcp_config.json`)
All policy and device settings are injected via environment variables (no hardcoded IPs or serials):
```json
{
"mcpServers": {
"tailscale-adb-mcp": {
"command": "/path/to/tailscale-adb-mcp/.venv/bin/tailscale-adb-mcp",
"args": [],
"env": {
"TAILSCALE_ADB_DEVICE_HINT": "your-phone-tailscale-hostname",
"TAILSCALE_ADB_ALLOWLIST_PACKAGES": "com.example.yourapp",
"TAILSCALE_ADB_ALLOWLIST_PUSH_DIRS": "/sdcard/Download/AppConfigs",
"TAILSCALE_ADB_UI_BACKEND": "adb"
}
}
}
}
```
### Environment Variables
| Variable | Default | Purpose |
| :--- | :--- | :--- |
| `TAILSCALE_ADB_ALLOWLIST_PACKAGES` | *(empty — fail-closed)* | Comma-separated packages allowed for UI actions, `launch`, `force_stop`, `install` |
| `TAILSCALE_ADB_ALLOWLIST_PUSH_DIRS` | *(empty — fail-closed)* | Comma-separated remote directories allowed for `android_push` |
| `TAILSCALE_ADB_DEVICE_HINT` | `""` | Tailscale node hostname for dynamic IP lookup |
| `TAILSCALE_ADB_SNAPSHOT_TTL_SEC` | `20` | Expiry TTL for `@eN` UI node references |
| `TAILSCALE_ADB_TOP_BAR_GUARD_PX` | `140` | Blocks taps/swipes in the heads-up notification zone unless `allow_top_bar=True` |
| `TAILSCALE_ADB_UI_BACKEND` | `adb` | `adb` (zero phone deps) or `uiautomator2` (live viewfinders / non-focusable overlays) |
## Verification & Testing
- **Offline unit suite (CI):** `154` tests running 100% offline against `FakeAdbRunner` and anonymized Android 16 fixtures (zero device required).
- **Live smoke test:** verified over Tailscale on Android 16 (`@pytest.mark.live`, excluded from CI).
```bash
uv run ruff check .
uv run pytest -m "not live" -v
```
## License
MIT — see [LICENSE](LICENSE).
TDQS
Scored across 12 tools
Each tool targets a clearly distinct ADB operation or diagnostic area: connection lifecycle, UI inspection/action/assertion, logs, screenshots, install, file push, and three separated doctor diagnostics. The closest pair, android_snapshot and android_assert, are still distinguishable because snapshot returns the UI tree while assert polls for a target and watches logcat.
All tools use a consistent android_ snake_case prefix, making the set easy to scan. A few names are noun-oriented (android_logs, android_screenshot, android_doctor_battery) rather than strict verb_noun, but the convention remains predictable.
Twelve tools is well within the appropriate range for an Android-over-ADB automation server. Each tool covers a distinct, useful capability without obvious redundancy.
The surface covers core device automation: connect/disconnect, UI inspection and actions, assertions, logs, screenshots, APK install, file push, and diagnostics. Minor gaps exist around file pull, uninstall, and broader shell/package lifecycle operations, but agents can work around many of these.