Metadata-Version: 2.4
Name: android-agent
Version: 0.1.1
Summary: State-aware Android UI harness for coding agents: compact JSON state, closed-loop actions, MCP server.
Author-email: vaibhavreddys <vaibhavreddys@users.noreply.github.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/vaibhavreddys/android-agent
Project-URL: Source, https://github.com/vaibhavreddys/android-agent
Project-URL: Issues, https://github.com/vaibhavreddys/android-agent/issues
Keywords: android,adb,uiautomator,mcp,ai-agent,automation,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: uiautomator2<4,>=3.0
Provides-Extra: mcp
Requires-Dist: mcp>=1.2; extra == "mcp"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Dynamic: license-file

# android-agent

[![PyPI version](https://img.shields.io/pypi/v/android-agent?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/android-agent/)
[![Python versions](https://img.shields.io/pypi/pyversions/android-agent?style=for-the-badge&logo=python&logoColor=white)](https://pypi.org/project/android-agent/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green?style=for-the-badge)](https://github.com/vaibhavreddys/android-agent/blob/main/LICENSE)
[![MCP compatible](https://img.shields.io/badge/MCP-compatible-00D4AA?style=for-the-badge)](https://modelcontextprotocol.io/)

<!-- mcp-name: io.github.vaibhavreddys/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.

**From PyPI** (Python 3.10+):

```bash
pip install android-agent                                   # CLI only
pip install "android-agent[mcp]"                            # CLI + MCP server
pipx install "android-agent[mcp]"                           # isolated, no venv to manage
uvx --from "android-agent[mcp]" android-agent-mcp           # zero-install MCP server
```

`pip`/`pipx` need `adb` on `PATH`; `uvx` fetches the package on first run and
caches it. Pick `[mcp]` if you want Claude/Cursor/Codex to drive the device —
the bare package has only one dependency (`uiautomator2`).

**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 |
| `--allow PACKAGE` | Accept this package as "the app" too (repeatable) |
| `--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 |

### Android hands off between packages

Settings opens `com.android.settings.intelligence` for search. Share sheets,
permission prompts and in-app WebViews are all owned by *other* packages. An
`--app` pin that treats every one of those as "wrong app" goes blind exactly
when the agent needs to act.

So the pin is two-sided: `state` always reads the package that is actually in
the foreground and always reports `elements_from`, and it sets
`status: target_app_not_focused` when that package isn't yours. Reading never
lies; only *acting* requires permission.

```bash
# read-only: flagged, but still usable
android-agent --app com.android.settings state
# {"status": "target_app_not_focused", "elements_from": "com.android.settings.intelligence", ...}

# declare the hand-off expected, then act on it
android-agent --app com.android.settings --allow com.android.settings.intelligence type e2 "wifi"
```

`ANDROID_AGENT_ALLOWED_PACKAGES` takes the same list, comma-separated.

| Env var | Purpose |
|---|---|
| `ANDROID_AGENT_APP_PACKAGE` | Default target package |
| `ANDROID_AGENT_ALLOWED_PACKAGES` | Comma-separated hand-off packages (same as repeated `--allow`) |
| `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.
- **An empty dump is a failure, not an empty screen.** uiautomator2 does not
  raise when accessibility returns nothing; it hands back `<hierarchy/>`. That
  would surface as "element not found" for a button that is plainly on screen,
  so an empty dump gets the same retries as an exception and a persistent one
  raises `dump_hierarchy_failed` / `empty_ui_dump` instead of `ref_not_found`.
- **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 validated in CI (`twine check`). Uploads use either
  OIDC Trusted Publishing from GitHub Actions or a PyPI API token supplied at
  release time — no credential is stored in this repo.

## 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).
