Skip to main content
Glama
README.md
# android-agent

**A state-aware Android UI harness for coding agents.** It turns a phone
(emulator, USB, or wireless adb) into a legible, scriptable surface: compact JSON
state in, verified actions out — and an MCP server so Claude/Cursor/Codex can
drive it as tools.

```console
$ android-agent --app com.example.app state
{
  "focus": { "package": "com.example.app", "activity": "com.example.app.MainActivity" },
  "status": "ok",
  "visible_texts": ["Sign in", "Phone number", "Continue", "Need help?"],
  "interactive_elements": [
    { "ref": "e1", "type": "EditText", "label": "phone_input", "editable": true,
      "value": "", "hint": "Phone number", "tap_center": [540, 812] },
    { "ref": "e2", "type": "Button", "label": "Continue", "id": "continue_button",
      "clickable": true, "tap_center": [540, 1310] }
  ]
}
```

## The problem it solves

`uiautomator dump` returns the entire view hierarchy as **one single line of
XML** — 14–34 KB on a normal screen. Paste that into a model's context a few
times and the loop is dead: you have spent your context budget on
`bounds="[0,0][1080,2400]"` and `class="android.widget.FrameLayout"`.

Agents don't need the tree. They need: *what app is focused, what text is on
screen, what can I tap, and what happened after I tapped.*

That is what this harness returns — typically **10–30× smaller**, with the
focused app, empty-state and lock-screen cases handled explicitly instead of
degenerating into "element not found".

Measured on a reference device with `benchmarks/token_cost.py` (30 interactive
elements, 16 visible strings):

| Observation | Raw `uiautomator` XML | `android-agent state` |
|---|---|---|
| Bytes | 57,561 | 4,421 |
| ≈ tokens | 14,390 | 1,105 |
| Ratio | 1× | **13×** |

Denser screens compress better; text-light screens compress less. Run the
benchmark on your own device — the numbers are per-screen, not universal.

## Two ideas, and that's the whole design

**1. Every action returns the new state.** No fire-and-forget taps. The harness
does not trust that a tap worked; it re-reads the UI and shows you the result, so
an agent verifies instead of assuming. This is the single biggest reliability win
over coordinate-driven scripting.

**2. Refs are ephemeral on purpose.** Elements are numbered `e1..eN` for the
current screen only, and they expire after any action. There is no stale
reference to misuse — if a layout changed, the old ref is simply gone and the
agent must re-read. Stable `resource-id`s (Compose `testTag`) are supported and
preferred when they exist.

## Install

Requires Python 3.10+, `adb` on `PATH`, and a device with USB debugging enabled.

```bash
# CLI only (one dependency: uiautomator2)
pip install android-agent

# CLI + MCP server
pip install "android-agent[mcp]"

# Isolated, no venv needed
pipx install "android-agent[mcp]"
```

Working from source:

```bash
git clone https://github.com/vaibhavreddys/android-agent
cd android-agent
pip install -e ".[mcp]"
```

## CLI

```bash
android-agent devices                    # what adb transports are visible
android-agent state                      # focus + texts + tappable elements
android-agent --app com.example.app launch
android-agent tap e2                     # tap by ref from the last state
android-agent tap continue_button        # ...or by resource-id (survives layout changes)
android-agent tap 540 1310               # ...or by pixel
android-agent type e1 "9876543210"       # focus, clear, type, verify
android-agent key back                   # or home / recents / enter / KEYCODE_*
android-agent swipe up
android-agent edge-back                  # predictive-back edge gesture
android-agent wait "Welcome" 10
android-agent find "continue"            # locate without tapping
android-agent shell "pm list packages | grep example"
android-agent logcat 200 "FATAL|AndroidRuntime"
```

Every command prints JSON. Flags go **before** the subcommand:

| Flag | Effect |
|---|---|
| `--app PACKAGE` | Pin the target app; actions fail loudly if it loses focus |
| `--serial SERIAL` | Pin one adb transport |
| `--compact` | Single-line JSON (fewer tokens) |
| `--bounds` | Include raw pixel rects |
| `--screenshot PATH` / `--no-screenshot` | Where / whether to capture |

| Env var | Purpose |
|---|---|
| `ANDROID_AGENT_APP_PACKAGE` | Default target package |
| `ANDROID_AGENT_SERIAL` | Default transport |
| `ANDROID_AGENT_UNLOCK_PIN` | PIN for a secured device (wake + unlock) |
| `ANDROID_AGENT_STATE_DIR` | Where artifacts land (default `~/.cache/android-agent`) |
| `ANDROID_AGENT_SETTLE_SECONDS` | Post-action settle time |
| `ANDROID_AGENT_NO_LOCK` | Disable the cross-process device lock |
| `ADB` / `ANDROID_HOME` | adb discovery when it isn't on `PATH` |

## Multi-step flows: one connection, not one process per step

Each standalone CLI call pays the connection + dump cost (~1 s on a fast device,
5–8 s on a slow one). A 12-step journey as 12 processes is 12 connections. As one
`run`, it is one:

```bash
android-agent run examples/login_flow.json
```

```json
[
  { "cmd": "launch", "args": ["com.example.app"] },
  { "expect": "Sign in", "timeout": 15 },
  { "tap": "phone_input" },
  { "cmd": "type", "args": ["phone_input", "9876543210"] },
  { "tap": "continue_button", "expect": "Enter the code" }
]
```

`expect` is awaited **after** the step runs, and a miss marks the step failed
rather than silently continuing. Shorthand (`{"tap": "e3"}`) and full form
(`{"cmd": "tap", "args": ["e3"]}`) are both accepted.

## MCP server (drive it from an agent)

```bash
android-agent-mcp          # stdio transport
```

Register it with your client:

```json
{
  "mcpServers": {
    "android": { "command": "android-agent-mcp", "args": [] }
  }
}
```

The server is a thin adapter over the same command surface, so the CLI and MCP
behaviour cannot drift. It exposes 20 tools — `get_state`, `tap`, `tap_at`,
`type_text`, `press_key`, `swipe`, `edge_back`, `long_press`, `wait_for_text`,
`find_elements`, `launch_app`, `run_flow`, `shell`, `logcat`, `screenshot`,
`dump_ui`, `list_devices`, `set_target_app`, `reconnect` — and keeps a
**persistent device session**, which is the whole point of running as a server
rather than shelling out per call.

## Design notes

Details that took longer than they should have, written up so you don't repeat
them:

- **[A locked phone looks exactly like a broken app](https://github.com/vaibhavreddys/android-agent/blob/main/docs/locked-device.md)** —
  why an empty element list plus a black screenshot is a keyguard problem, and
  the ~0.1 s detection that replaces a ~10 s one.
- **[When wireless ADB switches itself off](https://github.com/vaibhavreddys/android-agent/blob/main/docs/wireless-adb.md)** — the
  measured root cause (band steering, not mDNS) and the five churn bugs that make
  watchdog tooling flaky.

A few smaller decisions visible in the code:

- **`dumpsys` before `app_current()`** for focus detection. `app_current()` is
  unreliable on some OEM builds and costs seconds when it is wrong.
- **Settle by sleeping, not by polling.** `wait_stable()` moved between
  `Device` and `Watcher` across uiautomator2 majors; polling the hierarchy costs
  more than the transition itself.
- **Read text back after writing it.** A Compose `testTag` often sits on a
  wrapper, not the real `EditText`, so a write can land nowhere. The harness
  verifies and falls back to the focused field.
- **Prefer `resource-id` only when it is unique.** List rows commonly reuse one
  id per row; blindly clicking by id always hits row 1.
- **Connections are serialised with an advisory lock.** A device has one
  UiAutomation slot; two agents connecting at once make atx-agent restart its
  server and the loser gets `UiAutomationService ... already registered`. The
  lock covers connect, not the whole session, so a long-lived MCP server does not
  block a CLI call.

## Security notes

- **Runs entirely locally.** No telemetry and no network calls of its own — the
  only traffic is adb to the device you name.
- **`shell` and `run` execute arbitrary commands** on the device as the shell
  user. That is the point of an escape hatch; never point this at a device you
  do not control.
- **`ANDROID_AGENT_UNLOCK_PIN`** is read from the environment and sent through
  `input text`. It is never written to disk or logged.
- **Releases** are built and published by this repo's GitHub Actions workflow
  using OIDC Trusted Publishing, so no long-lived PyPI token exists to leak.

## Limitations

- **One UiAutomation slot.** uiautomator2, `uiautomator dump` and Maestro all
  compete for it. Don't run them concurrently.
- **Behind `FLAG_SECURE`** (banking/DRM apps) the screenshot stays black even
  when unlocked. The UI tree is still readable, so the harness degrades to
  text-only.
- **No visual assertions.** This reads the accessibility tree, not pixels. Use a
  screenshot-diff tool for "does it *look* right".
- **Not a test framework.** There is no runner, no reporting, no retries at the
  suite level. Maestro/Appium do that well; this is the layer underneath, built
  for an agent deciding its next step.

## License

MIT — see [LICENSE](https://github.com/vaibhavreddys/android-agent/blob/main/LICENSE).