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.
$ 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-ids (Compose testTag) are supported and
preferred when they exist.
Install
Requires Python 3.10+, adb on PATH, and a device with USB debugging enabled.
# 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:
git clone https://github.com/vaibhavreddys/android-agent
cd android-agent
pip install -e ".[mcp]"
CLI
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.
# 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:
android-agent run examples/login_flow.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)
android-agent-mcp # stdio transport
Register it with your client:
{
"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 — 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 — 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:
dumpsysbeforeapp_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 betweenDeviceandWatcheracross uiautomator2 majors; polling the hierarchy costs more than the transition itself. - Read text back after writing it. A Compose
testTagoften sits on a wrapper, not the realEditText, so a write can land nowhere. The harness verifies and falls back to the focused field. - Prefer
resource-idonly 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 raisesdump_hierarchy_failed/empty_ui_dumpinstead ofref_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.
shellandrunexecute 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_PINis read from the environment and sent throughinput 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 dumpand 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.
Metadata
Release files for android-agent 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| android_agent-0.1.0.tar.gz | 31.7 kB | Without provenance | Details for android_agent-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| android_agent-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for android_agent-0.1.0-py3-none-any.whl |
Total release size: 61.4 kB
Release files / android_agent-0.1.0.tar.gz
| Download URL | android_agent-0.1.0.tar.gz |
|---|---|
| Size | 31.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5bb808814f395c3fe0a9ef38d8d662625590f74052a5d982b0c7c0f0d25f4331
|
|
BLAKE2b-256 checksum How to use checksums |
26d6492dde225694f49625cb71e6a0e49031140df6a3a8fa6e69030cab98f02c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Release files / android_agent-0.1.0-py3-none-any.whl
| Download URL | android_agent-0.1.0-py3-none-any.whl |
|---|---|
| Size | 29.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
903f28ec7e173dd6376fa706bc159c694b839ced428ebea6a75b9c7447f01cae
|
|
BLAKE2b-256 checksum How to use checksums |
072bacdb4542ed8360efd72092ee1679e8da3505c11544464f4d573aedb40065
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Security for android-agent 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.