Mobile MCP: let AI agents drive your iOS and Android apps. MCP server for simulators, emulators and real devices. Works with Claude Code, Codex, Cursor and any MCP client.
TypeScript agentandroidandroid-automationappium-alternativeclaude-codecodexcursoremulatoriosios-automationmcpmcp-servermobilemobile-automationmobile-testingreal-devicesimulatorskills
fix: detect errors and point to wiki (#23)
Wim Selles0fc1f89ea768
diff --git a/src/android.ts b/src/android.tsindex 48c008b..4da5cef 100644--- a/src/android.ts+++ b/src/android.ts@@ -3,7 +3,7 @@ import { execFileSync } from "child_process";import * as xml from "fast-xml-parser";-import { Bounds, Button, Dimensions, ElementCoordinates, InstalledApp, Robot, SwipeDirection } from "./robot";+import { ActionableError, Bounds, Button, Dimensions, ElementCoordinates, InstalledApp, Robot, SwipeDirection } from "./robot";interface UiAutomatorXmlNode {node: UiAutomatorXmlNode[];@@ -101,7 +101,7 @@ export class AndroidRobot implements Robot {y1 = Math.floor(screenSize.height * 0.80);break;default:- throw new Error(`Swipe direction "${direction}" is not supported`);+ throw new ActionableError(`Swipe direction "${direction}" is not supported`);}this.adb("shell", "input", "swipe", `${x0}`, `${y0}`, `${x1}`, `${y1}`, "1000");@@ -194,7 +194,7 @@ export class AndroidRobot implements Robot {public async pressButton(button: Button) {if (!BUTTON_MAP[button]) {- throw new Error(`Button "${button}" is not supported`);+ throw new ActionableError(`Button "${button}" is not supported`);}this.adb("shell", "input", "keyevent", BUTTON_MAP[button]);diff --git a/src/ios.ts b/src/ios.tsindex 2e983dd..5e3d8ff 100644--- a/src/ios.ts+++ b/src/ios.ts@@ -6,7 +6,7 @@ import { execFileSync } from "child_process";import { Socket } from "net";import { ScreenElement, WebDriverAgent } from "./webdriver-agent";-import { Button, Dimensions, InstalledApp, Robot, SwipeDirection } from "./robot";+import { ActionableError, Button, Dimensions, InstalledApp, Robot, SwipeDirection } from "./robot";const WDA_PORT = 8100;const IOS_TUNNEL_PORT = 60105;@@ -15,6 +15,10 @@ interface ListCommandOutput {deviceList: string[];}+interface VersionCommandOutput {+ version: string;+}+const getGoIosPath = (): string => {return "ios";};@@ -46,16 +50,28 @@ export class IosRobot implements Robot {return await this.isListeningOnPort(WDA_PORT);}- private async wda(): Promise<WebDriverAgent> {- if (!(await this.isTunnelRunning())) {- throw new Error("iOS tunnel is not running, please see https://github.com/mobile-next/mobile-mcp/wiki/Getting-Started-with-iOS");+ private async assertTunnelRunning(): Promise<void> {+ if (await this.isTunnelRequired()) {+ if (!(await this.isTunnelRunning())) {+ throw new ActionableError("iOS tunnel is not running, please see https://github.com/mobile-next/mobile-mcp/wiki/");+ }}+ }++ private async wda(): Promise<WebDriverAgent> {++ await this.assertTunnelRunning();if (!(await this.isWdaForwardRunning())) {- throw new Error("Port forwarding to WebDriverAgent is not running, please see https://github.com/mobile-next/mobile-mcp/wiki/Getting-Started-with-iOS");+ throw new ActionableError("Port forwarding to WebDriverAgent is not running (tunnel okay), please see https://github.com/mobile-next/mobile-mcp/wiki/");}const wda = new WebDriverAgent("localhost", WDA_PORT);++ if (!(await wda.isRunning())) {+ throw new ActionableError("WebDriverAgent is not running on device (tunnel okay, port forwarding okay), please see https://github.com/mobile-next/mobile-mcp/wiki/");+ }+return wda;}@@ -63,6 +79,18 @@ export class IosRobot implements Robot {return execFileSync(getGoIosPath(), ["--udid", this.deviceId, ...args], {}).toString();}+ public async getIosVersion(): Promise<string> {+ const output = await this.ios("info");+ const json = JSON.parse(output);+ return json.ProductVersion;+ }++ private async isTunnelRequired(): Promise<boolean> {+ const version = await this.getIosVersion();+ const args = version.split(".");+ return parseInt(args[0], 10) >= 17;+ }+public async getScreenSize(): Promise<Dimensions> {const wda = await this.wda();return await wda.getScreenSize();@@ -74,6 +102,8 @@ export class IosRobot implements Robot {}public async listApps(): Promise<InstalledApp[]> {+ await this.assertTunnelRunning();+const output = await this.ios("apps", "--all", "--list");return output.split("\n")@@ -87,10 +117,12 @@ export class IosRobot implements Robot {}public async launchApp(packageName: string): Promise<void> {+ await this.assertTunnelRunning();await this.ios("launch", packageName);}public async terminateApp(packageName: string): Promise<void> {+ await this.assertTunnelRunning();await this.ios("kill", packageName);}@@ -120,6 +152,7 @@ export class IosRobot implements Robot {}public async getScreenshot(): Promise<Buffer> {+ await this.assertTunnelRunning();const tmpFilename = join(tmpdir(), `screenshot-${randomBytes(8).toString("hex")}.png`);await this.ios("screenshot", "--output", tmpFilename);const buffer = readFileSync(tmpFilename);@@ -129,7 +162,23 @@ export class IosRobot implements Robot {}export class IosManager {++ public async isGoIosInstalled(): Promise<boolean> {+ try {+ const output = execFileSync(getGoIosPath(), ["--version"], { stdio: ["pipe", "pipe", "ignore"] }).toString();+ const json: VersionCommandOutput = JSON.parse(output);+ return json.version !== undefined && json.version.startsWith("v");+ } catch (error) {+ return false;+ }+ }+public async listDevices(): Promise<string[]> {+ if (!(await this.isGoIosInstalled())) {+ console.error("go-ios is not installed, no physical iOS devices can be detected");+ return [];+ }+const output = execFileSync(getGoIosPath(), ["list"]).toString();const json: ListCommandOutput = JSON.parse(output);return json.deviceList;diff --git a/src/robot.ts b/src/robot.tsindex 76f3528..fbcf62a 100644--- a/src/robot.ts+++ b/src/robot.ts@@ -24,6 +24,12 @@ export type SwipeDirection = "up" | "down" | "left" | "right";export type Button = "HOME" | "BACK" | "VOLUME_UP" | "VOLUME_DOWN" | "ENTER";+export class ActionableError extends Error {+ constructor(message: string) {+ super(message);+ }+}+export interface Robot {/*** Get the screen size of the device in pixels.diff --git a/src/server.ts b/src/server.tsindex 2f41fcc..11754dd 100644--- a/src/server.ts+++ b/src/server.ts@@ -5,7 +5,7 @@ import sharp from "sharp";import { error, trace } from "./logger";import { AndroidRobot, getConnectedDevices } from "./android";-import { Robot } from "./robot";+import { ActionableError, Robot } from "./robot";import { SimctlManager } from "./iphone-simulator";import { IosManager, IosRobot } from "./ios";@@ -35,11 +35,18 @@ export const createMcpServer = (): McpServer => {content: [{ type: "text", text: response }],};} catch (error: any) {- trace(`Tool '${description}' failed: ${error.message} stack: ${error.stack}`);- return {- content: [{ type: "text", text: `Error: ${error.message}` }],- isError: true,- };+ if (error instanceof ActionableError) {+ return {+ content: [{ type: "text", text: `${error.message}. Please fix the issue and try again.` }],+ };+ } else {+ // a real exception+ trace(`Tool '${description}' failed: ${error.message} stack: ${error.stack}`);+ return {+ content: [{ type: "text", text: `Error: ${error.message}` }],+ isError: true,+ };+ }}};@@ -51,7 +58,7 @@ export const createMcpServer = (): McpServer => {const requireRobot = () => {if (!robot) {- throw new Error("No device selected. Use the mobile_use_device tool to select a device.");+ throw new ActionableError("No device selected. Use the mobile_use_device tool to select a device.");}};@@ -194,7 +201,7 @@ export const createMcpServer = (): McpServer => {},async ({ button }) => {requireRobot();- robot!.pressButton(button);+ await robot!.pressButton(button);return `Pressed the button: ${button}`;});@@ -207,7 +214,7 @@ export const createMcpServer = (): McpServer => {},async ({ url }) => {requireRobot();- robot!.openUrl(url);+ await robot!.openUrl(url);return `Opened URL: ${url}`;});@@ -220,7 +227,7 @@ export const createMcpServer = (): McpServer => {},async ({ direction }) => {requireRobot();- robot!.swipe(direction);+ await robot!.swipe(direction);return `Swiped ${direction} on screen`;});diff --git a/src/webdriver-agent.ts b/src/webdriver-agent.tsindex ac1d1ab..ea4b792 100644--- a/src/webdriver-agent.ts+++ b/src/webdriver-agent.ts@@ -1,4 +1,4 @@-import { Dimensions, SwipeDirection } from "./robot";+import { Dimensions, ActionableError, SwipeDirection } from "./robot";export interface SourceTreeElement {type: string;@@ -36,6 +36,17 @@ export class WebDriverAgent {constructor(private readonly host: string, private readonly port: number) {}+ public async isRunning(): Promise<boolean> {+ const url = `http://${this.host}:${this.port}/status`;+ try {+ const response = await fetch(url);+ return response.status === 200;+ } catch (error) {+ console.error(`Failed to connect to WebDriverAgent: ${error}`);+ return false;+ }+ }+public async createSession(): Promise<string> {const url = `http://${this.host}:${this.port}/session`;const response = await fetch(url, {@@ -103,7 +114,7 @@ export class WebDriverAgent {// Type assertion to check if button is a key of _mapif (!(button in _map)) {- throw new Error(`Button "${button}" is not supported`);+ throw new ActionableError(`Button "${button}" is not supported`);}await this.withinSession(async sessionUrl => {