Doramagic 项目包 · 项目说明书

mobile-mcp 项目

生成时间:2026-05-13 17:52:49 UTC

项目概述

Mobile MCP(Mobile Model Context Protocol)是一个基于 Model Context Protocol (MCP) 标准的移动设备自动化框架。它使 AI 代理能够通过标准化的接口与 iOS、Android 设备进行交互,支持真机、模拟器和仿真器。资料来源:[README.md:1-10]()

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 系统架构图

继续阅读本节完整说明和来源证据。

章节 核心模块说明

继续阅读本节完整说明和来源证据。

章节 MCP 工具分类

继续阅读本节完整说明和来源证据。

简介

Mobile MCP(Mobile Model Context Protocol)是一个基于 Model Context Protocol (MCP) 标准的移动设备自动化框架。它使 AI 代理能够通过标准化的接口与 iOS、Android 设备进行交互,支持真机、模拟器和仿真器。资料来源:README.md:1-10

该项目的核心目标是通过 MCP 协议为 AI 助手提供移动设备控制能力,实现自动化测试、数据采集、UI 交互等多种场景。开发者无需编写原生代码,即可通过自然语言指令驱动移动设备完成复杂任务。资料来源:README.md:35-50

核心特性

Mobile MCP 具有以下核心特性:

特性描述
快速轻量利用原生无障碍树(Accessibility Tree)进行大多数交互,在无 a11y 标签时使用截图坐标方案
LLM 友好无需计算机视觉模型即可进行屏幕分析
视觉感知可评估和分析屏幕实际渲染内容
跨平台同时支持 iOS 和 Android 设备
灵活部署支持 stdio 和 SSE 两种服务器模式
安全认证SSE 模式支持 Bearer Token 授权验证

资料来源:README.md:50-60

架构设计

系统架构图

graph TD
    subgraph MCP客户端 ["MCP 客户端 (IDE/Agent)"]
        A[Claude Desktop]
        B[Cursor]
        C[VS Code]
        D[其他 MCP 兼容客户端]
    end
    
    subgraph MCP协议层 ["MCP 协议层"]
        E[stdio 模式]
        F[SSE Server 模式]
    end
    
    subgraph Mobile MCP 核心 ["Mobile MCP 核心"]
        G[src/server.ts<br/>MCP 服务器入口]
        H[设备管理器层]
        I[机器人抽象层]
    end
    
    subgraph 设备抽象层 ["设备抽象层"]
        J[Robot 接口]
        K[WebDriverAgent<br/>iOS WDA]
        L[MobileDevice<br/>Android ADB]
        M[iPhone Simulator<br/>模拟器支持]
    end
    
    subgraph 物理设备 ["物理/虚拟设备"]
        N[iOS 真机/模拟器]
        O[Android 真机/仿真器]
    end
    
    A --> E
    B --> E
    C --> F
    D --> F
    E --> G
    F --> G
    G --> H
    H --> I
    I --> J
    J --> K
    J --> L
    J --> M
    K --> N
    L --> O
    M --> N

核心模块说明

#### 1. MCP 服务器层 (src/server.ts)

MCP 服务器是整个系统的入口点,负责:

  • 注册和暴露所有 MCP 工具
  • 管理设备连接和会话
  • 处理工具调用请求
  • 提供 SSE 服务器模式支持

服务器通过 mobilecli 工具进行设备管理,并在启动时验证 mobilecli 的可用性。资料来源:src/server.ts:1-50

#### 2. 设备管理器层

设备管理器负责设备的发现、连接和管理:

管理器职责源码文件
IosManageriOS 设备发现和管理src/ios.ts
AndroidDeviceManagerAndroid 设备管理src/android.ts
IPhoneSimulatoriPhone 模拟器支持src/iphone-simulator.ts

资料来源:src/ios.ts:1-80

#### 3. 机器人抽象层 (src/robot.ts)

Robot 接口定义了所有设备交互的统一抽象:

interface Robot {
    // 设备信息
    getScreenSize(): Promise<ScreenSize>;
    getOrientation(): Promise<Orientation>;
    setOrientation(orientation: Orientation): Promise<void>;
    
    // 应用管理
    listApps(): Promise<InstalledApp[]>;
    launchApp(packageName: string, locale?: string): Promise<void>;
    terminateApp(packageName: string): Promise<void>;
    installApp(path: string): Promise<void>;
    uninstallApp(bundleId: string): Promise<void>;
    
    // 屏幕交互
    getScreenshot(): Promise<Buffer>;
    getElementsOnScreen(): Promise<ScreenElement[]>;
    tap(x: number, y: number): Promise<void>;
    doubleTap(x: number, y: number): Promise<void>;
    longPress(x: number, y: number, duration: number): Promise<void>;
    swipe(direction: SwipeDirection): Promise<void>;
    
    // 输入操作
    sendKeys(text: string): Promise<void>;
    pressButton(button: Button): Promise<void>;
    openUrl(url: string): Promise<void>;
}

资料来源:src/robot.ts:1-150

#### 4. 平台特定实现

##### iOS 实现 (src/webdriver-agent.ts)

iOS 设备通过 WebDriverAgent (WDA) 进行控制:

  • 通过 HTTP API 与 WDA 通信
  • 使用 /source/?format=json 获取页面元素
  • 使用 /screenshot 获取屏幕截图
  • 通过 /actions 端点执行手势操作

元素筛选支持以下类型:TextField, Button, Switch, Icon, SearchField, StaticText, Image

资料来源:src/webdriver-agent.ts:1-100

##### Android 实现 (src/mobile-device.ts)

Android 设备通过 mobilecli 工具进行控制:

  • 使用 dump ui 命令获取界面元素
  • 使用 io tap 执行点击操作
  • 使用 io text 输入文本
  • 使用 io button 模拟按键
  • 使用 device orientation 管理屏幕方向

资料来源:src/mobile-device.ts:1-100

主要功能

MCP 工具分类

Mobile MCP 提供了丰富的 MCP 工具,主要分为以下几类:

#### 设备信息类

工具名称功能描述
mobile_list_available_devices列出所有可用设备(模拟器、仿真器、真机)
mobile_get_screen_size获取设备屏幕尺寸(像素)
mobile_get_orientation获取当前屏幕方向
mobile_set_orientation设置屏幕方向(竖屏/横屏)

#### 应用管理类

工具名称功能描述
mobile_list_apps列出设备上所有已安装应用
mobile_launch_app启动指定应用(通过包名)
mobile_terminate_app终止运行中的应用
mobile_install_app安装应用(支持 .apk, .ipa, .app, .zip)
mobile_uninstall_app卸载应用

#### 屏幕交互类

工具名称功能描述
mobile_take_screenshot截图以了解屏幕内容
mobile_save_screenshot保存截图到文件
mobile_list_elements_on_screen列出屏幕元素及其坐标和属性
mobile_click_on_screen_at_coordinates在指定坐标点击
mobile_double_tap_on_screen双击指定坐标
mobile_long_press_on_screen_at_coordinates长按指定坐标
mobile_swipe_on_screen在屏幕上滑动(支持四个方向)

#### 输入与导航类

工具名称功能描述
mobile_type_keys向焦点元素输入文本
mobile_press_button按下设备物理按钮

资料来源:README.md:100-130

通信模式

Mobile MCP 支持两种通信模式:

stdio 模式(默认)

默认模式,Mobile MCP 通过标准输入输出与客户端通信。适用于大多数本地场景。

npx @mobilenext/mobile-mcp@latest

配置示例:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

SSE Server 模式

当需要远程访问或多人协作时,可启用 SSE 服务器模式:

npx @mobilenext/mobile-mcp@latest --listen 3000

可绑定到特定接口:

npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000

连接地址:http://<host>:3000/mcp

#### 认证配置

SSE 模式支持 Bearer Token 认证:

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

所有请求必须包含:Authorization: Bearer my-secret-token

资料来源:README.md:180-210

应用场景

主要用例

场景描述
原生应用自动化iOS 和 Android 应用的测试或数据录入场景
脚本化流程无需手动控制模拟器/仿真器或真机即可完成表单交互
多步骤用户旅程由 LLM 驱动的自动化用户流程
通用应用交互基于代理框架的移动应用交互
代理间通信支持移动自动化的代理间通信和数据提取

资料来源:README.md:30-40

典型工作流示例

#### 示例 1:应用测试与截图

打开指定应用,截取当前屏幕截图,
列出所有可见的 UI 元素,
然后点击"登录"按钮

#### 示例 2:多步骤表单填写

打开 Settings 应用,
导航到 "General" > "About",
滚动到页面底部,
记录设备的序列号和型号

#### 示例 3:内容搜索与保存

打开 Substack 网站,
搜索 "Latest trends in AI automation 2025",
打开第一篇文章,
高亮标题为 "Emerging AI trends" 的章节,
保存文章到阅读列表待稍后查看,
评论一段随机的段落摘要

#### 示例 4:活动预约

打开 Eventbrite,
搜索 "Austin, TX" 本周末的 AI 创业公司meetup 活动,
选择最热门的一个,
注册并确认参加,
设置日历提醒

资料来源:README.md:60-100

环境要求

前置条件

使用 Mobile MCP 前,需要准备以下环境:

平台要求
iOSmacOS + Xcode + WebDriverAgent
AndroidAndroid SDK + ADB
通用Node.js 环境用于运行 mobilecli

详细安装说明请参阅 官方 Wiki

资料来源:README.md:105-110

客户端集成

Mobile MCP 可与多种 MCP 兼容客户端集成:

客户端集成方式
Claude DesktopJSON 配置文件
Cursor手动配置或一键安装
VS CodeVS Code MCP 扩展
Claude CodeCLI 命令添加
CodexTOML 配置文件
CopilotMCP 配置
Gemini CLICLI 命令添加
Goose自定义扩展
WindsurfMCP 服务器设置
ClineMCP 设置文件
AmpVS Code 扩展或 CLI

详细配置请参考各客户端的 MCP 文档或 项目 Wiki

技术栈

层级技术/工具
协议层Model Context Protocol (MCP)
运行时Node.js
iOS 控制WebDriverAgent (WDA)
Android 控制mobilecli / ADB
iOS 连接go-ios 工具

路线图

项目团队持续优化 Mobile MCP,详细的路线图可在 GitHub Projects 中查看。

路线图涵盖的领域包括:

  • 新功能开发
  • 性能优化
  • 平台扩展
  • 文档完善
  • 社区反馈集成

相关资源

资源链接
项目首页https://github.com/mobile-next/mobile-mcp
官方文档https://github.com/mobile-next/mobile-mcp/wiki
问题反馈GitHub Issues
Slack 社区https://mobilenexthq.com/join-slack
路线图https://github.com/orgs/mobile-next/projects/3

资料来源:[README.md:50-60]()

安装与配置

Mobile MCP (Model Context Protocol) 是一个用于移动端自动化和控制的服务端工具,支持 iOS 和 Android 平台的原生应用自动化、模拟器/真机控制、以及脚本化流程交互。该工具通过 MCP 协议与 AI 助手集成,使 LLM 能够操控移动设备完成各类自动化任务。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 运行环境

继续阅读本节完整说明和来源证据。

章节 设备支持

继续阅读本节完整说明和来源证据。

章节 方式一:npx 直接运行

继续阅读本节完整说明和来源证据。

概述

Mobile MCP (Model Context Protocol) 是一个用于移动端自动化和控制的服务端工具,支持 iOS 和 Android 平台的原生应用自动化、模拟器/真机控制、以及脚本化流程交互。该工具通过 MCP 协议与 AI 助手集成,使 LLM 能够操控移动设备完成各类自动化任务。

资料来源:README.md

系统要求

运行环境

要求项规格
Node.js 版本>= 18
包管理器npm / npx
许可证Apache-2.0
发布格式npm 包 (@mobilenext/mobile-mcp)

资料来源:package.json:6-9

设备支持

系统支持以下类型的移动设备连接:

  • iOS 真机:通过 WebDriverAgent (WDA) 进行控制
  • iOS 模拟器:通过 simctl 命令控制
  • Android 真机:通过 Android Debug Bridge (ADB) 命令控制
  • Android 模拟器:通过 ADB 连接

设备发现和类型识别逻辑位于 src/server.ts 中的 getRobotFromDevice 函数:

const getRobotFromDevice = (deviceId: string): Robot => {
    // 检查 iOS 真机
    const iosManager = new IosManager();
    const iosDevice = iosManager.listDevices().find(d => d.deviceId === deviceId);
    if (iosDevice) return new IosRobot(deviceId);

    // 检查 Android 设备
    const androidManager = new AndroidDeviceManager();
    const androidDevice = androidManager.getConnectedDevices().find(d => d.deviceId === deviceId);
    if (androidDevice) return new AndroidRobot(deviceId);

    // 检查 iOS 模拟器
    const response = mobilecli.getDevices({ platform: "ios", type: "simulator", includeOffline: false });
    // ...
};

资料来源:src/server.ts:31-52

安装方式

方式一:npx 直接运行

最简安装方式,通过 npx 直接启动服务:

npx @mobilenext/mobile-mcp@latest

方式二:本地安装

npm install -g @mobilenext/mobile-mcp

方式三:项目依赖安装

npm install @mobilenext/mobile-mcp

MCP 客户端配置

标准配置模板

大多数 MCP 客户端支持以下标准配置格式:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

资料来源:README.md:1-10

各客户端配置详情

#### VS Code (Copilot)

{
  "mcpServers": {
    "mobile-mcp": {
      "type": "local",
      "command": "npx",
      "tools": ["*"],
      "args": ["@mobilenext/mobile-mcp@latest"]
    }
  }
}

#### Claude Desktop

配置文件路径:~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

#### Cursor

在 Cursor 设置中添加新的 MCP Server,使用命令类型:

命令: npx -y @mobilenext/mobile-mcp@latest

#### Cline

将标准配置添加到 MCP 设置文件中:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

#### Windsurf

在 MCP servers 设置中添加新服务器,使用命令类型:

npx @mobilenext/mobile-mcp@latest

#### Codeium (Windsurf)

配置路径:~/.codex/config.toml

[mcp_servers.mobile-mcp]
command = "npx"
args = ["@mobilenext/mobile-mcp@latest"]

#### Gemini CLI

gemini mcp add mobile-mcp npx -y @mobilenext/mobile-mcp@latest

#### Goose

设置类型:STDIO 命令:npx -y @mobilenext/mobile-mcp@latest

#### Kiro

配置文件路径:.kiro/settings/mcp.json

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["@mobilenext/mobile-mcp@latest"]
    }
  }
}

#### Amp (VS Code 扩展)

通过 Amp VS Code 扩展设置或 settings.json 添加:

"amp.mcpServers": {
  "mobile-mcp": {
    "command": "npx",
    "args": ["@mobilenext/mobile-mcp@latest"]
  }
}

或通过 CLI:

amp mcp add mobile-mcp -- npx @mobilenext/mobile-mcp@latest

SSE 服务器模式

默认情况下,Mobile MCP 通过 stdio 通信运行。如需以 HTTP 服务器模式运行,使用 --listen 参数:

npx @mobilenext/mobile-mcp@latest --listen 3000

这会将服务绑定到 localhost:3000

指定网络接口

npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000

MCP 客户端连接配置

配置客户端连接到 SSE 服务器:

http://<host>:3000/mcp

资料来源:README.md:1-20

授权配置

SSE 服务器支持 Bearer Token 授权。设置环境变量:

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

所有请求必须包含头部:

Authorization: Bearer my-secret-token

环境变量

变量名说明必填
MOBILEMCP_AUTHSSE 服务器的 Bearer Token 认证密钥仅 SSE 模式
PATH需包含 mobilecli 可执行文件路径

mobilecli 可用性检查

服务启动时会自动检查 mobilecli 是否可用:

const ensureMobilecliAvailable = (): void => {
    try {
        const version = mobilecli.getVersion();
        if (version.startsWith("failed")) {
            throw new Error("mobilecli version check failed");
        }
    } catch (error: any) {
        throw new ActionableError(`mobilecli is not available or not working properly...`);
    }
};

资料来源:src/server.ts:18-30

通信协议架构

graph TD
    A[MCP 客户端<br/>AI 助手] -->|MCP 协议| B[Mobile MCP Server<br/>mobile-mcp]
    B -->|stdio 或 SSE| A
    B --> C[mobilecli]
    C -->|iOS 控制| D[iOS 模拟器<br/>simctl]
    C -->|iOS 真机| E[WebDriverAgent<br/>WDA 隧道]
    C -->|Android| F[ADB]
    D --> G[iOS 模拟器]
    E --> H[iOS 真机]
    F --> I[Android 设备/模拟器]

可用工具列表

安装并配置完成后,以下工具将自动注册到 MCP 客户端:

设备管理

工具名称功能描述
mobile_list_available_devices列出所有可用设备(模拟器、仿真器、真机)
mobile_get_screen_size获取设备屏幕尺寸(像素)
mobile_get_orientation获取当前屏幕方向
mobile_set_orientation设置屏幕方向(竖屏/横屏)

应用管理

工具名称功能描述
mobile_list_apps列出设备上安装的所有应用
mobile_launch_app通过包名启动应用
mobile_terminate_app终止运行中的应用
mobile_install_app从文件安装应用(.apk, .ipa, .app, .zip)
mobile_uninstall_app卸载应用

屏幕交互

工具名称功能描述
mobile_take_screenshot截取屏幕截图
mobile_save_screenshot保存截图到文件
mobile_list_elements_on_screen列出屏幕上的 UI 元素及其坐标和属性
mobile_click_on_screen_at_coordinates点击指定坐标
mobile_double_tap_on_screen双击指定坐标
mobile_long_press_on_screen_at_coordinates长按指定坐标
mobile_swipe_on_screen在任意方向滑动

输入与导航

工具名称功能描述
mobile_type_keys向焦点元素输入文本
mobile_press_button按下设备按钮
mobile_open_url打开 URL

崩溃日志

工具名称功能描述
mobile_list_crashes列出设备上的崩溃报告
mobile_get_crash获取指定 ID 的崩溃报告内容

资料来源:README.md:100-130

依赖项

核心依赖

{
  "@modelcontextprotocol/sdk": "1.26.0",
  "ajv": "^8.18.0",
  "commander": "14.0.0",
  "express": "5.1.0",
  "fast-xml-parser": "5.5.7",
  "qs": "^6.15.0",
  "zod": "^4.1.13",
  "zod-to-json-schema": "3.25.0"
}

可选依赖

{
  "mobilecli": "0.3.70"
}

mobilecli 为可选依赖,用于与 iOS/Android 设备通信。

资料来源:package.json:23-45

构建与开发

项目构建

npm run build

构建产物输出到 lib 目录。

开发模式

npm run watch

代码检查

npm run lint

故障排除

mobilecli 不可用

错误信息:

mobilecli is not available or not working properly

解决方案:访问 官方 Wiki 查看 mobilecli 安装说明。

iOS 设备连接问题

iOS 真机需要以下服务正常运行:

  1. iOS 隧道:用于网络通信
  2. WDA 端口转发:WebDriverAgent 端口转发
  3. WebDriverAgent:设备上安装并运行

连接检查逻辑位于 src/ios.ts

private async assertTunnelRunning(): Promise<void> {
    if (await this.isTunnelRequired()) {
        if (!(await this.isTunnelRunning())) {
            throw new ActionableError("iOS tunnel is not running...");
        }
    }
}

private async wda(): Promise<WebDriverAgent> {
    await this.assertTunnelRunning();
    if (!(await this.isWdaForwardRunning())) {
        throw new ActionableError("Port forwarding to WebDriverAgent is not running...");
    }
    if (!(await wda.isRunning())) {
        throw new ActionableError("WebDriverAgent is not running on device...");
    }
    return wda;
}

资料来源:src/ios.ts:60-80

应用安装失败

安装 .zip 文件时会进行以下验证:

  1. 路径安全检查(防止 zip-slip 攻击)
  2. 自动解压到临时目录
  3. 查找 .app bundle 文件

如未找到 .app bundle,抛出错误:

No .app bundle found in the .zip file

资料来源:src/iphone-simulator.ts:80-100

更多资源

资料来源:[README.md](https://github.com/mobile-next/mobile-mcp/blob/main/README.md)

客户端配置指南

本指南详细说明如何在不同 IDE 和 AI 编程助手客户端中配置 Mobile MCP 服务器。Mobile MCP 是一个基于 Model Context Protocol (MCP) 的移动设备自动化框架,支持 iOS、Android、模拟器和真机等平台。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 配置参数说明

继续阅读本节完整说明和来源证据。

章节 Claude Desktop

继续阅读本节完整说明和来源证据。

章节 Claude Code

继续阅读本节完整说明和来源证据。

标准配置模板

无论使用何种客户端,大多数工具都使用相同的基础配置结构:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

配置参数说明

参数类型说明
commandstring执行命令,固定为 npx
argsarray命令参数,-y 表示自动确认,@mobilenext/mobile-mcp@latest 指定包名和版本
资料来源:README.md

Claude 系列客户端配置

Claude Desktop

在 Claude Desktop 中配置 Mobile MCP,需要编辑 MCP 安装配置文件。详细步骤请参考 MCP 快速入门指南,直接使用上述标准配置即可。

Claude Code

使用 Claude Code CLI 添加 Mobile MCP 服务器:

claude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latest

或者手动编辑配置文件 ~/.claude/settings.json,添加标准配置模板中的 JSON 内容。

资料来源:README.md

Cline

Cline 客户端配置最为简单,只需将标准配置 JSON 添加到 MCP 设置文件即可:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

更多详情请参考 Cline 配置文档

资料来源:README.md

AI IDE 客户端配置

Cursor

Cursor 提供两种安装方式:

#### 方式一:点击安装按钮

访问 Cursor 安装页面,点击安装按钮自动配置。

#### 方式二:手动安装

  1. 进入 Cursor SettingsMCPAdd new MCP Server
  2. 根据喜好命名服务器
  3. 使用 command 类型,命令设为 npx -y @mobilenext/mobile-mcp@latest
  4. 可通过点击 Edit 验证配置或添加命令行参数
资料来源:README.md

Codex

使用 Codex CLI 添加服务器:

codex mcp add mobile-mcp npx "@mobilenext/mobile-mcp@latest"

或者编辑配置文件 ~/.codex/config.toml

[mcp_servers.mobile-mcp]
command = "npx"
args = ["@mobilenext/mobile-mcp@latest"]

更多配置信息请参考 Codex MCP 文档。

资料来源:README.md

Copilot

使用 Copilot CLI 交互式添加服务器:

/mcp add

或者手动编辑 ~/.copilot/mcp-config.json

{
  "mcpServers": {
    "mobile-mcp": {
      "type": "local",
      "command": "npx",
      "tools": ["*"],
      "args": ["@mobilenext/mobile-mcp@latest"]
    }
  }
}
资料来源:README.md

其他开发工具配置

Gemini CLI

gemini mcp add mobile-mcp npx -y @mobilenext/mobile-mcp@latest

Goose

#### 点击安装

访问 Goose 安装页面,使用默认配置自动安装。

#### 手动安装

  1. 进入 Advanced settingsExtensionsAdd custom extension
  2. 自定义命名
  3. 选择类型为 STDIO
  4. 设置命令为 npx -y @mobilenext/mobile-mcp@latest
  5. 点击 "Add Extension"

Kiro

.kiro/settings/mcp.json 中添加配置:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["@mobilenext/mobile-mcp@latest"]
    }
  }
}

详细文档请参考 Kiro MCP 文档

opencode

~/.config/opencode/opencode.json 中配置:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "mobile-mcp": {
      "type": "local",
      "command": ["npx", "@mobilenext/mobile-mcp@latest"],
      "enabled": true
    }
  }
}

Qodo Gen

  1. 在 VSCode 或 IntelliJ 中打开 Qodo Gen 聊天面板
  2. 进入 Connect more tools+ Add new MCP
  3. 粘贴标准配置
  4. 点击 Save

Windsurf

  1. 打开 Windsurf 设置
  2. 导航至 MCP servers
  3. 添加新服务器,选择 command 类型
  4. 输入命令:npx @mobilenext/mobile-mcp@latest

或在设置中的 mcpServers 下添加标准配置。

Amp

#### VS Code 扩展方式

通过 Amp VS Code 扩展设置界面添加,或更新 settings.json

"amp.mcpServers": {
  "mobile-mcp": {
    "command": "npx",
    "args": ["@mobilenext/mobile-mcp@latest"]
  }
}

#### Amp CLI 方式

amp mcp add mobile-mcp -- npx @mobilenext/mobile-mcp@latest
资料来源:README.md

SSE 服务器模式配置

Mobile MCP 默认通过 stdio 通信。如需启动 SSE 服务器,使用 --listen 参数:

基础配置

npx @mobilenext/mobile-mcp@latest --listen 3000

这将绑定到 localhost:3000

绑定特定网络接口

npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000

配置 MCP 客户端连接到 http://<host>:3000/mcp

资料来源:README.md

Bearer Token 授权配置

为 SSE 服务器启用 Bearer Token 认证,需设置 MOBILEMCP_AUTH 环境变量:

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

启用后,所有请求必须包含认证头:

Authorization: Bearer my-secret-token
资料来源:README.md

设备连接架构

Mobile MCP 通过 mobilecli 工具与移动设备通信,支持多种设备类型:

graph TB
    subgraph "MCP 客户端"
        A[Claude Code] --> B[配置解析]
        C[Cursor] --> B
        D[Copilot] --> B
    end
    
    subgraph "Mobile MCP 服务器"
        B --> E[服务器初始化]
        E --> F{设备类型检测}
        F -->|iOS| G[IosRobot]
        F -->|Android| H[AndroidRobot]
        F -->|Simulator| I[SimulatorRobot]
    end
    
    subgraph "设备通信层"
        G --> J[ios libimobiledevice]
        H --> K[Android Debug Bridge]
        I --> J
    end
    
    subgraph "移动设备"
        J --> L[iOS 设备]
        K --> M[Android 设备]
    end

设备类型检测流程

  1. 获取设备标识符
  2. 检查是否为 iOS 真机(通过 IosManager.listDevices()
  3. 检查是否为 Android 设备(通过 AndroidDeviceManager.getConnectedDevices()
  4. 检查是否为模拟器(通过 mobilecli.getDevices()
资料来源:src/server.ts
资料来源:src/robot.ts

环境要求

Node.js 版本

要求 Node.js 版本 >= 18

"engines": {
  "node": ">=18"
}
资料来源:package.json

mobilecli 依赖

mobilecli 是可选依赖项,用于底层设备通信:

"optionalDependencies": {
  "mobilecli": "0.3.70"
}

服务器启动时会验证 mobilecli 是否可用:

const ensureMobilecliAvailable = (): void => {
  try {
    const version = mobilecli.getVersion();
    if (version.startsWith("failed")) {
      throw new Error("mobilecli version check failed");
    }
  } catch (error: any) {
    throw new ActionableError(`mobilecli is not available or not working properly.`);
  }
};
资料来源:src/server.ts

配置问题排查

常见配置错误

错误信息可能原因解决方案
mobilecli is not availablemobilecli 未安装或路径错误参考 Wiki 安装文档
iOS tunnel is not runningiOS 设备隧道未建立确保 WebDriverAgent 和端口转发正常运行
Port forwarding to WebDriverAgent is not runningWDA 端口未转发检查端口 8100 是否正常转发
WebDriverAgent is not running on deviceWDA 应用未启动重启设备上的 WDA 应用

调试步骤

  1. 验证 mobilecli:运行 npx mobilecli --version 确认安装
  2. 检查设备连接mobilecli list-devices 查看可用设备
  3. 查看服务端日志:启用详细日志以诊断问题
  4. 参考 Wiki 文档:访问 官方 Wiki 获取详细故障排除指南
资料来源:src/server.ts
资料来源:src/ios.ts

完整配置示例

开发环境完整配置

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"],
      "env": {
        "MOBILEMCP_AUTH": "dev-token"
      }
    }
  }
}

生产环境 SSE 模式配置

# 启动带认证的 SSE 服务器
MOBILEMCP_AUTH=secure-token npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000

对应的客户端配置:

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"],
      "url": "http://localhost:3000/mcp",
      "headers": {
        "Authorization": "Bearer secure-token"
      }
    }
  }
}

进阶配置

iOS 设备专用配置

iOS 设备需要额外的 WebDriverAgent (WDA) 配置。服务器会自动处理:

  1. 隧道连接验证
  2. WDA 端口转发检查(默认端口 8100)
  3. WebDriverAgent 运行状态检测
private async assertTunnelRunning(): Promise<void> {
  if (await this.isTunnelRequired()) {
    if (!(await this.isTunnelRunning())) {
      throw new ActionableError("iOS tunnel is not running");
    }
  }
}

private async wda(): Promise<WebDriverAgent> {
  await this.assertTunnelRunning();
  
  if (!(await this.isWdaForwardRunning())) {
    throw new ActionableError("Port forwarding to WebDriverAgent is not running");
  }
  
  const wda = new WebDriverAgent("localhost", WDA_PORT);
  
  if (!(await wda.isRunning())) {
    throw new ActionableError("WebDriverAgent is not running on device");
  }
  
  return wda;
}
资料来源:src/ios.ts

Android 设备专用配置

Android 设备通过 ADB 通信,支持以下功能:

  • 应用安装(.apk 文件)
  • 应用卸载(通过 bundle ID)
  • 应用启动(支持设置 locale)
  • Shell 命令执行
public async launchApp(packageName: string, locale?: string): Promise<void> {
  validatePackageName(packageName);
  
  if (locale) {
    validateLocale(locale);
    try {
      this.silentAdb("shell", "cmd", "locale", "set-app-locales", packageName, "--locales", locale);
    } catch (error) {
      // set-app-locales requires Android 13+ (API 33)
    }
  }
  
  try {
    this.silentAdb("shell", "monkey", "-p", packageName, "-c", "android.intent.category.LAUNCHER", "1");
  } catch (error) {
    throw new ActionableError(`Failed launching app with package name "${packageName}"`);
  }
}
资料来源:src/android.ts

相关资源

来源:https://github.com/mobile-next/mobile-mcp / 项目说明书

系统架构

Mobile MCP 是一个基于 Model Context Protocol (MCP) 的移动端自动化服务框架,旨在为 AI Agent 提供统一的移动设备交互能力。该项目支持 iOS 和 Android 平台,能够控制真机、模拟器和模拟器,核心设计理念是通过原生无障碍树(Accessibility Tree)实现 UI 元素识别和交互,无需依赖计算机视觉模型。 资料来...

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 MCP 服务层

继续阅读本节完整说明和来源证据。

章节 设备管理机制

继续阅读本节完整说明和来源证据。

章节 Robot 接口定义

继续阅读本节完整说明和来源证据。

概述

Mobile MCP 是一个基于 Model Context Protocol (MCP) 的移动端自动化服务框架,旨在为 AI Agent 提供统一的移动设备交互能力。该项目支持 iOS 和 Android 平台,能够控制真机、模拟器和模拟器,核心设计理念是通过原生无障碍树(Accessibility Tree)实现 UI 元素识别和交互,无需依赖计算机视觉模型。 资料来源:README.md

整体架构

Mobile MCP 采用分层架构设计,从上到下依次为:MCP 协议层、工具调度层、机器人抽象层和设备适配层。这种设计确保了上层与具体设备实现的解耦,使得框架能够灵活支持多种移动设备类型。

graph TD
    A[MCP Client<br/>Claude/Cursor等] --> B[MCP SDK<br/>协议通信]
    B --> C[Server<br/>工具注册与调度]
    C --> D[Robot Interface<br/>抽象接口层]
    D --> E1[iOS Robot<br/>WebDriverAgent]
    D --> E2[Android Robot<br/>mobilecli]
    D --> E3[Simulator Robot]
    E1 --> F1[iOS Device<br/>真机/模拟器]
    E2 --> F2[Android Device<br/>真机/模拟器]
    E3 --> F1

核心组件

MCP 服务层

src/server.ts 是整个系统的核心入口,负责 MCP 协议的初始化、工具定义和执行调度。

组件职责
tool()工具定义函数,使用 Zod 进行参数校验
getRobotFromDevice()根据设备 ID 返回对应的 Robot 实例
ensureMobilecliAvailable()验证 mobilecli 依赖是否可用

服务层初始化时首先调用 ensureMobilecliAvailable() 验证 mobilecli 可用性,通过 posthog("launch", {}) 记录启动事件。随后通过 getRobotFromDevice() 方法实现设备类型的自动识别。 资料来源:src/server.ts:1-50

设备管理机制

#### 设备识别流程

graph TD
    A[设备ID] --> B{检查iOS设备列表}
    B -->|匹配| C[返回IosRobot]
    B -->|不匹配| D{检查Android设备列表}
    D -->|匹配| E[返回AndroidRobot]
    D -->|不匹配| F{检查iOS模拟器}
    F -->|匹配| G[返回IosRobot]
    F -->|不匹配| H[抛出异常]

设备识别按照 iOS 真机 → Android 真机 → iOS 模拟器的优先级顺序进行检测。每个设备类型都有对应的 Manager 类负责设备列表管理:

  • IosManager: 通过 iosManager.listDevices() 获取 iOS 设备列表
  • AndroidDeviceManager: 通过 androidManager.getConnectedDevices() 获取 Android 设备列表
  • mobilecli: 通过 mobilecli.getDevices() 获取模拟器列表

资料来源:src/server.ts:20-45

#### 设备列表工具

系统提供 mobile_list_available_devices 工具用于列举所有可用设备,返回设备 ID、平台类型、设备名称和连接状态信息。

机器人抽象层

Robot 接口定义

src/robot.ts 定义了 Robot 抽象接口,规定了所有设备类型必须实现的核心方法:

方法功能描述参数
getScreenSize()获取屏幕尺寸
getOrientation()获取屏幕方向
setOrientation()设置屏幕方向orientation
swipe()滑动操作direction, distance
swipeFromCoordinate()从坐标滑动x, y, direction, distance
tap()点击操作x, y
doubleTap()双击操作x, y
longPress()长按操作x, y, duration
getScreenshot()获取截图
getElementsOnScreen()获取屏幕元素
listApps()列出已安装应用
launchApp()启动应用packageName, locale
terminateApp()终止应用packageName
installApp()安装应用path
uninstallApp()卸载应用bundleId
openUrl()打开 URLurl
sendKeys()发送按键text
pressButton()按压按钮button

资料来源:src/robot.ts:1-100

屏幕元素数据模型

interface ScreenElement {
    type: string;       // 元素类型:TextField, Button, Switch 等
    label: string;      // 无障碍标签
    name: string;       // 元素名称
    value: string;      // 元素值
    identifier: string; // 元素标识符
    rect: {
        x: number;      // 左上角 X 坐标
        y: number;      // 左上角 Y 坐标
        width: number;  // 元素宽度
        height: number; // 元素高度
    };
}

iOS 实现

架构特点

iOS 设备控制采用 WebDriverAgent (WDA) 作为底层交互协议,通过 go-ios 工具建立设备隧道和端口转发。

graph LR
    A[MCP Server] -->|localhost:PORT| B[Port Forwarding]
    B --> C[WebDriverAgent]
    C --> D[iOS Device]
    
    E[go-ios tunnel] -->|WDA_PORT| B
    E -->|IOS_TUNNEL_PORT| F[iOS Device Network]

关键组件

src/ios.ts 包含以下核心功能:

组件功能
isTunnelRunning()检查 iOS 隧道是否运行
isWdaForwardRunning()检查 WDA 端口转发是否建立
assertTunnelRunning()确保隧道可用
wda()获取 WebDriverAgent 实例

iOS 实现层包含严格的状态检查机制,在执行任何设备操作前必须确保隧道和端口转发正常运行。 资料来源:src/ios.ts:1-80

WebDriverAgent 交互

src/webdriver-agent.ts 实现了 WebDriverAgent 协议,支持以下操作:

操作端点方法
按压按钮/wda/pressButtonPOST
指针动作/actionsPOST
获取页面源码/source/?format=jsonGET
打开 URL/urlPOST

元素识别通过 Accessibility Tree 实现,系统只返回特定类型的元素:TextField、Button、Switch、Icon、SearchField、StaticText、Image,并对元素可见性进行过滤。 资料来源:src/webdriver-agent.ts:1-120

Android 实现

mobilecli 集成

Android 设备通过 mobilecli 命令行工具实现控制。src/mobile-device.ts 封装了所有 Android 特有的交互逻辑。

命令功能
io tap x,y点击坐标
io longpress x,y --duration ms长按操作
io text "text"输入文本
io button BACK/HOME按压虚拟按键
dump ui获取 UI 层次结构
device orientation set/get屏幕方向控制

资料来源:src/mobile-device.ts:1-60

UI 层级获取

Android 设备通过 dump ui 命令获取屏幕元素,响应结构为 DumpUIResponse,包含 data.elements 数组,每个元素包含 type、label、text、name、value、identifier、rect 和 focused 属性。

通信协议

STDIO 模式

默认配置下,Mobile MCP 通过标准输入输出(STDIO)与 MCP Client 通信,适用于本地集成场景。启动命令:

npx -y @mobilenext/mobile-mcp@latest

SSE 服务器模式

当需要远程连接时,可启用 SSE(Server-Sent Events)服务器模式:

npx @mobilenext/mobile-mcp@latest --listen 3000

可通过环境变量配置认证令牌:

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

SSE 模式下,所有请求需要携带 Authorization: Bearer <token> 头部。 资料来源:README.md

工具系统

工具注册机制

所有工具通过 tool() 函数注册到 MCP 服务器,每个工具包含:

属性说明
name工具名称,如 mobile_tap_on_screen
description工具功能描述
inputSchemaZod schema 定义参数
annotations工具标注,如 destructiveHint
handler异步处理函数

核心工具列表

工具名功能破坏性提示
mobile_list_available_devices列出可用设备
mobile_get_screen_size获取屏幕尺寸
mobile_get_orientation获取屏幕方向
mobile_set_orientation设置屏幕方向
mobile_list_apps列出已安装应用
mobile_launch_app启动应用
mobile_terminate_app终止应用
mobile_install_app安装应用
mobile_uninstall_app卸载应用
mobile_take_screenshot截图
mobile_list_elements_on_screen获取屏幕元素
mobile_click_on_screen_at_coordinates点击坐标
mobile_double_tap_on_screen双击坐标
mobile_long_press_on_screen_at_coordinates长按坐标
mobile_swipe_on_screen滑动屏幕
mobile_type_keys输入文本
mobile_press_button按压按钮
mobile_open_url打开 URL

资料来源:src/server.ts

依赖管理

核心依赖

依赖版本用途
@modelcontextprotocol/sdk1.26.0MCP 协议实现
zod^4.1.13参数校验
express5.1.0SSE 服务器
commander14.0.0CLI 参数解析
fast-xml-parser5.5.7XML 解析
qs^6.15.0查询字符串处理
ajv^8.18.0JSON Schema 验证

可选依赖

依赖版本用途
mobilecli0.3.70Android 设备控制

资料来源:package.json

安全机制

URL 安全限制

系统默认只允许 http:// 和 https:// 协议 URL,unsafe URL schemes 需要显式设置环境变量:

MOBILEMCP_ALLOW_UNSAFE_URLS=1

此检查在 mobile_open_url 工具中实现。 资料来源:src/server.ts

启动流程

sequenceDiagram
    participant MCP as MCP Client
    participant Server as Server
    participant Mobilecli as mobilecli
    participant Device as Device Manager
    
    MCP->>Server: 连接请求
    Server->>Mobilecli: 检查版本
    alt mobilecli 不可用
        Server-->>MCP: 抛出错误
    end
    Server->>Device: 获取设备列表
    Device-->>Server: 设备信息
    Server->>MCP: 注册工具
    MCP->>Server: 工具调用请求
    Server->>Device: 获取 Robot 实例
    Device-->>Server: Robot 对象
    Server->>Robot: 执行操作
    Robot-->>Server: 操作结果
    Server-->>MCP: 返回结果

扩展性设计

系统通过 Robot 接口抽象层支持多种设备类型的扩展,新增设备类型只需:

  1. 实现 Robot 接口的所有方法
  2. getRobotFromDevice() 中添加设备识别逻辑
  3. 注册对应的 Manager 类

这种设计模式使得框架具有良好的可扩展性,能够适应新平台或新设备类型的集成需求。

资料来源:[src/server.ts:20-45](https://github.com/mobile-next/mobile-mcp/blob/main/src/server.ts)

设备管理

设备管理是 Mobile MCP 的核心子系统,负责统一管理 iOS、Android 模拟器、 Android 模拟器以及物理真机等各类移动设备。该模块通过抽象层将不同平台的设备操作统一为一致的接口,使上层工具能够以平台无关的方式与设备进行交互。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 整体架构

继续阅读本节完整说明和来源证据。

章节 核心组件

继续阅读本节完整说明和来源证据。

章节 设备列表获取

继续阅读本节完整说明和来源证据。

概述

设备管理是 Mobile MCP 的核心子系统,负责统一管理 iOS、Android 模拟器、 Android 模拟器以及物理真机等各类移动设备。该模块通过抽象层将不同平台的设备操作统一为一致的接口,使上层工具能够以平台无关的方式与设备进行交互。

设备管理的核心职责包括:

  • 设备发现与枚举
  • 设备类型自动识别
  • 设备连接状态管理
  • 设备 Robot 实例化
  • Agent 状态维护与自动安装

资料来源:src/server.ts:16-18

架构设计

整体架构

Mobile MCP 采用分层架构设计,设备管理层位于服务层与平台实现层之间:

graph TD
    A[MCP 客户端] --> B[Server.ts 工具层]
    B --> C[设备管理模块]
    C --> D[Robot 抽象接口]
    D --> E[iOS Robot 实现]
    D --> F[Android Robot 实现]
    D --> G[MobileDevice Robot 实现]
    C --> H[mobilecli 工具层]
    H --> I[iOS 平台层]
    H --> J[Android 平台层]

核心组件

组件文件位置职责
getRobotFromDevice()src/server.ts设备类型检测与 Robot 实例化工厂
Robotsrc/robot.ts设备操作抽象接口定义
IosRobotsrc/ios.tsiOS 设备操作实现
AndroidRobotsrc/android.tsAndroid 设备操作实现
MobileDevicesrc/mobile-device.ts模拟器设备操作实现
IosManagersrc/ios.tsiOS 设备枚举与管理
AndroidDeviceManagersrc/android.tsAndroid 设备枚举与管理

资料来源:src/server.ts:16-66

设备发现流程

设备列表获取

当调用 mobile_list_available_devices 工具时,系统按以下顺序扫描各平台设备:

graph TD
    A[开始] --> B[初始化 IosManager]
    B --> C[初始化 AndroidDeviceManager]
    C --> D[获取 Android 设备列表]
    D --> E[遍历 Android 设备详情]
    E --> F[获取 iOS 设备列表]
    F --> G[遍历 iOS 设备详情]
    G --> H[通过 mobilecli 获取模拟器]
    H --> I[合并去重]
    I --> J[返回设备列表]

设备发现函数实现:

async ({}) => {
    ensureMobilecliAvailable();
    const iosManager = new IosManager();
    const androidManager = new AndroidDeviceManager();
    const devices: MobilecliDevice[] = [];
    // 获取 Android 设备
    const androidDevices = androidManager.getConnectedDevices();
    // ... 合并各平台设备
}

资料来源:src/server.ts:100-130

设备类型识别

getRobotFromDevice() 函数负责将设备 ID 映射到对应的 Robot 实现:

graph TD
    A[传入 deviceId] --> B{检查是否为 iOS 真机}
    B -->|是| C[返回 IosRobot]
    B -->|否| D{检查是否为 Android 真机}
    D -->|是| E[返回 AndroidRobot]
    D -->|否| F{检查是否为 iOS 模拟器}
    F -->|是| G[检查 agentVerifiedSimulators]
    G -->|未验证| H[调用 agentStatus]
    H -->|失败| I[调用 agentInstall]
    I --> J[添加到已验证集合]
    J --> K[返回 MobileDevice]
    F -->|是| L[返回 MobileDevice]

核心实现逻辑:

const getRobotFromDevice = (deviceId: string): Robot => {
    ensureMobilecliAvailable();
    
    // 检查 iOS 真机
    const iosManager = new IosManager();
    const iosDevices = iosManager.listDevices();
    const iosDevice = iosDevices.find(d => d.deviceId === deviceId);
    if (iosDevice) {
        return new IosRobot(deviceId);
    }
    
    // 检查 Android 真机
    const androidManager = new AndroidDeviceManager();
    const androidDevices = androidManager.getConnectedDevices();
    const androidDevice = androidDevices.find(d => d.deviceId === deviceId);
    if (androidDevice) {
        return new AndroidRobot(deviceId);
    }
    
    // 检查 iOS 模拟器
    const response = mobilecli.getDevices({
        platform: "ios",
        type: "simulator",
        includeOffline: false,
    });
    // ... 模拟器处理逻辑
}

资料来源:src/server.ts:16-66

Robot 抽象接口

Robot 接口定义了所有设备类型的通用操作方法:

方法功能描述参数
tap(x, y)点击屏幕指定坐标x: number, y: number
doubleTap(x, y)双击屏幕指定坐标x: number, y: number
longPress(x, y, duration)长按屏幕指定坐标x, y, duration(ms)
swipeFromCoordinate(x, y, direction, distance?)从坐标处滑动方向、距离
getScreenshot()获取屏幕截图
getElementsOnScreen()获取屏幕元素列表
listApps()列出已安装应用
launchApp(packageName, locale?)启动应用包名、区域
terminateApp(packageName)终止应用包名
installApp(path)安装应用文件路径
uninstallApp(bundleId)卸载应用标识符
openUrl(url)打开 URL网址
sendKeys(text)发送文本输入文本内容
pressButton(button)按下物理按钮按钮类型
setOrientation(orientation)设置屏幕方向portrait/landscape
getOrientation()获取屏幕方向

资料来源:src/robot.ts:1-80

平台实现

iOS 设备管理

iOS 平台使用 IosManager 类进行设备管理,通过 WebDriverAgent 或 iOS Device Kit 实现与设备的通信:

  • 支持物理真机连接
  • 支持 iOS 模拟器
  • 自动检测 WebDriverAgent 安装状态
  • 支持应用启动时指定区域设置
export class IosManager {
    listDevices(): IosDevice[] {
        // 列出所有 iOS 设备
    }
}

export class IosRobot implements Robot {
    constructor(deviceId: string) {
        // 初始化 iOS Robot 实例
    }
}

资料来源:src/ios.ts:1-50

Android 设备管理

Android 平台使用 AndroidDeviceManager 类进行设备管理,通过 ADB 和 UI Automator 实现与设备的通信:

  • 支持物理真机连接
  • 支持 Android 模拟器
  • 支持折叠屏等多屏幕设备
  • 支持应用启动时指定区域设置
export class AndroidDeviceManager {
    getConnectedDevices(): AndroidDevice[] {
        // 获取已连接的 Android 设备
    }
}

export class AndroidRobot implements Robot {
    constructor(deviceId: string) {
        // 初始化 Android Robot 实例
    }
}

资料来源:src/android.ts:1-50

mobilecli 集成

mobilecli 依赖

mobilecli 是 Mobile MCP 的核心底层工具,提供跨平台的设备管理能力:

属性
包名mobilecli
版本0.3.70
类型可选依赖 (optionalDependencies)
Node 版本要求>=18

资料来源:package.json:28-29

依赖检查

在执行任何设备操作前,系统会通过 ensureMobilecliAvailable() 函数验证 mobilecli 是否可用:

const ensureMobilecliAvailable = (): void => {
    try {
        const version = mobilecli.getVersion();
        if (version.startsWith("failed")) {
            throw new Error("mobilecli version check failed");
        }
    } catch (error: any) {
        throw new ActionableError(
            `mobilecli is not available or not working properly. ` +
            `Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki`
        );
    }
};

资料来源:src/server.ts:9-17

mobilecli API

API 方法功能返回类型
mobilecli.getVersion()获取 mobilecli 版本string
mobilecli.getDevices(options)获取设备列表DeviceResponse
mobilecli.agentStatus(deviceId)检查设备 Agent 状态AgentStatus
mobilecli.agentInstall(deviceId)在设备上安装 Agentvoid
interface DeviceResponse {
    status: "ok" | "fail";
    data?: {
        devices: MobilecliDevice[];
    };
}

interface MobilecliDevice {
    id: string;
    name: string;
    platform: string;
    type: string;
}

资料来源:src/mobilecli.ts:1-30

模拟器特殊处理

Agent 验证机制

对于 iOS 模拟器,系统维护一个 agentVerifiedSimulators 集合来追踪已验证的模拟器:

const agentVerifiedSimulators = new Set<string>();

首次使用模拟器时,系统自动执行 Agent 状态检查:

graph TD
    A[模拟器 deviceId] --> B{agentVerifiedSimulators.has}
    B -->|未验证| C[调用 agentStatus]
    C -->|状态失败| D[调用 agentInstall]
    D --> E[添加到已验证集合]
    B -->|已验证| F[跳过验证]
    E --> G[返回 MobileDevice]
    F --> G

资料来源:src/server.ts:50-60

模拟器设备类型

通过 mobilecli 获取的模拟器使用 MobileDevice 类进行管理,该类提供统一的设备操作接口。

资料来源:src/mobile-device.ts:1-30

错误处理

ActionableError

系统定义 ActionableError 类用于提供可操作的错误信息:

class ActionableError extends Error {
    constructor(message: string) {
        super(message);
    }
}

常见错误场景

错误场景错误消息解决方案
mobilecli 不可用"mobilecli is not available or not working properly"检查安装并参考 Wiki 文档
设备未找到"Device \"{deviceId}\" not found"使用 mobile_list_available_devices 查看可用设备
Agent 安装失败"agentInstall failed"手动检查 WebDriverAgent/iOS Device Kit 安装状态

资料来源:src/server.ts:9-17, 64-66

使用示例

列出可用设备

# 使用 Claude Code
claude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latest

# 调用 mobile_list_available_devices 工具

选择设备并执行操作

// 1. 获取设备列表
const devices = await server.tools.mobile_list_available_devices();

// 2. 根据设备 ID 创建 Robot 实例
const robot = getRobotFromDevice(deviceId);

// 3. 执行设备操作
await robot.tap(100, 200);
await robot.getScreenshot();
await robot.launchApp("com.example.app");

相关工具

设备管理模块提供以下 MCP 工具:

工具名称功能只读
mobile_list_available_devices列出所有可用设备
mobile_get_screen_size获取屏幕尺寸
mobile_get_orientation获取屏幕方向
mobile_set_orientation设置屏幕方向
mobile_list_apps列出已安装应用
mobile_launch_app启动应用
mobile_terminate_app终止应用
mobile_install_app安装应用
mobile_uninstall_app卸载应用

资料来源:src/server.ts:100-200

总结

设备管理模块是 Mobile MCP 连接 MCP 协议与实际移动设备的桥梁。通过统一的 Robot 抽象接口,系统支持 iOS 物理设备、iOS 模拟器、Android 物理设备和 Android 模拟器四种设备类型。该模块利用 mobilecli 工具进行跨平台设备发现和通信,并针对不同平台特性(如 iOS 的 Agent 验证机制)进行了专门优化。

资料来源:[src/server.ts:16-18]()

MCP 工具详解

Mobile MCP 是一个基于 Model Context Protocol (MCP) 的移动设备自动化框架,通过标准化的工具接口实现对 iOS、Android、模拟器和真机的远程控制。本文详细介绍该项目中所有可用的 MCP 工具,包括其功能、参数定义和底层实现机制。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 工具注册机制

继续阅读本节完整说明和来源证据。

章节 列出可用设备

继续阅读本节完整说明和来源证据。

章节 获取设备类型

继续阅读本节完整说明和来源证据。

工具系统架构

Mobile MCP 的工具系统采用注册式架构,所有工具通过统一的 tool() 函数注册到 MCP 服务器。每个工具包含名称、标题、描述、参数模式和回调函数四个核心组件。

graph TD
    A[MCP Client] -->|tool request| B[McpServer]
    B --> C[tool registry]
    C --> D[回调函数执行]
    D --> E[device manager]
    E --> F[iOS Robot]
    E --> G[Android Robot]
    F --> H[WebDriverAgent/iOS]
    G --> I[ADB/Android]
    D --> J[返回结果]

工具注册机制

工具注册函数定义于 src/server.ts,其签名如下:

const tool = (
    name: string,           // 工具唯一标识符
    title: string,          // 人类可读标题
    description: string,    // 功能描述
    paramsSchema: ZodSchemaShape,  // 参数模式
    annotations: ToolAnnotations, // 注解信息
    cb: (args: any) => Promise<string>  // 回调函数
) => { ... }

ToolAnnotations 接口定义了工具的语义注解:

注解字段类型说明
readOnlyHintboolean指示工具是否只读操作
destructiveHintboolean指示工具是否可能造成数据损坏

资料来源:src/server.ts:52-57

设备管理工具

列出可用设备

工具名称: mobile_list_available_devices

功能描述: 返回所有可用的移动设备列表,包括 iOS 模拟器、iOS 真机、Android 模拟器、Android 真机以及离线设备(可选)。

参数定义:

参数名类型必填说明
includeOfflineboolean是否包含离线设备

返回值: JSON 格式的设备列表,包含每个设备的标识符、平台类型、设备类型和可用状态。

资料来源:src/server.ts:103-112

获取设备类型

工具名称: mobile_get_device_type

功能描述: 获取指定设备的类型信息。

参数定义:

参数名类型必填说明
devicestring设备标识符

实现逻辑: 通过遍历 iOS 设备列表、Android 设备列表和模拟器列表来确定设备类型。

graph TD
    A[输入 deviceId] --> B{查找 iOS 设备}
    B -->|找到| C[返回 ios]
    B -->|未找到| D{查找 Android 设备}
    D -->|找到| E[返回 android]
    D -->|未找到| F{查找模拟器}
    F -->|找到| G[返回 simulator]
    F -->|未找到| H[抛出异常]

资料来源:src/server.ts:85-102

屏幕与显示工具

获取屏幕尺寸

工具名称: mobile_get_screen_size

功能描述: 获取移动设备的屏幕尺寸(像素单位)。

参数定义:

参数名类型必填说明
devicestring设备标识符

返回值: 包含 widthheight 的屏幕尺寸对象。

资料来源:README.md

获取屏幕方向

工具名称: mobile_get_orientation

功能描述: 获取当前设备的屏幕方向。

返回值: "portrait""landscape"

资料来源:src/robot.ts:67-70

设置屏幕方向

工具名称: mobile_set_orientation

功能描述: 更改设备的屏幕方向。

参数定义:

参数名类型必填说明
devicestring设备标识符
orientationstring目标方向:portraitlandscape

接口定义(Robot 抽象类):

setOrientation(orientation: Orientation): Promise<void>;

资料来源:src/robot.ts:60-65

应用管理工具

列出已安装应用

工具名称: mobile_list_apps

功能描述: 列出目标设备上所有已安装的应用程序。

参数定义:

参数名类型必填说明
devicestring设备标识符

返回值: 包含应用名称、包名/Bundle ID 等信息的 JSON 数组。

资料来源:README.md

启动应用

工具名称: mobile_launch_app

功能描述: 通过包名称(Android)或 Bundle ID(iOS)启动指定应用。

参数定义:

参数名类型必填说明
devicestring设备标识符
appIdstring应用标识符
localestring启动时使用的语言环境(仅 iOS)

资料来源:src/server.ts, CHANGELOG.md

终止应用

工具名称: mobile_terminate_app

功能描述: 强制停止并终止正在运行的应用。

参数定义:

参数名类型必填说明
devicestring设备标识符
appIdstring要终止的应用标识符

Android 实现: 使用 adb shell am force-stop <packageName> 命令。

资料来源:src/android.ts:126-128

安装应用

工具名称: mobile_install_app

功能描述: 从本地文件安装应用。

支持格式: .apk(Android)、.ipa(iOS)、.app.zip

参数定义:

参数名类型必填说明
devicestring设备标识符
appPathstring应用文件路径

卸载应用

工具名称: mobile_uninstall_app

功能描述: 卸载指定应用。

参数定义:

参数名类型必填说明
devicestring设备标识符
appIdstring应用标识符

屏幕交互工具

截图

工具名称: mobile_take_screenshot

功能描述: 拍摄当前屏幕截图,用于了解屏幕内容。

参数定义:

参数名类型必填说明
devicestring设备标识符

保存截图

工具名称: mobile_save_screenshot

功能描述: 将截图保存到指定文件路径。

参数定义:

参数名类型必填说明
devicestring设备标识符
outputPathstring输出文件路径

安全修复: 0.0.49 版本修复了路径遍历漏洞,防止通过 ../ 访问目录外文件。

资料来源:CHANGELOG.md

点击坐标

工具名称: mobile_click_on_screen_at_coordinates

功能描述: 在指定屏幕坐标处执行点击操作。

参数定义:

参数名类型必填说明
devicestring设备标识符
xnumberX 坐标
ynumberY 坐标

双击

工具名称: mobile_double_tap_on_screen

功能描述: 在指定坐标执行双击操作。

参数定义:

参数名类型必填说明
devicestring设备标识符
xnumberX 坐标
ynumberY 坐标

长按

工具名称: mobile_long_press_on_screen_at_coordinates

功能描述: 在指定坐标执行长按操作。

参数定义:

参数名类型必填说明
devicestring设备标识符
xnumberX 坐标
ynumberY 坐标
durationnumber长按持续时间(毫秒)

接口定义(Robot 抽象类):

longPress(x: number, y: number, duration: number): Promise<void>;

资料来源:src/robot.ts:41-49

滑动

工具名称: mobile_swipe_on_screen

功能描述: 在屏幕上执行滑动操作,支持任意方向。

参数定义:

参数名类型必填说明
devicestring设备标识符
directionstring滑动方向:updownleftright

输入工具

输入文本

工具名称: mobile_type_keys

功能描述: 向当前焦点元素输入文本,支持可选的提交操作。

参数定义:

参数名类型必填说明
devicestring设备标识符
textstring要输入的文本
submitboolean是否在输入后提交

接口定义(Robot 抽象类):

sendKeys(text: string): Promise<void>;

资料来源:src/robot.ts:29-33

按键

工具名称: mobile_press_button

功能描述: 模拟物理按键按压。

参数定义:

参数名类型必填说明
devicestring设备标识符
buttonstring按键名称(如 ENTERHOMEBACK

接口定义(Robot 抽象类):

pressButton(button: Button): Promise<void>;

iOS 实现(WebDriverAgent):

await this.withinSession(async sessionUrl => {
    const url = `${sessionUrl}/wda/pressButton`;
    const response = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: button }),
    });
    return response.json();
});

资料来源:src/webdriver-agent.ts, src/robot.ts:35-38

元素检测工具

列出屏幕元素

工具名称: mobile_list_elements_on_screen

功能描述: 列出屏幕上所有 UI 元素及其坐标和属性信息。

参数定义:

参数名类型必填说明
devicestring设备标识符

返回值: 包含元素类型、标签、名称、值、标识符和矩形区域的数组。

ScreenElement 数据结构:

字段类型说明
typestring元素类型(如 TextFieldButtonSwitch
labelstring元素标签
namestring元素名称
valuestring元素值
identifierstring元素标识符(resource-id 或 rawIdentifier)
rectobject元素矩形区域 {x, y, width, height}

Android 元素收集逻辑:

graph TD
    A[获取 UI Automator XML] --> B[遍历 XML 节点]
    B --> C{节点是否包含可交互属性?}
    C -->|text/content-desc/hint/resource-id| D[创建 ScreenElement]
    C -->|无| E[跳过]
    D --> F{rect width > 0 && height > 0?}
    F -->|是| G[添加到元素列表]
    F -->|否| E
    G --> H{是否有子节点?}
    H -->|是| B
    H -->|否| I[返回元素列表]

iOS 元素过滤逻辑:

const acceptedTypes = ["TextField", "Button", "Switch", "Icon", "SearchField", "StaticText", "Image"];

if (acceptedTypes.includes(source.type)) {
    if (source.isVisible === "1" && this.isVisible(source.rect)) {
        if (source.label !== null || source.name !== null || source.rawIdentifier !== null) {
            output.push({ ... });
        }
    }
}

资料来源:src/android.ts, src/webdriver-agent.ts:1-35

崩溃日志工具

列出崩溃报告

工具名称: mobile_list_crashes

功能描述: 列出设备上可用的崩溃报告。

参数定义:

参数名类型必填说明
devicestring设备标识符

返回值: 崩溃报告 ID 列表。

实现:

async ({ device }) => {
    ensureMobilecliAvailable();
    const response = mobilecli.crashesList(device);
    return JSON.stringify(response.data);
}

资料来源:src/server.ts:201-211

获取崩溃详情

工具名称: mobile_get_crash

功能描述: 根据崩溃 ID 获取完整崩溃报告内容。

参数定义:

参数名类型必填说明
devicestring设备标识符
crashIdstring崩溃报告 ID

录制工具

开始录制

工具名称: mobile_start_recording

功能描述: 开始录制屏幕操作视频。

参数定义:

参数名类型必填说明
devicestring设备标识符
outputPathstring输出文件路径

实现细节:

  • 使用子进程启动录制命令
  • 设置 5 分钟超时保护
  • 返回 ActiveRecording 对象包含进程和开始时间

停止录制

工具名称: mobile_stop_recording

功能描述: 停止正在进行的屏幕录制。

返回值: 包含文件路径、大小(MB)和持续时间的信息字符串。

超时机制:

const timeout = setTimeout(() => {
    child.kill("SIGKILL");
    resolve();
}, 5 * 60 * 1000);

资料来源:src/server.ts:145-200

URL 导航工具

打开 URL

工具名称: mobile_open_url

功能描述: 在设备浏览器或应用内打开指定 URL。

参数定义:

参数名类型必填说明
devicestring设备标识符
urlstring目标 URL(支持 http://, https:// 或自定义 scheme)

接口定义(Robot 抽象类):

openUrl(url: string): Promise<void>;

iOS 实现(WebDriverAgent):

public async openUrl(url: string): Promise<void> {
    await this.withinSession(async sessionUrl => {
        await fetch(`${sessionUrl}/url`, {
            method: "POST",
            body: JSON.stringify({ url }),
        });
    });
}

资料来源:src/webdriver-agent.ts, src/robot.ts:25-28

工具分类总览

分类工具数量核心功能
设备管理2列表查询、类型获取
屏幕显示3尺寸、方向管理
应用管理4安装、卸载、启动、终止
屏幕交互5点击、双击、长按、滑动、截图
输入2文本输入、按键
元素检测1UI 元素枚举
崩溃日志2列表查询、详情获取
录制2开始/停止屏幕录制
导航1URL 打开

技术依赖

Mobile MCP 工具系统的核心依赖:

依赖包版本用途
@modelcontextprotocol/sdk1.26.0MCP 协议实现
zod^4.1.13参数验证
zod-to-json-schema3.25.0Zod 转 JSON Schema
mobilecli0.3.70移动设备 CLI 接口

资料来源:package.json:23-34

总结

Mobile MCP 通过统一的工具注册机制,封装了针对 iOS 和 Android 平台的大量自动化操作。所有工具遵循相同的接口规范,通过设备管理器自动路由到对应的平台实现(IosRobotAndroidRobot)。这种设计使得 AI Agent 能够通过简单的工具调用完成复杂的移动端自动化任务,包括应用管理、UI 交互、数据采集和端到端工作流执行。

资料来源:[src/server.ts:52-57]()

iOS 实现

Mobile MCP 的 iOS 实现模块负责与 iOS 设备(真机和模拟器)进行交互。该模块通过统一的抽象接口 Robot 提供跨平台自动化能力,同时针对 iOS 平台特性实现了特定的设备管理、元素获取和交互操作。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 整体架构

继续阅读本节完整说明和来源证据。

章节 设备类型识别

继续阅读本节完整说明和来源证据。

章节 Robot 接口定义

继续阅读本节完整说明和来源证据。

概述

Mobile MCP 的 iOS 实现模块负责与 iOS 设备(真机和模拟器)进行交互。该模块通过统一的抽象接口 Robot 提供跨平台自动化能力,同时针对 iOS 平台特性实现了特定的设备管理、元素获取和交互操作。

iOS 实现的核心目标包括:

  • 支持 iOS 模拟器(iPhone Simulator)和真机设备
  • 通过原生无障碍树(Accessibility Tree)获取 UI 元素信息
  • 提供截图、点击、滑动、文本输入等基础交互能力
  • 自动管理 WebDriverAgent 或 iOS Device Kit 生命周期

资料来源:src/robot.ts:1-50

架构设计

整体架构

Mobile MCP 采用分层架构设计,iOS 实现位于设备交互层:

graph TD
    A[MCP Server] --> B[Server Layer]
    B --> C[Tool Handlers]
    C --> D[Robot Interface]
    D --> E[iOS Robot]
    D --> F[Android Robot]
    E --> G[IosManager]
    E --> H[Mobilecli]
    G --> I[WebDriverAgent]
    G --> J[iOS Device Kit]
    H --> K[iPhone Simulator]

设备类型识别

服务器启动时通过 getRobotFromDevice 函数识别设备类型并返回对应的 Robot 实例:

const getRobotFromDevice = (deviceId: string): Robot => {
    ensureMobilecliAvailable();
    
    // 检查是否为 iOS 真机
    const iosManager = new IosManager();
    const iosDevices = iosManager.listDevices();
    const iosDevice = iosDevices.find(d => d.deviceId === deviceId);
    if (iosDevice) {
        return new IosRobot(deviceId);
    }
    
    // 检查是否为 Android 设备
    const androidManager = new AndroidDeviceManager();
    const androidDevices = androidManager.getConnectedDevices();
    const androidDevice = androidDevices.find(d => d.deviceId === deviceId);
    if (androidDevice) {
        return new AndroidRobot(deviceId);
    }
    
    // 检查是否为 iOS 模拟器
    const response = mobilecli.getDevices({
        platform: "ios",
        type: "simulator",
        includeOffline: false,
    });
    // ...
};

资料来源:src/server.ts:1-100

核心组件

Robot 接口定义

Robot 接口是所有设备交互的抽象基类,定义了统一的操作契约:

方法功能描述参数
getScreenSize()获取屏幕尺寸
getOrientation()获取屏幕方向
setOrientation(orientation)设置屏幕方向portraitlandscape
getScreenshot()获取屏幕截图
getElementsOnScreen()获取屏幕元素列表
tap(x, y)点击指定坐标x, y 坐标
doubleTap(x, y)双击指定坐标x, y 坐标
longPress(x, y, duration)长按指定坐标x, y, duration(ms)
swipeFromCoordinate(x, y, direction, distance)滑动操作起点坐标、方向、距离
sendKeys(text)输入文本文本内容
pressButton(button)按下物理按钮HOME, BACK, VOLUME_UP 等
openUrl(url)打开 URLURL 字符串
listApps()列出已安装应用
launchApp(packageName, locale?)启动应用包名,可选语言
terminateApp(packageName)终止应用包名
installApp(path)安装应用文件路径
uninstallApp(bundleId)卸载应用Bundle ID

资料来源:src/robot.ts:1-120

IosRobot 实现

IosRobot 是 iOS 平台的 Robot 接口实现,负责具体的 iOS 设备操作。该类封装了与 iOS 设备通信的所有逻辑,包括:

  • 元素查询与遍历
  • 坐标点击和手势操作
  • 文本输入
  • 应用管理
  • 截图获取

IosManager

IosManager 负责管理 iOS 设备的发现和状态监控:

  • listDevices() - 列出所有已连接的 iOS 真机
  • 设备健康状态检查

iPhone Simulator

iOS 模拟器通过 mobilecli 工具进行管理,提供与真机类似的交互能力。模拟器支持完整的功能测试,无需真实硬件即可进行 UI 自动化测试。

工作原理

设备连接流程

sequenceDiagram
    participant User as 用户
    participant Server as MCP Server
    participant IosManager as IosManager
    participant Device as iOS 设备
    participant WDA as WebDriverAgent/iOS Device Kit

    User->>Server: mobile_list_available_devices
    Server->>IosManager: listDevices()
    IosManager->>Device: 查询设备
    Device-->>IosManager: 设备列表
    IosManager-->>Server: 返回设备
    Server-->>User: 可用设备列表

    User->>Server: 选择设备并执行操作
    Server->>IosRobot: 创建实例
    IosRobot->>WDA: 初始化连接
    WDA->>Device: 建立通信

模拟器 Agent 验证

对于 iOS 模拟器,系统会自动验证并安装必要的 Agent:

if (!agentVerifiedSimulators.has(deviceId)) {
    const agentStatus = mobilecli.agentStatus(deviceId);
    if (agentStatus.status === "fail") {
        mobilecli.agentInstall(deviceId);
    }
    agentVerifiedSimulators.add(deviceId);
}

资料来源:src/server.ts:50-80

依赖组件

mobilecli

mobilecli 是项目的基础依赖工具,提供跨平台的移动设备管理能力:

{
  "optionalDependencies": {
    "mobilecli": "0.3.70"
  }
}

版本历史记录显示 mobilecli 版本持续更新以支持新功能和修复问题:

版本主要更新
0.3.70当前使用版本,支持最新 iOS Device Kit
0.3.68引入 iOS Device Kit
0.2.0早期版本

资料来源:package.json:25-30

iOS Device Kit vs WebDriverAgent

从 v0.0.53 版本开始,项目从 WebDriverAgent 迁移到开源的 iOS Device Kit(Apache 许可证),主要优势包括:

  • 开源许可证(WebDriverAgent 使用自定义许可证)
  • 更稳定的设备连接管理
  • 更好的黑屏问题处理
graph LR
    A[v0.0.52 及之前] -->|WebDriverAgent| B[闭源实现]
    C[v0.0.53 及之后] -->|iOS Device Kit| D[Apache 许可证]

资料来源:CHANGELOG.md

iOS 工具集

Mobile MCP 为 iOS 平台提供以下 MCP 工具:

设备管理

工具名称功能
mobile_list_available_devices列出所有可用设备(包含 iOS 模拟器和真机)
mobile_get_screen_size获取 iOS 设备屏幕尺寸
mobile_get_orientation获取当前屏幕方向
mobile_set_orientation设置屏幕方向

应用管理

工具名称功能
mobile_list_apps列出 iOS 设备上安装的所有应用
mobile_launch_app通过 Bundle ID 启动应用
mobile_terminate_app终止运行中的应用
mobile_install_app安装 .ipa 或 .app 文件
mobile_uninstall_app卸载应用

屏幕交互

工具名称功能
mobile_take_screenshot截取当前屏幕
mobile_save_screenshot保存截图到文件
mobile_list_elements_on_screen获取屏幕元素及属性
mobile_click_on_screen_at_coordinates点击指定坐标
mobile_double_tap_on_screen双击指定坐标
mobile_long_press_on_screen_at_coordinates长按指定坐标
mobile_swipe_on_screen滑动操作

输入与导航

工具名称功能
mobile_type_keys输入文本
mobile_press_button按下物理按钮(HOME、BACK、VOLUME 等)
mobile_open_url在浏览器中打开 URL

使用示例

配置 Claude Desktop

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["@mobilenext/mobile-mcp@latest"]
    }
  }
}

使用 Claude Code 连接 iOS 模拟器

claude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latest

列出可用设备

在 Claude Code 或其他 MCP 客户端中执行:

使用 mobile_list_available_devices 工具列出所有可用的 iOS 设备和模拟器

在 iOS 模拟器上测试应用

# 查看可用模拟器
xcrun simctl list

# 启动特定模拟器
xcrun simctl boot "iPhone 16"

# 使用 mobile_list_available_devices 获取设备 ID
# 然后使用 mobile_launch_app 启动测试应用

故障排除

常见问题

问题解决方案
设备未识别运行 xcrun simctl list 检查模拟器状态
WebDriverAgent 连接失败更新 mobilecli 到最新版本
模拟器黑屏使用 iOS Device Kit(v0.0.53+)或重启模拟器
Agent 未安装调用 mobilecli.agentInstall(deviceId)

验证 mobilecli 安装

const ensureMobilecliAvailable = (): void => {
    try {
        const version = mobilecli.getVersion();
        if (version.startsWith("failed")) {
            throw new Error("mobilecli version check failed");
        }
    } catch (error: any) {
        throw new ActionableError(`mobilecli is not available or not working properly. 
            Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki`);
    }
};

资料来源:src/server.ts:15-25

版本历史

版本iOS 相关更新
0.0.54更新 mobilecli 至 0.3.70;修复导致 iOS Device Kit 黑屏死机的问题
0.0.53引入 iOS Device Kit 替代 WebDriverAgent;添加崩溃报告工具
0.0.38迁移 iPhone Simulator 调用至 mobilecli;自动下载安装 WebDriverAgent
0.0.22修复 go-ios 安装检测问题
0.0.21模拟器上自动启动 WebDriverAgent

资料来源:CHANGELOG.md

扩展阅读

资料来源:[src/robot.ts:1-50]()

Android 实现

Android 实现是 mobile-mcp 项目的核心模块之一,负责与 Android 设备(真机、模拟器)进行交互。该模块通过 ADB(Android Debug Bridge)协议与设备通信,实现了设备管理、UI 元素检测、屏幕交互、应用管理等一系列移动端自动化能力。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 整体架构

继续阅读本节完整说明和来源证据。

章节 Android 通信流程

继续阅读本节完整说明和来源证据。

章节 AndroidDeviceManager

继续阅读本节完整说明和来源证据。

概述

Android 实现是 mobile-mcp 项目的核心模块之一,负责与 Android 设备(真机、模拟器)进行交互。该模块通过 ADB(Android Debug Bridge)协议与设备通信,实现了设备管理、UI 元素检测、屏幕交互、应用管理等一系列移动端自动化能力。

Android 模块的主要职责包括:

  • 通过 adb devices 命令发现和验证已连接的 Android 设备
  • 使用 uiautomator dump 获取界面层次结构并解析 UI 元素
  • 执行点击、双击、长按、滑动等手势操作
  • 管理应用生命周期(安装、卸载、启动、终止)
  • 截取屏幕截图和屏幕录制
  • 获取设备信息(屏幕尺寸、方向、系统版本等)

资料来源:src/android.ts:1-100

系统架构

整体架构

Mobile MCP 采用跨平台统一抽象的设计理念,通过 Robot 模式为 iOS 和 Android 提供统一的操作接口。Android 实现位于这一架构的核心层。

graph TD
    A[MCP Server] --> B[Device Manager]
    B --> C[Android Device Manager]
    B --> D[iOS Device Manager]
    C --> E[AndroidRobot]
    D --> F[IosRobot]
    E --> G[ADB Communication]
    G --> H[Android Device/Emulator]
    F --> I[WebDriverAgent/go-ios]
    I --> J[iOS Device/Simulator]

Android 通信流程

Android 设备通过 ADB 与服务端通信,每条命令的执行都遵循以下流程:

sequenceDiagram
    participant MCP as MCP Server
    participant AR as AndroidRobot
    participant ADB as ADB Command
    participant DEV as Android Device

    MCP->>AR: 调用 Android 方法
    AR->>ADB: 构建 adb 命令
    ADB->>DEV: 执行 shell 命令
    DEV-->>ADB: 返回执行结果
    ADB-->>AR: 解析响应数据
    AR-->>MCP: 返回结构化结果

资料来源:src/android.ts:50-150

核心组件

AndroidDeviceManager

AndroidDeviceManager 类负责设备发现和枚举,是 Android 模块的入口点。

方法说明返回类型
getConnectedDevices()获取已连接的真机和模拟器列表Array<{deviceId, deviceType}>
getConnectedDevicesWithDetails()获取包含详细信息的设备列表Array<{deviceId, deviceType, version, name}>

设备发现机制

// 从 android.ts 提取的关键实现逻辑
const names = execFileSync(getAdbPath(), ["devices"])
  .toString()
  .split("\n")
  .map(line => line.trim())
  .filter(line => line !== "")
  .filter(line => !line.startsWith("List of devices attached"))
  .filter(line => line.split("\t")[1]?.trim() === "device")  // 仅包含在线设备
  .map(line => line.split("\t")[0]);

设备必须满足两个条件才会被返回:

  1. 出现在 adb devices 命令输出中
  2. 状态为 device(而非 offlineunauthorized

资料来源:src/android.ts:180-220

AndroidRobot

AndroidRobot 是与单个 Android 设备交互的核心类,封装了所有设备操作。

属性/方法说明
deviceId设备标识符
getScreenSize()获取屏幕分辨率
getOrientation()获取屏幕方向
setOrientation()设置屏幕方向
listElementsOnScreen()获取屏幕元素列表
click()点击指定坐标
doubleTap()双击指定坐标
longPress()长按指定坐标
swipe()滑动操作
typeKeys()输入文本
pressButton()按压物理按钮
takeScreenshot()截取屏幕截图
startScreenRecording()开始屏幕录制
stopScreenRecording()停止屏幕录制
launchApp()启动应用
terminateApp()终止应用
installApp()安装应用
uninstallApp()卸载应用
listRunningProcesses()列出运行中的进程

资料来源:src/android.ts:100-350

设备发现机制

设备类型检测

Android 模块通过读取系统属性来判断设备类型:

private getDeviceType(deviceId: string): string {
  const output = this.adb(deviceId, "getprop", "ro.build.characteristics");
  if (output.toString().includes("emulator")) {
    return "emulator";
  }
  return "device";
}

支持的设备类型:

  • emulator: Android 模拟器
  • device: Android 真机

系统信息获取

属性获取方式说明
versiongetprop ro.build.version.releaseAndroid 系统版本
namegetprop ro.product.model设备型号名称

资料来源:src/android.ts:200-250

UI 元素检测

界面层次结构获取

Android 使用 uiautomator dump 命令获取当前界面的 UI 层次结构(Accessibility Tree):

public async listElementsOnScreen(): Promise<ScreenElements> {
  const output = this.uiautomatorDump();
  const parsed = this.parseUIAutomatorXML(output);
  return parsed;
}

XML 解析流程

graph LR
    A[Raw XML Output] --> B[fast-xml-parser]
    B --> C[解析后对象]
    C --> D[提取 node 属性]
    D --> E[构建元素数组]
    E --> F[ScreenElements]

元素属性提取

解析后的 UI 元素包含以下关键属性:

属性XML 路径说明
text@text元素文本内容
resourceId@resource-id资源 ID
className@class类名
bounds@bounds坐标边界
contentDesc@content-desc内容描述
clickable@clickable是否可点击
enabled@enabled是否启用

元素选择器优先级

系统使用以下属性按优先级查找元素:

  1. content-desc (Accessibility Hint)
  2. text (显示文本)
  3. resource-id (资源 ID)
  4. class-name + text 组合

资料来源:src/android.ts:250-350

坐标计算

元素的点击坐标基于 bounds 属性计算:

// bounds 格式: [x1,y1][x2,y2]
const match = bounds.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);
if (match) {
  const x = Math.floor((parseInt(match[1]) + parseInt(match[3])) / 2);
  const y = Math.floor((parseInt(match[2]) + parseInt(match[4])) / 2);
  // 返回中心点坐标
}

资料来源:src/android.ts:300-330

屏幕交互

点击操作

方法命令参数
click(x, y)input tapx, y 坐标
doubleTap(x, y)input swipe + 时间控制x, y 坐标
longPress(x, y)input swipe + 长间隔x, y 坐标, 时长

双击实现原理

public async doubleTap(x: number, y: number): Promise<void> {
  const duration = 50; // 50ms 内完成两次点击
  this.adb(deviceId, "shell", "input", "swipe", 
    `${x} ${y} ${x} ${y} ${duration}`);
}

滑动操作

滑动方向基于屏幕尺寸百分比计算起始和终止坐标:

public async swipe(direction: SwipeDirection): Promise<void> {
  const screenSize = await this.getScreenSize();
  const centerX = screenSize.width >> 1;  // 屏幕宽度一半

  switch (direction) {
    case "up":
      // 从底部 80% 位置滑到顶部 20% 位置
      y0 = Math.floor(screenSize.height * 0.80);
      y1 = Math.floor(screenSize.height * 0.20);
      break;
    case "down":
      // 从顶部 20% 位置滑到底部 80% 位置
      y0 = Math.floor(screenSize.height * 0.20);
      y1 = Math.floor(screenSize.height * 0.80);
      break;
    // left/right 方向类似
  }
  
  this.adb(deviceId, "shell", "input", "swipe", 
    `${x0} ${y0} ${x1} ${y1} ${duration}`);
}

滑动参数表

方向起始位置终止位置默认时长
upy = 80% 屏幕高度y = 20% 屏幕高度300ms
downy = 20% 屏幕高度y = 80% 屏幕高度300ms
leftx = 80% 屏幕宽度x = 20% 屏幕宽度300ms
rightx = 20% 屏幕宽度x = 80% 屏幕宽度300ms

资料来源:src/android.ts:350-420

物理按钮

支持的物理按钮:

按钮名称ADB 命令
HOMEinput keyevent KEYCODE_HOME
BACKinput keyevent KEYCODE_BACK
ENTERinput keyevent KEYCODE_ENTER
VOLUME_UPinput keyevent KEYCODE_VOLUME_UP
VOLUME_DOWNinput keyevent KEYCODE_VOLUME_DOWN
POWERinput keyevent KEYCODE_POWER

资料来源:src/android.ts:420-480

应用管理

应用安装与卸载

安装流程

public async installApp(filePath: string): Promise<void> {
  this.adb(deviceId, "install", "-r", filePath);
}
  • -r 标志表示覆盖安装(允许降级)
  • 支持的文件格式:.apk

卸载流程

public async uninstallApp(packageName: string): Promise<void> {
  this.adb(deviceId, "uninstall", packageName);
}

应用启动

启动应用使用 monkey 命令触发 LAUNCHER Intent:

public async launchApp(packageName: string, locale?: string): Promise<void> {
  validatePackageName(packageName);

  if (locale) {
    validateLocale(locale);
    try {
      // Android 13+ 支持设置应用语言
      this.silentAdb("shell", "cmd", "locale", "set-app-locales", 
        packageName, "--locales", locale);
    } catch (error) {
      // 静默忽略旧版本 Android 的语言设置失败
    }
  }

  this.adb("shell", "monkey", "-p", packageName, 
    "-c", "android.intent.category.LAUNCHER", "1");
}

包名验证规则

function validatePackageName(packageName: string): void {
  // 包名必须至少包含一个点
  // 例如: com.example.app
  if (!packageName.includes(".")) {
    throw new Error("Invalid package name format");
  }
}

资料来源:src/android.ts:100-180

运行进程查询

public async listRunningProcesses(): Promise<string[]> {
  return this.adb("shell", "ps", "-e")
    .toString()
    .split("\n")
    .map(line => line.trim())
    .filter(line => line.startsWith("u"))  // 非系统进程
    .map(line => line.split(/\s+/)[8]);    // 获取进程名
}

屏幕截图与录制

截图

截图功能使用 screencap 命令:

public async takeScreenshot(): Promise<Buffer> {
  const output = this.adb(deviceId, "exec-out", "screencap", "-p");
  return output;
}
  • 使用 exec-out 而非 shell 避免 CR/LF 换行符问题
  • 返回 PNG 格式的二进制数据

Windows 兼容性修复

版本 0.0.15 修复了 Windows 上的换行符问题:

Android: Fixed broken Android screenshots on Windows because of crlf (#53)

资料来源:CHANGELOG.md

屏幕录制

Android 10+ 支持原生屏幕录制功能:

public async startScreenRecording(
  filePath: string, 
  options?: ScreenRecordingOptions
): Promise<void> {
  const { width, height, bitRate, timeLimit } = options || {};
  
  const args = [
    "shell", "screenrecord",
    "--output-format", "h264",
    "--time-limit", String(timeLimit || 180),
    filePath
  ];
  
  if (width && height) {
    args.push("--size", `${width}x${height}`);
  }
  
  this.adb(deviceId, ...args);
}

录制参数表

参数默认值说明
timeLimit180秒最长录制时间
width设备宽度视频宽度
height设备高度视频高度
bitRate系统默认视频比特率

版本 0.0.46 新增了对 Android 模拟器和真机的屏幕录制支持。

资料来源:CHANGELOG.md

ADB 命令封装

核心执行方法

private adb(...args: string[]): Buffer {
  return execFileSync(getAdbPath(), args);
}

private silentAdb(...args: string[]): void {
  try {
    execFileSync(getAdbPath(), args);
  } catch {
    // 静默忽略错误
  }
}

ADB 路径解析

ADB 路径通过环境变量 ANDROID_HOME 配置:

import { execFileSync } from "child_process";
import { join } from "path";

function getAdbPath(): string {
  const androidHome = process.env.ANDROID_HOME;
  if (androidHome) {
    return join(androidHome, "platform-tools", "adb");
  }
  return "adb";  // 使用系统 PATH 中的 adb
}

版本 0.0.12 引入了对 ANDROID_HOME 路径下 adb 的支持。

资料来源:CHANGELOG.md

与服务端集成

设备类型检测

server.ts 中,服务端通过 AndroidDeviceManager 判断设备类型:

// src/server.ts 中的设备检测逻辑
const androidManager = new AndroidDeviceManager();
const androidDevices = androidManager.getConnectedDevices();
const androidDevice = androidDevices.find(d => d.deviceId === deviceId);

if (androidDevice) {
  return new AndroidRobot(deviceId);
}

设备不可用错误处理

const ensureMobilecliAvailable = (): void => {
  try {
    const version = mobilecli.getVersion();
    if (version.startsWith("failed")) {
      throw new Error("mobilecli version check failed");
    }
  } catch (error: any) {
    throw new ActionableError(
      `mobilecli is not available or not working properly. ` +
      `Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki`
    );
  }
};

资料来源:src/server.ts:30-60

依赖项

生产依赖

依赖包版本用途
fast-xml-parser5.5.7解析 uiautomator XML 输出
zod^4.1.13参数验证和类型定义

可选依赖

依赖包版本用途
mobilecli0.3.70辅助 CLI 工具

系统要求

  • Node.js >= 18
  • Android SDK (含 platform-tools)
  • 已连接的 Android 设备或模拟器

资料来源:package.json

版本历史

版本发布日期主要变更
0.0.462026-03-03新增屏幕录制支持
0.0.452026-03-02修复 shell 转义问题
0.0.322025-10-08新增双击支持,减少 stdout 污染
0.0.312025-10-07修复 libc 兼容性问题
0.0.302025-10-06支持应用语言设置
0.0.232025-07-31修复折叠屏设备截图问题
0.0.152025-05-04修复 Windows 截图 CRLF 问题
0.0.142025-05-02优化 UI 元素检测,尝试多次 uiautomator dump
0.0.132025-04-20使用 accessibility hints 和 class names 查找元素
0.0.122025-04-12支持 ANDROID_HOME 环境变量

资料来源:CHANGELOG.md

常见问题排查

设备未被发现

  1. 确认设备已通过 USB 连接且授权调试
  2. 运行 adb devices 确认设备状态为 device
  3. 检查 ANDROID_HOME 环境变量是否正确设置

截图失败

  1. 确认设备屏幕未锁定
  2. 检查设备是否支持 screencap 命令(Android 4.0+)
  3. 验证磁盘空间充足

元素定位不准确

  1. 使用 listElementsOnScreen 工具获取最新界面状态
  2. 优先使用 content-desctext 属性定位
  3. 考虑使用坐标点击作为备选方案

uiautomator dump 超时

版本 0.0.14 实现了多次重试机制,自动重试 UI 层次结构获取。

总结

Android 实现为 mobile-mcp 提供了完整的 Android 设备自动化能力。通过 ADB 协议与设备通信,该模块实现了设备发现、UI 元素检测、屏幕交互、应用管理等核心功能。统一的接口设计使得 Android 和 iOS 平台可以无缝切换,为跨平台移动端自动化提供了坚实基础。

资料来源:[src/android.ts:1-100]()

故障排除

本文档提供 Mobile MCP 常见问题的诊断和解决方案。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 必需组件

继续阅读本节完整说明和来源证据。

章节 mobilecli 可用性检查

继续阅读本节完整说明和来源证据。

章节 架构概览

继续阅读本节完整说明和来源证据。

前提条件检查

必需组件

确保系统已安装所有必需组件:

组件说明最低版本
Node.js运行环境>=18
mobilecli命令行工具0.3.70
Xcode (iOS)iOS 开发环境-
Xcode Command Line ToolsXcode 命令行工具-
go-iosiOS 设备通信-
Android SDK (Android)Android 开发环境-
ADBAndroid 调试桥接器-

mobilecli 可用性检查

Mobile MCP 启动时会自动检查 mobilecli 是否可用:

const ensureMobilecliAvailable = (): void => {
    try {
        const version = mobilecli.getVersion();
        if (version.startsWith("failed")) {
            throw new Error("mobilecli version check failed");
        }
    } catch (error: any) {
        throw new ActionableError(`mobilecli is not available or not working properly. Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki for installation instructions`);
    }
};

资料来源src/server.ts

如果遇到 mobilecli 相关错误,请参考 官方 Wiki 安装指南

iOS 设备问题排查

架构概览

graph TD
    A[Mobile MCP] --> B[iOS Manager]
    B --> C{iOS Tunnel Required?}
    C -->|Yes| D[iOS Tunnel Status]
    C -->|No| E[WebDriverAgent Check]
    D --> F{Tunnel Running?}
    F -->|Yes| E
    F -->|No| G[Error: iOS tunnel not running]
    E --> H{WDA Forward Running?}
    H -->|Yes| I[Create WebDriverAgent]
    H -->|No| J[Error: Port forwarding not running]
    I --> K[Return WebDriverAgent]

iOS Tunnel 未运行

当检测到 iOS Tunnel 未运行时,会抛出以下错误:

iOS tunnel is not running, please see https://github.com/mobile-next/mobile-mcp/wiki/

资料来源src/ios.ts

解决方案

  1. 确保已启动 iOS Tunnel 服务
  2. 检查 Xcode Command Line Tools 已正确安装
  3. 验证设备已通过 USB 连接
  4. 参考 官方 Wiki iOS 隧道配置指南

WebDriverAgent 问题

#### 端口转发未运行

Port forwarding to WebDriverAgent is not running (tunnel okay), please see https://github.com/mobile-next/mobile-mcp/wiki/

资料来源src/ios.ts

排查步骤

  1. 确认 iOS Tunnel 已正常运行
  2. 检查端口 8100 是否被占用
  3. 重启 WebDriverAgent 服务

#### WebDriverAgent 服务未运行

WebDriverAgent is not running on device (tunnel okay, port forwarding okay), please see https://github.com/mobile-next/mobile-mcp/wiki/

资料来源src/ios.ts

解决方案

  1. 在 iOS 设备上手动启动 WebDriverAgent
  2. 确保设备已通过 Xcode 授权用于开发
  3. 检查设备是否信任计算机

iOS Tunnel 健康检查

系统通过以下方式检查 iOS Tunnel 状态:

检查项方法失败时的错误信息
Tunnel 端口监听isListeningOnPort(IOS_TUNNEL_PORT)iOS tunnel is not running
WDA 端口转发isListeningOnPort(WDA_PORT)Port forwarding to WebDriverAgent is not running
WDA 服务状态wda.isRunning()WebDriverAgent is not running on device

资料来源src/ios.ts

Android 设备问题排查

设备连接检查

graph LR
    A[Android Device] --> B[ADB Daemon]
    B --> C{Device Connected?}
    C -->|Yes| D[AndroidRobot Ready]
    C -->|No| E[Error: Device not found]
    D --> F[Execute Commands]

ADB 设备未找到

排查步骤

  1. 确认设备已通过 USB 连接并启用 USB 调试
  2. 运行 adb devices 检查设备列表
  3. 如果设备未列出,尝试:
  • 重启 ADB 服务:adb kill-server && adb start-server
  • 检查设备授权状态
  • 更换 USB 数据线

Android 命令执行

Android 设备通过 adb shell 执行命令:

public runCommand(args: string[]): string {
    return execFileSync("adb", ["-s", this.deviceId, "shell", ...args], {
        encoding: "utf-8",
    }).toString();
}

资料来源src/mobile-device.ts

常见错误处理

错误类型可能原因解决方案
设备离线USB 连接不稳定重新连接或更换数据线
未授权设备未授权调试在设备上点击"允许调试"
无响应设备系统无响应重启设备

iOS 模拟器问题排查

应用安装失败

#### ZIP 文件处理错误

graph TD
    A[Install App Request] --> B{File Extension?}
    B -->|.zip| C[Extract ZIP File]
    B -->|.app| D[Direct Install]
    C --> E{Path Validation}
    E -->|Valid| F[Find .app Bundle]
    E -->|Invalid| G[Error: Zip Slip]
    F --> H{App Bundle Found?}
    H -->|Yes| I[Install .app]
    H -->|No| J[Error: No .app bundle found]

资料来源src/iphone-simulator.ts

#### 常见安装错误

错误信息可能原因解决方案
No .app bundle found in the .zip fileZIP 内不含 .app 包确保 ZIP 包含正确的 iOS 应用包
Failed to unzip fileZIP 文件损坏或密码保护验证 ZIP 文件完整性
Zip Slip 漏洞检测失败ZIP 包含路径遍历攻击使用安全的 ZIP 文件
simctl install failed模拟器未运行或不支持启动目标模拟器

资料来源src/iphone-simulator.ts

ZIP 安全验证

系统会验证 ZIP 文件路径,防止 Zip Slip 攻击:

private validateZipPaths(path: string): void {
    // 确保 ZIP 文件不包含恶意路径
    trace(`Detected .zip file, validating contents`);
}

资料来源src/iphone-simulator.ts

通用设备管理问题

设备识别流程

graph TD
    A[Get Robot Request] --> B[Ensure mobilecli Available]
    B --> C{Check iOS Devices}
    C -->|Found| D[Create IosRobot]
    C -->|Not Found| E{Check Android Devices}
    E -->|Found| F[Create AndroidRobot]
    E -->|Not Found| G{Check iOS Simulators}
    G -->|Found| H[Create IosRobot]
    G -->|Not Found| I[Return Error]

资料来源src/server.ts

设备类型检测优先级

  1. iOS 物理设备 - 通过 IosManager.listDevices() 检测
  2. Android 物理设备 - 通过 AndroidDeviceManager.getConnectedDevices() 检测
  3. iOS 模拟器 - 通过 mobilecli.getDevices() 检测

资料来源src/server.ts

录制功能问题

录制超时处理

录制功能设置了 5 分钟超时限制:

const timeout = setTimeout(() => {
    child.kill("SIGKILL");
    resolve();
}, 5 * 60 * 1000);

资料来源src/server.ts

常见问题

问题原因解决方案
录制被强制终止超过 5 分钟限制缩短录制时长
输出文件未找到录制异常终止检查设备存储空间
文件大小为 0录制未成功启动检查设备屏幕状态

录制输出检查

录制完成后,系统会验证输出文件:

if (!fs.existsSync(outputPath)) {
    return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
}

const stats = fs.statSync(outputPath);
const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2);

资料来源src/server.ts

崩溃报告问题

获取崩溃列表

使用 mobile_list_crashes 工具获取设备上的崩溃报告:

tool(
    "mobile_list_crashes",
    "List Crash Reports",
    "List crash reports available on the device",
    {
        device: z.string().describe("The device identifier to use..."),
    },
    { readOnlyHint: true },
    async ({ device }) => {
        ensureMobilecliAvailable();
        const response = mobilecli.crashesList(device);
        return JSON.stringify(response.data);
    }
);

资料来源src/server.ts

排查步骤

  1. 确认 mobilecli 可用
  2. 检查设备是否有足够的存储空间
  3. 验证崩溃报告未被清理

环境变量配置

SSE 服务器认证

使用 MOBILEMCP_AUTH 环境变量配置 Bearer Token 认证:

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

所有请求必须包含 Authorization: Bearer my-secret-token 头。

日志和调试

启用调试日志

在运行时设置日志级别以获取详细输出:

参考 src/logger.ts 获取日志配置详情。

常见错误类型

错误类型来源说明
ActionableErrorMobile MCP包含可操作建议的错误
系统错误Node.js/adb底层系统级错误
网络错误端口转发/Tunnel连接问题

获取帮助

如果以上方案无法解决您的问题:

  1. 访问 官方 Wiki 文档
  2. 加入 Slack 社区
  3. 查看 已知问题
  4. 查看 路线图 了解即将修复的功能

来源:https://github.com/mobile-next/mobile-mcp / 项目说明书

安全配置

Mobile MCP 提供了多层安全机制来保护服务器通信和文件系统操作。本文档详细介绍各项安全配置的使用方法和最佳实践。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 Bearer Token 认证

继续阅读本节完整说明和来源证据。

章节 认证错误处理

继续阅读本节完整说明和来源证据。

章节 路径遍历防护

继续阅读本节完整说明和来源证据。

认证机制

Bearer Token 认证

当 Mobile MCP 以 SSE 服务器模式运行时,可通过设置 MOBILEMCP_AUTH 环境变量启用 Bearer Token 认证。

#### 配置方式

MOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000

#### 认证流程

sequenceDiagram
    participant Client as MCP 客户端
    participant Server as Mobile MCP Server
    
    Client->>Server: 请求 /mcp 端点
    Server->>Server: 检查 Authorization Header
    alt 未设置 MOBILEMCP_AUTH
        Server->>Server: 允许无认证访问
    else 设置了 MOBILEMCP_AUTH
        alt 缺少 Authorization Header
            Server-->>Client: 401 Unauthorized
        else Token 不匹配
            Server-->>Client: 401 Unauthorized
        else Token 正确
            Server-->>Client: 200 OK + MCP 响应
        end
    end

#### 请求格式要求

所有请求必须包含以下 HTTP Header:

Authorization: Bearer my-secret-token
配置项环境变量说明必需
认证令牌MOBILEMCP_AUTH设置 Bearer Token 值SSE 模式下必需

认证错误处理

当认证失败时,服务器返回标准的 HTTP 401 状态码。客户端需要确保在配置中正确设置认证令牌,避免连接失败。

文件系统安全

路径遍历防护

Mobile MCP 在保存截图和录制视频功能中实现了路径遍历防护机制,防止恶意请求访问预期目录之外的文件。

#### 安全修复历史

版本日期修复内容PR
0.0.492026-03-24修复截图和视频保存中的路径遍历漏洞#296

#### 受保护的文件操作

graph TD
    A[文件保存请求] --> B{验证路径}
    B -->|包含 ../ 或绝对路径 | C[拒绝访问]
    B -->|合法相对路径 | D[执行保存操作]
    C --> E[返回安全错误]
    D --> F[保存到 lib/screenshots 或 lib/videos 目录]

依赖安全

安全更新机制

Mobile MCP 定期更新依赖包以修复已知安全漏洞。

#### 安全更新历史

版本日期更新内容PR
0.0.482026-03-20fast-xml-parser 安全更新#292
0.0.472026-03-09更新依赖包以提升安全性#285

#### 关键依赖安全状态

依赖包版本用途安全状态
@modelcontextprotocol/sdk1.26.0MCP 协议实现已审核
fast-xml-parser5.5.7XML 解析已更新
express5.1.0SSE 服务器框架已审核
zod4.1.13参数验证已审核

运行时安全检查

mobilecli 可用性验证

服务器启动时执行 mobilecli 可用性检查,确保底层工具正常工作:

const ensureMobilecliAvailable = (): void => {
    try {
        const version = mobilecli.getVersion();
        if (version.startsWith("failed")) {
            throw new Error("mobilecli version check failed");
        }
    } catch (error: any) {
        throw new ActionableError(`mobilecli is not available or not working properly...`);
    }
};

如果 mobilecli 不可用或工作异常,服务器将抛出可操作的错误提示,指导用户访问文档进行排查。

设备类型验证

getRobotFromDevice 函数通过设备 ID 确定设备类型,并创建对应的 Robot 实例:

graph TD
    A[接收 deviceId] --> B{检查 iOS 设备}
    B -->|找到 | C[返回 IosRobot]
    B -->|未找到 | D{检查 Android 设备}
    D -->|找到 | E[返回 AndroidRobot]
    D -->|未找到 | F{检查 iOS 模拟器}
    F -->|找到 | G[返回 IosRobot]
    F -->|未找到 | H[抛出 ActionableError]

安全配置最佳实践

开发环境

{
  "mcpServers": {
    "mobile-mcp": {
      "command": "npx",
      "args": ["-y", "@mobilenext/mobile-mcp@latest"]
    }
  }
}

生产环境(启用认证)

# 设置强认证令牌
export MOBILEMCP_AUTH="$(openssl rand -hex 32)"

# 启动 SSE 服务器
npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000

配置参数表

参数命令行环境变量说明默认值
监听地址--listen <port>-SSE 服务器监听端口无(stdio 模式)
绑定接口--listen <ip:port>-指定绑定地址localhost
认证令牌-MOBILEMCP_AUTHBearer Token

报告安全漏洞

如发现安全漏洞,请通过以下方式报告:

安全版本对照表

功能支持版本说明
Bearer Token 认证全部版本SSE 模式下通过 MOBILEMCP_AUTH 配置
路径遍历防护≥ 0.0.49保护截图和视频文件操作
fast-xml-parser 更新≥ 0.0.48XML 解析安全修复
mobilecli 检查全部版本启动时验证工具可用性

来源:https://github.com/mobile-next/mobile-mcp / 项目说明书

失败模式与踩坑日记

保留 Doramagic 在发现、验证和编译中沉淀的项目专属风险,不把社区讨论只当作装饰信息。

high 来源证据:feat(iOS): add Unix Domain Socket support for usbmuxd (/var/run/usbmuxd) with TCP fallback

可能增加新用户试用和生产接入成本。

high 来源证据:mobile_type_keys not support Chinese words

可能增加新用户试用和生产接入成本。

high 来源证据:Default-on telemetry creates security and compliance risk for enterprise users

可能阻塞安装或首次运行。

high 来源证据:iOS physical-device support blocked on macOS 26 (Tahoe) — go-ios can't read /var/db/lockdown/RemotePairing/

可能阻塞安装或首次运行。

Pitfall Log / 踩坑日志

项目:mobile-next/mobile-mcp

摘要:发现 21 个潜在踩坑项,其中 4 个为 high/blocking;最高优先级:配置坑 - 来源证据:feat(iOS): add Unix Domain Socket support for usbmuxd (/var/run/usbmuxd) with TCP fallback。

1. 配置坑 · 来源证据:feat(iOS): add Unix Domain Socket support for usbmuxd (/var/run/usbmuxd) with TCP fallback

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:feat(iOS): add Unix Domain Socket support for usbmuxd (/var/run/usbmuxd) with TCP fallback
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_dbf2449bab944bc99876270f1ec05c62 | https://github.com/mobile-next/mobile-mcp/issues/322 | 来源讨论提到 macos 相关条件,需在安装/试用前复核。

2. 配置坑 · 来源证据:mobile_type_keys not support Chinese words

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:mobile_type_keys not support Chinese words
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_2dc233de12994981b510eaee492c2389 | https://github.com/mobile-next/mobile-mcp/issues/238 | 来源类型 github_issue 暴露的待验证使用条件。

3. 安全/权限坑 · 来源证据:Default-on telemetry creates security and compliance risk for enterprise users

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Default-on telemetry creates security and compliance risk for enterprise users
  • 对用户的影响:可能阻塞安装或首次运行。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_5f969914c2b845edae80052061f7b4c3 | https://github.com/mobile-next/mobile-mcp/issues/330 | 来源类型 github_issue 暴露的待验证使用条件。

4. 安全/权限坑 · 来源证据:iOS physical-device support blocked on macOS 26 (Tahoe) — go-ios can't read /var/db/lockdown/RemotePairing/

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:iOS physical-device support blocked on macOS 26 (Tahoe) — go-ios can't read /var/db/lockdown/RemotePairing/
  • 对用户的影响:可能阻塞安装或首次运行。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0a003bada38d4c7b85ace117a1057fba | https://github.com/mobile-next/mobile-mcp/issues/323 | 来源讨论提到 npm 相关条件,需在安装/试用前复核。

5. 配置坑 · 来源证据:start/stop_screen_recording produces corrupt files on Android and silently fails on iOS physical devices

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:start/stop_screen_recording produces corrupt files on Android and silently fails on iOS physical devices
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0cfa3373dd3042f885f3bfc06594d58b | https://github.com/mobile-next/mobile-mcp/issues/321 | 来源讨论提到 macos 相关条件,需在安装/试用前复核。
  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题:mobile fleet documentation link broken
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_b92402a79ce24b41b5f9ca2351e56e81 | https://github.com/mobile-next/mobile-mcp/issues/328 | 来源类型 github_issue 暴露的待验证使用条件。

7. 能力坑 · 能力判断依赖假设

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:README/documentation is current enough for a first validation pass.
  • 对用户的影响:假设不成立时,用户拿不到承诺的能力。
  • 建议检查:将假设转成下游验证清单。
  • 防护动作:假设必须转成验证项;没有验证结果前不能写成事实。
  • 证据:capability.assumptions | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | README/documentation is current enough for a first validation pass.

8. 维护坑 · 来源证据:Version 0.0.49

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题:Version 0.0.49
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_885b7e8395a34cc8aaa7ce492d0b5d31 | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.49 | 来源类型 github_release 暴露的待验证使用条件。

9. 维护坑 · 来源证据:Version 0.0.54

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题:Version 0.0.54
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_02193405127b48d2a7d25148f61b2e9b | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.54 | 来源类型 github_release 暴露的待验证使用条件。

10. 维护坑 · 维护活跃度未知

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:未记录 last_activity_observed。
  • 对用户的影响:新项目、停更项目和活跃项目会被混在一起,推荐信任度下降。
  • 建议检查:补 GitHub 最近 commit、release、issue/PR 响应信号。
  • 防护动作:维护活跃度未知时,推荐强度不能标为高信任。
  • 证据:evidence.maintainer_signals | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | last_activity_observed missing

11. 安全/权限坑 · 下游验证发现风险项

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:下游已经要求复核,不能在页面中弱化。
  • 建议检查:进入安全/权限治理复核队列。
  • 防护动作:下游风险存在时必须保持 review/recommendation 降级。
  • 证据:downstream_validation.risk_items | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | no_demo; severity=medium

12. 安全/权限坑 · 存在安全注意事项

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:No sandbox install has been executed yet; downstream must verify before user use.
  • 对用户的影响:用户安装前需要知道权限边界和敏感操作。
  • 建议检查:转成明确权限清单和安全审查提示。
  • 防护动作:安全注意事项必须面向用户前置展示。
  • 证据:risks.safety_notes | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | No sandbox install has been executed yet; downstream must verify before user use.

13. 安全/权限坑 · 存在评分风险

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:风险会影响是否适合普通用户安装。
  • 建议检查:把风险写入边界卡,并确认是否需要人工复核。
  • 防护动作:评分风险必须进入边界卡,不能只作为内部分数。
  • 证据:risks.scoring_risks | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | no_demo; severity=medium

14. 安全/权限坑 · 来源证据:Version 0.0.45

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.45
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_e5939588c2f74a4f8e7ae874c9fee9f2 | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.45 | 来源类型 github_release 暴露的待验证使用条件。

15. 安全/权限坑 · 来源证据:Version 0.0.47

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.47
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_6f22eab42c4140bf9692e3ff9f80dc62 | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.47 | 来源类型 github_release 暴露的待验证使用条件。

16. 安全/权限坑 · 来源证据:Version 0.0.48

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.48
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_4e414a95529d4f27bb06648558502daa | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.48 | 来源类型 github_release 暴露的待验证使用条件。

17. 安全/权限坑 · 来源证据:Version 0.0.51

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.51
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_eca0ad1c1f574a52897db27953196b98 | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.51 | 来源类型 github_release 暴露的待验证使用条件。

18. 安全/权限坑 · 来源证据:Version 0.0.52

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.52
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0c0b172807554ff4b1969c4fff8abf4b | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.52 | 来源讨论提到 npm 相关条件,需在安装/试用前复核。

19. 安全/权限坑 · 来源证据:Version 0.0.53

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Version 0.0.53
  • 对用户的影响:可能阻塞安装或首次运行。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_c0fb42201cf24850bcd4fa91470e2042 | https://github.com/mobile-next/mobile-mcp/releases/tag/0.0.53 | 来源类型 github_release 暴露的待验证使用条件。

20. 维护坑 · issue/PR 响应质量未知

  • 严重度:low
  • 证据强度:source_linked
  • 发现:issue_or_pr_quality=unknown。
  • 对用户的影响:用户无法判断遇到问题后是否有人维护。
  • 建议检查:抽样最近 issue/PR,判断是否长期无人处理。
  • 防护动作:issue/PR 响应未知时,必须提示维护风险。
  • 证据:evidence.maintainer_signals | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | issue_or_pr_quality=unknown

21. 维护坑 · 发布节奏不明确

  • 严重度:low
  • 证据强度:source_linked
  • 发现:release_recency=unknown。
  • 对用户的影响:安装命令和文档可能落后于代码,用户踩坑概率升高。
  • 建议检查:确认最近 release/tag 和 README 安装命令是否一致。
  • 防护动作:发布节奏未知或过期时,安装说明必须标注可能漂移。
  • 证据:evidence.maintainer_signals | github_repo:956657893 | https://github.com/mobile-next/mobile-mcp | release_recency=unknown

来源:Doramagic 发现、验证与编译记录