Skip to main content
Glama
Steph-ux

Android MCP

by Steph-ux

Android MCP

Полное управление Android из любого ИИ-агента — Claude, OpenCode, Windsurf, Cursor… 7 категориальных инструментов MCP · Живой просмотр 90 кадров/с · WiFi ADB · установка приложений не требуется


Быстрая демонстрация

android_screen(action="screenshot")                          # PNG capture
android_screen(action="ocr")                                 # visible text
android_interact(action="tap", params={"x": 540, "y": 960}) # tap
android_interact(action="find", params={"text": "Send"})     # find + tap
android_system(action="battery")                             # battery info
android_screen(action="viewer")                              # 90fps interactive window on PC

Related MCP server: DeepADB

Архитектура

AI Agent (Claude / OpenCode / Windsurf / Cursor…)
        ↓  MCP Protocol (stdio)
    server.py          ← 7 categorical tools
        ↓
    device_manager.py  ← device selection, multi-device
        ↓
    backends/
        ├── adb_backend.py       ← PRIMARY  : uiautomator2 + direct ADB
        └── companion_backend.py ← FALLBACK : Flutter app WebSocket
        ↓
    N Android phones / emulators

ADB-бэкенд (основной) — работает на любом устройстве с включенным режимом разработчика. На телефон ничего устанавливать не нужно. Использует uiautomator2 + команды ADB.

Companion-бэкенд (резервный) — опциональное приложение Flutter, если ADB недоступен в сети.


Требования

  • Python 3.10+

  • ADB в переменной PATH (winget install Google.PlatformTools)

  • Android: Режим разработчика + отладка по USB (или отладка по WiFi)


Установка

git clone https://github.com/Steph-ux/android-mcp
cd android-mcp
pip install -r requirements.txt

# Initialize uiautomator2 (once per device)
python -m uiautomator2 init

Живой просмотр 90 кадров/с (опционально)

winget install Genymobile.scrcpy
python viewer.py

Конфигурация MCP

# Generate the correct JSON for your AI client
python mcp_config.py --client claude     # Claude Desktop
python mcp_config.py --client opencode  # OpenCode
python mcp_config.py --client windsurf  # Windsurf
python mcp_config.py --client cursor    # Cursor
python mcp_config.py --write            # write directly to config files

Пример для Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "android-mcp": {
      "command": "C:/Python312/python.exe",
      "args": ["D:/path/to/android-mcp/server.py"],
      "type": "stdio"
    }
  }
}

WiFi-подключение без USB (Android 11+)

# On the phone: Settings → Developer options → Wireless debugging → Pair device
adb pair 192.168.1.42:38765    # enter the code shown on the phone
adb connect 192.168.1.42:5555

Полное руководство → WIFI_PAIRING.md


7 инструментов MCP

Конвенция вызова: android_xxx(action="...", params={...}, device_id="serial") device_id всегда опционален (используется текущее выбранное устройство).


android_device — Управление устройством

Действие

Параметры

Описание

list

—

Все подключенные устройства (USB, WiFi, эмуляторы)

select

serial

Установить устройство по умолчанию

connect

host, port

WiFi ADB подключение

disconnect

—

Отключить текущее WiFi-устройство

info

—

Модель, ОС, разрешение, плотность

status

—

Устройство подключено и готово?

setup

—

Настройка анимаций, режима бодрствования, агента ATX


android_screen — Захват и трансляция

Действие

Параметры

Описание

screenshot

—

PNG-захват (обходит FLAG_SECURE) → изображение

region

x y width height

Захват определенной области → изображение

size

—

{width, height}

is_on

—

Экран включен?

wake

—

Разбудить экран

start_stream

—

Запустить ADB-поток (~16 кадров/с)

stop_stream

—

Остановить поток

live_frame

—

Последний кадр потока → изображение

ocr

lang

Извлечь видимый текст (Tesseract)

find_image

template_b64 threshold

Поиск по шаблону (OpenCV)

viewer

fps bitrate no_control

Запустить окно scrcpy 90 кадров/с на ПК


android_interact — Касания, клавиатура, UI

Действие

Параметры

Описание

tap

x y

Нажатие

double_tap

x y

Двойное нажатие

long_press

x y duration_ms

Длительное нажатие

swipe

x1 y1 x2 y2 duration_ms

Свайп

drag

x1 y1 x2 y2 duration_ms

Перетаскивание

pinch

x y scale duration_ms

Масштабирование щипком

multi_touch

points

Жесты несколькими пальцами

type

text

Ввод текста

clear

—

Очистить активное поле

submit

text

Ввод + Enter

key

key

Системная клавиша (HOME, BACK, ENTER, VOLUME_UP…)

combo

keys

Комбинация клавиш (коды клавиш)

hierarchy

—

Полное дерево UI XML (uiautomator2)

find

text partial_match

Найти элемент и нажать на него

wait

text timeout partial_match

Ожидание элемента

scroll

text direction max_swipes

Прокрутка до элемента

assert

text partial_match

Проверка видимости текста


android_app — Приложения

Действие

Параметры

Описание

launch

package

Запустить приложение

close

package

Принудительно остановить приложение

list

include_system

Список установленных приложений

install

apk_path

Установить APK с ПК

uninstall

package

Удалить приложение

current

—

Пакет приложения на переднем плане

url

url

Открыть URL

intent

action uri package extras

Отправить Android intent

settings

section

Открыть системные настройки (main wifi bluetooth display…)


android_files — Файлы

Действие

Параметры

Описание

push

local_path remote_path

ПК → телефон

push_b64

remote_path data

Base64 → телефон

pull

remote_path local_path

Телефон → ПК

pull_b64

remote_path

Телефон → base64

list

directory

Список содержимого директории


android_system — Система и сеть

Действие

Параметры

Описание

shell

command

Команда ADB shell

logs

lines package

Logcat

battery

—

Уровень заряда и состояние зарядки

clipboard_get

—

Чтение буфера обмена

clipboard_set

text

Запись в буфер обмена

volume

level stream

Установка громкости

rotation

rotation

Поворот экрана (0-3)

wifi

enabled

WiFi вкл/выкл

bluetooth

enabled

Bluetooth вкл/выкл

mobile_data

enabled

Мобильные данные вкл/выкл

notifications

—

Активные уведомления

gps

lat lng

Подмена GPS-координат

sensors

sensor

Акселерометр, гироскоп, свет…

wifi_list

—

Доступные WiFi сети

wifi_connect

ssid password

Подключиться к WiFi

contacts

search limit

Чтение контактов

sms

to message

Отправить SMS (требует подтверждения на телефоне)


android_automation — Пакетные операции и макросы

Действие

Параметры

Описание

batch

actions stop_on_error

Выполнить N действий за один вызов

macro_start

name

Начать запись макроса

macro_record

action …params

Добавить действие в макрос

macro_stop

—

Сохранить макрос

macro_list

—

Список сохраненных макросов

macro_replay

name delay_ms

Воспроизвести макрос

macro_delete

name

Удалить макрос


Живой просмотр — scrcpy 90 кадров/с

python viewer.py                  # auto-detect device, 90fps, interactive
python viewer.py --fps 60         # 60fps
python viewer.py --record         # record to .mp4
python viewer.py --record out.mp4 # named output file
python viewer.py --multi          # one viewer per connected device
python viewer.py --no-control     # read-only mode

Управление

Действие

Левый клик

Нажатие

Перетаскивание

Свайп

Правый клик

BACK

Прокрутка

Прокрутка

Alt+H

HOME

Alt+S

Скриншот → буфер обмена ПК

Alt+F

Полноэкранный режим

Alt+R

Поворот


Тесты

# Unit tests (no device required)
pytest tests/test_server_unit.py -v      # 94 tests

# Integration tests (ADB device required)
pytest tests/test_integration.py -v

Структура проекта

android-mcp/
├── server.py              # MCP server — 7 tools
├── viewer.py              # scrcpy 90fps interactive viewer
├── mcp_config.py          # JSON config generator
├── device_manager.py      # Multi-device management
├── relay.py               # ⚠️ LEGACY — companion fallback only
├── requirements.txt
├── pyproject.toml
├── WIFI_PAIRING.md
├── backends/
│   ├── adb_backend.py     # Primary backend (uiautomator2 + ADB)
│   └── companion_backend.py  # Fallback backend (Flutter app)
├── examples/
│   ├── agent_loop.py      # Autonomous automation loop
│   └── whatsapp_auto.py   # WhatsApp automation example
└── tests/
    ├── conftest.py
    ├── test_server_unit.py   # 94 unit tests
    └── test_integration.py   # Real device tests

Примеры

# WhatsApp — send a message
await android_app("launch", {"package": "com.whatsapp"})
await android_interact("find", {"text": "Alice"})
await android_interact("type", {"text": "Hello!"})
await android_interact("key",  {"key": "ENTER"})

# Batch in a single call
await android_automation("batch", {"actions": [
    {"action": "key",  "key": "HOME"},
    {"action": "tap",  "x": 540, "y": 200},
    {"action": "type", "text": "search query"},
    {"action": "key",  "key": "ENTER"},
]})

# Macro: record + replay
await android_automation("macro_start",  {"name": "login"})
await android_automation("macro_record", {"action": "tap",  "x": 540, "y": 400})
await android_automation("macro_record", {"action": "type", "text": "password"})
await android_automation("macro_stop")
await android_automation("macro_replay", {"name": "login"})

Смотрите examples/whatsapp_auto.py и examples/agent_loop.py для полных сценариев использования.


Лицензия

MIT

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables AI agents to fully control Android devices through over 30 tools for app management, UI automation, and vision-based analysis via ADB. It supports multi-device management, action recording, and smart execution strategies ranging from UI hierarchy parsing to coordinate-based interaction.
    37
    182 npm
    1
    MIT
  • A
    license
    B
    quality
    A
    maintenance
    A comprehensive MCP server that enables AI agents to interact with Android devices through Android Debug Bridge (ADB), offering 198 tools for device control, app management, diagnostics, and more.
    100
    75 npm
    19
    Apache 2.0
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to control Android devices via ADB, providing tools for screen capture, tap/swipe/input, app management, and diagnostics. Works locally over USB or WiFi and integrates with MCP clients like Claude and Cursor.
    1
    MIT