Android Control MCP Server
Servidor MCP de Control de Android
Un servidor Model Context Protocol (MCP) listo para producción, construido en Node.js, que permite a los asistentes de IA (como Claude Desktop, Cursor y flujos de trabajo agénticos personalizados) observar, razonar y controlar dispositivos Android conectados.
🌟 Características
👀 Observación tipo Computer-Use: Captura de pantalla PNG de alta resolución devuelta directamente como bloques de imagen MCP junto con metadatos del dispositivo.
🔍 Análisis de jerarquía UIAutomator: Analizador inteligente de volcados XML que transforma árboles de UI de Android verbosos en JSON compacto y estructurado.
🎯 Clic en elementos semánticos: Haga clic en botones y controles por su texto visible, descripción de accesibilidad o ID de recurso sin necesidad de cálculos manuales de píxeles.
⚡ Gestos y entrada rápidos: Toque con precisión de píxel, deslizamiento multi-coordenada, desplazamiento direccional, emulación de teclas de hardware y escritura de texto con escape de shell.
📱 Gestión del ciclo de vida de aplicaciones: Inicie aplicaciones por nombre de paquete e inspeccione la actividad en primer plano actualmente enfocada.
🛡️ Seguridad y sandboxing: Validación de coordenadas de entrada contra los límites reales de la pantalla, códigos de tecla estrictamente permitidos, saneamiento de argumentos, tiempos de espera de comandos y registro estricto de
stderrpara garantizar la integridad del flujo MCP stdio.🔄 Soporte multi-dispositivo: Detecta automáticamente los dispositivos conectados o apunta a dispositivos específicos mediante
ANDROID_DEVICE_ID.
Related MCP server: autoglm-mcp-server
🏗️ Arquitectura
AI Client (Claude Desktop, Cursor, Agent)
│
│ stdio transport (JSON-RPC)
▼
Node.js MCP Server
│
├── Stderr Structured Logger
├── Zod Schema Validation
│
├── ADB Controller Layer
│ ├── Device Resolver (auto-detect or target serial)
│ ├── Input Engine (tap, swipe, keyevent, text, scroll)
│ ├── Screenshot Manager (exec-out binary stream)
│ └── App Manager (launch, foreground inspection)
│
└── UIAutomator Engine
├── XML Hierarchy Dump & Normalizer
├── Bounds & Center Coordinate Extractor
└── Semantic Element Finder & Click Resolver
│
▼
Android Device / Emulator📋 Requisitos previos
Node.js:
v20.0.0o superior (node -v)Android SDK Platform-Tools: ADB (
adb) instalado y accesible en suPATHdel sistema (o configurado medianteADB_PATH).Dispositivo o emulador Android:
Dispositivo físico: Conéctelo por USB, habilite Opciones de desarrollador y Depuración por USB.
Emulador: AVD de Android Studio, Genymotion o emulador sin interfaz gráfica.
Verificar la conexión del dispositivo
adb devices -lDebería ver su dispositivo listado como device:
List of devices attached
emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64🚀 Instalación e inicio rápido
# Clone or navigate to the repository
cd c:/Users/Abhishek/Code/mcp
# Install dependencies
npm install
# Run unit tests
npm test
# Start the MCP server
npm start⚙️ Configuración
Cree un archivo .env o pase variables de entorno:
# Target device ID (serial number). If omitted and 1 device is connected, it auto-selects.
ANDROID_DEVICE_ID=
# Custom path to ADB executable if not in PATH
# Windows: C:\Users\<user>\AppData\Local\Android\Sdk\platform-tools\adb.exe
# macOS: /Users/<user>/Library/Android/sdk/platform-tools/adb
ADB_PATH=adb
# Log level: debug | info | warn | error
LOG_LEVEL=info
# Default ADB timeout in milliseconds
ADB_TIMEOUT_MS=15000🔌 Conexión a clientes MCP
1. Configuración de Claude Desktop
Agregue lo siguiente a su claude_desktop_config.json:
Windows:
%APPDATA%\Claude\claude_desktop_config.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"android-control": {
"command": "node",
"args": ["C:/Users/Abhishek/Code/mcp/src/index.js"],
"env": {
"ANDROID_DEVICE_ID": "",
"ADB_PATH": "adb",
"LOG_LEVEL": "info"
}
}
}
}2. Configuración MCP de Cursor / Windsurf
En Features > MCP Servers de Cursor o en la configuración de Windsurf:
Nombre:
android-controlTipo:
commandComando:
node C:/Users/Abhishek/Code/mcp/src/index.js
🛠️ Referencia de herramientas MCP
1. android_device_info
Obtenga metadatos completos de hardware y sistema operativo del dispositivo.
Parámetros:
deviceId(string opcional): Número de serie del dispositivo objetivo.
Ejemplo de respuesta:
{ "deviceId": "emulator-5554", "model": "Pixel 8", "manufacturer": "Google", "androidVersion": "15", "sdk": 35, "resolution": { "width": 1080, "height": 2400 }, "connectionState": "connected" }
2. android_screenshot
Capture la pantalla de Android como un bloque de contenido de imagen MCP (image/png).
Parámetros:
deviceId(string opcional): Número de serie del dispositivo objetivo.
Devuelve: Bloque de datos de imagen PNG en base64 + metadatos de dimensiones.
3. android_ui_dump
Vuelca la jerarquía UIAutomator de la pantalla actual en un formato JSON compacto y amigable para IA.
Parámetros:
deviceId(string opcional): Número de serie del dispositivo objetivo.
Ejemplo de salida:
{ "package": "com.android.settings", "activity": "com.android.settings.Settings", "totalElements": 24, "interactiveElementsCount": 8, "elements": [ { "index": 0, "text": "Network & internet", "resourceId": "android:id/title", "className": "TextView", "clickable": true, "bounds": [196, 340, 1016, 400], "center": [606, 370] } ] }
4. android_find_element
Busca elementos de UI que coincidan con criterios específicos en la pantalla actual.
Parámetros:
text(string opcional): Texto visible (exacto o parcial).contentDescription(string opcional): Etiqueta de accesibilidad.resourceId(string opcional): ID de recurso.className(string opcional): Nombre de clase del widget.clickable(boolean opcional): Filtrar por capacidad de clic.exactMatch(boolean opcional, por defectofalse): Coincidencia exacta de cadena.
5. android_click_element
Encuentra un elemento y hace clic en su punto central en un solo paso.
Parámetros:
text(string opcional): Texto del elemento.contentDescription(string opcional): Descripción de contenido del elemento.resourceId(string opcional): ID de recurso del elemento.className(string opcional): Clase del elemento.
6. android_tap
Toca en coordenadas exactas (x, y) con validación de límites de pantalla.
Parámetros:
x(número): Coordenada X.y(número): Coordenada Y.
7. android_swipe
Realiza un gesto de arrastre / deslizamiento entre dos puntos.
Parámetros:
x1,y1(números): Coordenadas de inicio.x2,y2(números): Coordenadas de fin.duration(número opcional, por defecto: 300): Duración en milisegundos.
8. android_type_text
Escribe texto en la entrada actualmente enfocada. Maneja la codificación de espacios (%s) y el escape de caracteres de shell.
Parámetros:
text(string): Texto a escribir.
9. android_press_key
Presiona una tecla de hardware o de navegación.
Teclas admitidas:
HOME,BACK,ENTER,TAB,ESC,DELETE,SPACE,VOLUME_UP,VOLUME_DOWN,POWER,APP_SWITCH,CAMERA, etc.Parámetros:
key(string): Nombre de la tecla o código de tecla numérico.
10. android_scroll
Desplazamiento direccional calculado contra las dimensiones reales de la pantalla.
Parámetros:
direction(string:up|down|left|right)amount(número opcional): Distancia de desplazamiento en píxeles.
11. android_launch_app
Inicia una aplicación por su nombre de paquete.
Parámetros:
packageName(string): p. ej.com.android.settings,com.google.android.youtube.activity(string opcional): Nombre de actividad específica.
12. android_current_app
Inspecciona el paquete y la actividad en primer plano actualmente enfocados.
13. android_execute_action (Herramienta unificada de Computer-Use)
Despachador de acciones unificado único que admite todas las acciones: tap, swipe, type, press_key, click_element, scroll, launch_app.
{
"action": "click_element",
"text": "Wi-Fi"
}🤖 Flujo de trabajo de IA recomendado: Observar → Razonar → Actuar → Verificar
1. OBSERVE:
AI calls `android_screenshot` and `android_ui_dump`.
2. REASON:
AI inspects visual and UI structure to identify target elements.
3. ACT:
AI calls `android_click_element`, `android_type_text`, or `android_scroll`.
4. VERIFY:
AI captures another screenshot/dump to confirm desired state change.🧪 Pruebas
Ejecute la suite de pruebas automatizada:
npm testLas pruebas usan Vitest y simulan la capa de ejecución de ADB, lo que permite una verificación unitaria completa sin necesidad de un dispositivo Android físico conectado durante CI/CD.
🔒 Mejores prácticas de seguridad
Sin ejecución arbitraria de shell: El servidor NO expone herramientas de ejecución de
adb shellsin procesar.Invocación segura de procesos: Todos los comandos usan
child_process.execFilecon matrices de argumentos explícitas para prevenir la inyección de shell.Saneamiento de entrada: Los nombres de paquete, códigos de tecla y parámetros de coordenadas se validan estrictamente mediante esquemas Zod y verificación de límites.
Registro aislado de stderr: Todos los registros se dirigen exclusivamente a
stderrpara mantener el cumplimiento estricto del protocolo JSON-RPC enstdout.
📄 Licencia
MIT
Available Tools
13 toolsandroid_click_elementB
Find and click a UI element on the current Android screen by its visible text, content description, or resource ID. Computes the center of the element and executes a precise tap.
Inputs: text, deviceId, className, exactMatch, +2 more.
android_current_appA
Get the package name and activity of the currently focused foreground Android application.
Inputs: deviceId.
android_device_infoA
Get detailed information about the connected Android device, including device ID, model, manufacturer, Android OS version, SDK level, and screen resolution.
Inputs: deviceId.
android_execute_actionC
Execute a high-level Android action in a single tool call. Supports tap, swipe, type, press_key, click_element, scroll, and launch_app.
Inputs: action (required), x, y, x1, +13 more.
android_find_elementA
Search for UI elements on the current Android screen by visible text, content description, resource ID, or class name. Returns matching elements with their computed center tap coordinates.
Inputs: text, deviceId, className, clickable, +3 more.
android_launch_appB
Launch an Android application by its package name (e.g. "com.android.settings", "com.google.android.youtube", "com.android.chrome").
Inputs: packageName (required), activity, deviceId.
android_press_keyC
Press an Android hardware or navigation key. Supported keys include: HOME, BACK, CALL, ENDCALL, VOLUME_UP, VOLUME_DOWN, POWER, CAMERA, CLEAR, COMMA, PERIOD, TAB, SPACE, ENTER, DELETE, etc.
Inputs: key (required), deviceId.
android_screenshotA
Capture the current screen of the Android device as a PNG image for visual inspection and AI computer-use reasoning.
Inputs: deviceId.
android_scrollB
Scroll the screen in a specified direction (up, down, left, right).
Inputs: direction (required), amount, deviceId.
android_swipeA
Perform a swipe / drag gesture between two points (x1, y1) and (x2, y2) with a configurable duration.
Inputs: x1 (required), x2 (required), y1 (required), y2 (required), +2 more.
android_tapB
Tap at specific (x, y) pixel coordinates on the Android device screen.
Inputs: x (required), y (required), deviceId.
android_type_textA
Type text into the currently focused Android input field. Handles escaping for spaces and special characters.
Inputs: text (required), deviceId.
android_ui_dumpA
Dump the current Android screen UI hierarchy using UIAutomator. Returns a structured, compact list of visible and interactive UI elements with their text, resource IDs, and screen bounds.
Inputs: deviceId.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 13 tools
Most tools have clearly distinct purposes, but android_tap, android_click_element, and android_execute_action overlap in interaction, differing only by abstraction level (raw coordinates, element-based, and high-level bundling). Descriptions help disambiguate these, so the overlap is minor.
All tools share the 'android_' prefix, which is good, but the naming pattern is inconsistent: some are bare nouns (screenshot, scroll), some are verb phrases (type_text, launch_app), and some are noun phrases (current_app, device_info). This mix of conventions is still readable but not fully predictable.
With 13 tools, the server is well-scoped for a mobile automation domain, offering both low-level gestures and high-level actions without redundancy. This count is appropriate and each tool earns its place.
The tool surface covers core UI automation: screen capture, interaction (tap, swipe, type, press, scroll), element discovery (ui_dump, find_element, click_element), and app control (launch_app, current_app). Missing advanced gestures like pinch or long-press, but these are not essential for typical agent tasks.
Maintenance
Related MCP Connectors
Let Claude, ChatGPT and other agents use your Android phone: see the screen, tap, type, open apps.
Cloud Android devices for AI agents: install an APK, read the screen, tap, type, read logcat.
Give your AI agent a real cloud Android phone: push APKs, drive it, get screenshots and logs.
Cloud Android phones for AI agents: create a phone, read the screen, tap, type, install APKs, park.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables AI assistants to interact with Android devices and emulators via ADB, providing tools for screenshots, UI inspection, touch and text input, app management, and device control.42143 npm23MIT
- AlicenseAqualityDmaintenanceEnables AI models to control Android devices via ADB through natural language commands, supporting screen analysis and automated actions.357 npmMIT
- FlicenseBqualityDmaintenanceEnables AI agents to control Android devices via ADB, supporting gestures, input, screenshots, UI analysis, and app management.191-
- AlicenseAqualityCmaintenanceEnables AI agents to control, inspect, and automate Android devices, Waydroid containers, and AVD emulators over ADB. Provides tools for screenshots, UI-hierarchy text-based tapping, gestures, key presses, text input, app management, and raw shell commands.12MIT