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: correct tool descriptions and accept ref on double-tap and long-press (#471)
Mobile Kevin Bot!2c6413c84ddc
diff --git a/README.md b/README.mdindex 3c42117..a785e76 100644--- a/README.md+++ b/README.md@@ -96,15 +96,15 @@ How we help to scale mobile automation:- **`mobile_launch_app`** - Launch an app using its package name- **`mobile_terminate_app`** - Stop and terminate a running app- **`mobile_install_app`** - Install an app from file (.apk, .ipa, .app, .zip)-- **`mobile_uninstall_app`** - Uninstall an app using bundle ID or package name+- **`mobile_uninstall_app`** - Uninstall an app by its package name or bundle ID### Screen Interaction- **`mobile_take_screenshot`** - Take a screenshot to understand what's on screen- **`mobile_save_screenshot`** - Save a screenshot to a file- **`mobile_list_elements_on_screen`** - List UI elements with their coordinates and properties-- **`mobile_click_on_screen_at_coordinates`** - Click at specific x,y coordinates-- **`mobile_double_tap_on_screen`** - Double-tap at specific coordinates-- **`mobile_long_press_on_screen_at_coordinates`** - Long press at specific coordinates+- **`mobile_click_on_screen_at_coordinates`** - Click at specific x,y coordinates or on an element by its ref+- **`mobile_double_tap_on_screen`** - Double-tap at specific coordinates or on an element by its ref+- **`mobile_long_press_on_screen_at_coordinates`** - Long press at specific coordinates or on an element by its ref- **`mobile_swipe_on_screen`** - Swipe in any direction (up, down, left, right)- **`mobile_start_screen_recording`** - Start recording the device screen to a video file- **`mobile_stop_screen_recording`** - Stop the active screen recording and save the video@@ -112,7 +112,7 @@ How we help to scale mobile automation:### Input & Navigation- **`mobile_type_keys`** - Type text into focused elements with optional submit- **`mobile_press_button`** - Press device buttons (HOME, BACK, VOLUME_UP/DOWN, ENTER, etc.)-- **`mobile_open_url`** - Open URLs in the device browser+- **`mobile_open_url`** - Open http/https URLs in the device browser### Logs & Crash Reports- **`mobile_get_device_logs`** - Collect live device logs (logcat on Android, unified log on iOS), optionally saved to a filediff --git a/src/mobile-device.ts b/src/mobile-device.tsindex 55f5215..a73c316 100644--- a/src/mobile-device.ts+++ b/src/mobile-device.ts@@ -271,10 +271,26 @@ export class MobileDevice implements Robot {await this.tap(x, y);}+ public async doubleTapByRef(ref: string): Promise<void> {+ // resolve the ref once: two "io tap @ref" calls would each dump the ui again and miss the double-tap window+ const elements = await this.getElementsOnScreen();+ const element = elements.find(candidate => candidate.ref === ref);+ if (!element) {+ throw new ActionableError(`Element ${ref} was not found on the current screen. Call mobile_list_elements_on_screen again to get fresh refs`);+ }++ const { x, y, width, height } = element.rect;+ await this.doubleTap(x + width / 2, y + height / 2);+ }+public async longPress(x: number, y: number, duration: number): Promise<void> {this.runCommand(["io", "longpress", `${Math.round(x)},${Math.round(y)}`, "--duration", `${duration}`]);}+ public async longPressByRef(ref: string, duration: number): Promise<void> {+ this.runCommand(["io", "longpress", ref, "--duration", `${duration}`]);+ }+public async getElementsOnScreen(): Promise<ScreenElement[]> {const response = this.runJsonCommand<DumpUIResponse>(["dump", "ui"]);const elements = response.data?.elements;diff --git a/src/robot.ts b/src/robot.tsindex d455719..30f98b4 100644--- a/src/robot.ts+++ b/src/robot.ts@@ -178,6 +178,11 @@ export interface Robot {*/doubleTap(x: number, y: number): Promise<void>;+ /**+ * Double tap on the center of an element by its ref from the latest getElementsOnScreen (e.g. "@e5"). mobilecli only.+ */+ doubleTapByRef?(ref: string): Promise<void>;+/*** Long press on a specific coordinate on the screen.* @param x - The x coordinate to long press@@ -186,6 +191,11 @@ export interface Robot {*/longPress(x: number, y: number, duration: number): Promise<void>;+ /**+ * Long press on the center of an element by its ref from the latest getElementsOnScreen (e.g. "@e5"). mobilecli only.+ */+ longPressByRef?(ref: string, duration: number): Promise<void>;+/*** Get all elements on the screen. Works only on native apps (not webviews). Will* return a filtered list of elements that make sense to interact with.diff --git a/src/server.ts b/src/server.tsindex 5b15fcb..ec88455 100644--- a/src/server.ts+++ b/src/server.ts@@ -96,8 +96,10 @@ from the hierarchy, or to judge visual appearance.Each call is a device round-trip. Group known sequences (tap, type, tap) intomobile_batch_commands instead of issuing them one at a time.-Prefer mobile_open_url or mobile_launch_app over navigating through the UI to-reach a screen.`;+Prefer mobile_launch_app to open an app, and mobile_open_url to open a web page,+over navigating through the UI. mobile_open_url only accepts http:// and+https:// URLs unless the server was started with MOBILEMCP_ALLOW_UNSAFE_URLS=1,+so do not rely on it for app deep links.`;export const createMcpServer = (): McpServer => {@@ -568,7 +570,7 @@ export const createMcpServer = (): McpServer => {tool("mobile_launch_app","Launch App",- "Launch an app on mobile device. Use this to open a specific app. You can find the package name of the app by calling list_apps_on_device.",+ "Launch an app on mobile device. Use this to open a specific app. You can find the package name of the app by calling mobile_list_apps.",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),packageName: z.string().describe("The package name of the app to launch"),@@ -625,13 +627,13 @@ export const createMcpServer = (): McpServer => {"Uninstall an app from mobile device",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),- bundle_id: z.string().describe("Bundle identifier (iOS) or package name (Android) of the app to be uninstalled"),+ packageName: z.string().describe("The package name of the app to uninstall"),},{ readOnlyHint: false, destructiveHint: true, openWorldHint: false },- async ({ device, bundle_id }) => {+ async ({ device, packageName }) => {const robot = getRobotFromDevice(device);- await robot.uninstallApp(bundle_id);- return `Uninstalled app ${bundle_id}`;+ await robot.uninstallApp(packageName);+ return `Uninstalled app ${packageName}`;});@@ -684,16 +686,30 @@ export const createMcpServer = (): McpServer => {tool("mobile_double_tap_on_screen","Double Tap Screen",- "Double-tap on the screen at given x,y coordinates.",+ "Double-tap on the screen, either at x,y coordinates or on an element by its ref (e.g. \"@e5\") from the latest mobile_list_elements_on_screen result. Prefer ref when the element is listed.",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),- x: z.coerce.number().min(0).describe("The x coordinate to double-tap, in pixels"),- y: z.coerce.number().min(0).describe("The y coordinate to double-tap, in pixels"),+ x: z.coerce.number().min(0).optional().describe("The x coordinate to double-tap, in pixels. Required unless ref is given"),+ y: z.coerce.number().min(0).optional().describe("The y coordinate to double-tap, in pixels. Required unless ref is given"),+ ref: z.string().optional().describe("Element ref from mobile_list_elements_on_screen, e.g. \"@e5\". Takes precedence over x,y"),},{ readOnlyHint: false, destructiveHint: false, openWorldHint: true },- async ({ device, x, y }) => {+ async ({ device, x, y, ref }) => {const robot = getRobotFromDevice(device);- await robot!.doubleTap(x, y);+ if (ref !== undefined) {+ if (!robot.doubleTapByRef) {+ throw new ActionableError("Double-tapping by ref is not supported in legacy robot mode");+ }++ await robot.doubleTapByRef(ref);+ return `Double-tapped on element ${ref}`;+ }++ if (x === undefined || y === undefined) {+ throw new ActionableError("Either ref or both x and y must be provided");+ }++ await robot.doubleTap(x, y);return `Double-tapped on screen at coordinates: ${x}, ${y}`;});@@ -701,17 +717,31 @@ export const createMcpServer = (): McpServer => {tool("mobile_long_press_on_screen_at_coordinates","Long Press Screen",- "Long press on the screen at given x,y coordinates. If long pressing on an element, use the mobile_list_elements_on_screen tool to find the coordinates.",+ "Long press on the screen, either at x,y coordinates or on an element by its ref (e.g. \"@e5\") from the latest mobile_list_elements_on_screen result. Prefer ref when the element is listed.",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),- x: z.coerce.number().min(0).describe("The x coordinate to long press on the screen, in pixels"),- y: z.coerce.number().min(0).describe("The y coordinate to long press on the screen, in pixels"),+ x: z.coerce.number().min(0).optional().describe("The x coordinate to long press on the screen, in pixels. Required unless ref is given"),+ y: z.coerce.number().min(0).optional().describe("The y coordinate to long press on the screen, in pixels. Required unless ref is given"),+ ref: z.string().optional().describe("Element ref from mobile_list_elements_on_screen, e.g. \"@e5\". Takes precedence over x,y"),duration: z.coerce.number().min(1).max(10000).optional().describe("Duration of the long press in milliseconds. Defaults to 500ms."),},{ readOnlyHint: false, destructiveHint: false, openWorldHint: true },- async ({ device, x, y, duration }) => {+ async ({ device, x, y, ref, duration }) => {const robot = getRobotFromDevice(device);const pressDuration = duration ?? 500;+ if (ref !== undefined) {+ if (!robot.longPressByRef) {+ throw new ActionableError("Long pressing by ref is not supported in legacy robot mode");+ }++ await robot.longPressByRef(ref, pressDuration);+ return `Long pressed on element ${ref} for ${pressDuration}ms`;+ }++ if (x === undefined || y === undefined) {+ throw new ActionableError("Either ref or both x and y must be provided");+ }+await robot.longPress(x, y, pressDuration);return `Long pressed on screen at coordinates: ${x}, ${y} for ${pressDuration}ms`;}@@ -720,7 +750,7 @@ export const createMcpServer = (): McpServer => {tool("mobile_list_elements_on_screen","List Screen Elements",- "List elements on screen with their ref, coordinates, and display text or accessibility label. Use the ref with mobile_click_on_screen_at_coordinates. Refs and coordinates stay valid as long as the screen does not change; re-list only after navigation or a layout change.",+ "List elements on screen with their ref, coordinates, and display text or accessibility label. Use the ref with mobile_click_on_screen_at_coordinates, mobile_double_tap_on_screen or mobile_long_press_on_screen_at_coordinates. Refs and coordinates stay valid as long as the screen does not change; re-list only after navigation or a layout change.",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),format: z.enum(["text", "json"]).optional().describe("Output format. \"text\" (default) is one compact line per element, \"json\" is a json array"),@@ -752,10 +782,10 @@ export const createMcpServer = (): McpServer => {tool("mobile_open_url","Open URL",- "Open a URL in browser on device",+ "Open an http:// or https:// URL in the browser on device. Other URL schemes, such as app deep links, are rejected unless the server was started with MOBILEMCP_ALLOW_UNSAFE_URLS=1.",{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),- url: z.string().describe("The URL to open"),+ url: z.string().describe("The URL to open, starting with http:// or https://"),},{ readOnlyHint: false, destructiveHint: false, openWorldHint: true },async ({ device, url }) => {@@ -805,7 +835,7 @@ export const createMcpServer = (): McpServer => {{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),text: z.string().describe("The text to type"),- submit: z.boolean().describe("Whether to submit the text. If true, the text will be submitted as if the user pressed the enter key."),+ submit: z.boolean().optional().describe("Whether to submit the text. If true, the text will be submitted as if the user pressed the enter key. Defaults to false"),},{ readOnlyHint: false, destructiveHint: false, openWorldHint: true },async ({ device, text, submit }) => {@@ -1205,14 +1235,17 @@ export const createMcpServer = (): McpServer => {});+ // mobile_take_screenshot returns an image, which the text result of a batch cannot carry+ const batchableToolNames = [...toolCallbacks.keys()].filter(name => name !== "mobile_take_screenshot");+tool("mobile_batch_commands","Batch Commands",- "Run multiple tools in sequence in a single call, e.g. click, type, click, type. Use this to fill forms or perform multi-step flows without round-trips. The device argument is applied to every step unless a step provides its own.",+ `Run multiple tools in sequence in a single call, e.g. click, type, click, type. Use this to fill forms or perform multi-step flows without round-trips. The device argument is applied to every step unless a step provides its own. Tools allowed as steps: ${batchableToolNames.join(", ")}.`,{device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),steps: z.array(z.object({- name: z.string().describe("Tool name, e.g. mobile_click_on_screen_at_coordinates"),+ name: z.string().describe("Name of a tool allowed as a step, e.g. mobile_click_on_screen_at_coordinates"),arguments: z.record(z.string(), z.any()).describe("Arguments for the tool, same as calling it directly"),})).min(1).describe("Tools to run, in order"),stopOnError: z.boolean().optional().describe("Stop at the first failing step. Defaults to true"),diff --git a/test/mobile-device.test.ts b/test/mobile-device.test.tsindex d0232ef..17fc7c4 100644--- a/test/mobile-device.test.ts+++ b/test/mobile-device.test.ts@@ -59,6 +59,39 @@ test.describe("MobileDevice", () => {});});+ test.describe("gestures by element ref", () => {++ test("longPressByRef should pass the element ref to mobilecli io longpress", async () => {+ const { device, calls } = createMockMobileDevice("");+ await device.longPressByRef("@e5", 800);++ expect(calls[0]).toEqual(["io", "longpress", "@e5", "--duration", "800", "--device", "test-device"]);+ });++ test("doubleTapByRef should resolve the ref once and tap the element center twice", async () => {+ const dump = { status: "ok", data: { elements: [+ { ref: "@e1", type: "Button", label: "+", rect: { x: 100, y: 200, width: 40, height: 60 } },+ ] } };+ const { device, calls } = createMockMobileDevice(JSON.stringify(dump));+ await device.doubleTapByRef("@e1");++ expect(calls).toEqual([+ ["dump", "ui", "--device", "test-device"],+ ["io", "tap", "120,230", "--device", "test-device"],+ ["io", "tap", "120,230", "--device", "test-device"],+ ]);+ });++ test("doubleTapByRef should raise an actionable error for a ref that is not on screen", async () => {+ const { device, calls } = createMockMobileDevice(JSON.stringify({ status: "ok", data: { elements: [] } }));+ const pending = device.doubleTapByRef("@e9");++ await expect(pending).rejects.toThrow(ActionableError);+ await expect(pending).rejects.toThrow(/@e9 was not found on the current screen/);+ expect(calls).toEqual([["dump", "ui", "--device", "test-device"]]);+ });+ });+test.describe("element state", () => {test("getElementsOnScreen should keep ref, selected, checked and enabled from dump ui", async () => {diff --git a/test/server-tool-descriptions.test.ts b/test/server-tool-descriptions.test.tsnew file mode 100644index 0000000..d566c98--- /dev/null+++ b/test/server-tool-descriptions.test.ts@@ -0,0 +1,104 @@+import { expect, test } from "@playwright/test";+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";+import { createMcpServer } from "../src/server";++interface ToolParameter {+ description?: string;+}++interface ToolDefinition {+ name: string;+ description?: string;+ inputSchema: {+ properties?: Record<string, ToolParameter>;+ required?: string[];+ };+}++const TOOLS_THAT_CANNOT_RUN_IN_A_BATCH = ["mobile_batch_commands", "mobile_take_screenshot"];++const listToolDefinitions = async (): Promise<ToolDefinition[]> => {+ process.env.MOBILEMCP_DISABLE_TELEMETRY = "1";+ const server = createMcpServer();+ const client = new Client({ name: "tool-descriptions-test", version: "1.0.0" });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ const result = await client.listTools();+ return result.tools as ToolDefinition[];+};++const findTool = (tools: ToolDefinition[], name: string): ToolDefinition => {+ const tool = tools.find(candidate => candidate.name === name);+ if (!tool) {+ throw new Error(`Tool ${name} is not registered`);+ }++ return tool;+};++const parameterNamesOf = (tool: ToolDefinition): string[] => Object.keys(tool.inputSchema.properties ?? {});++const requiredParametersOf = (tool: ToolDefinition): string[] => tool.inputSchema.required ?? [];++const everythingWrittenAbout = (tool: ToolDefinition): string => {+ const parameterDescriptions = Object.values(tool.inputSchema.properties ?? {}).map(parameter => parameter.description ?? "");+ return [tool.description ?? "", ...parameterDescriptions].join("\n");+};++const toolNamesMentionedIn = (text: string): string[] => text.match(/mobile_[a-z_]+/g) ?? [];++test("only mentions tools that exist", async () => {+ const tools = await listToolDefinitions();+ const registeredNames = tools.map(tool => tool.name);++ for (const tool of tools) {+ for (const mentionedName of toolNamesMentionedIn(everythingWrittenAbout(tool))) {+ expect(registeredNames, `${tool.name} mentions ${mentionedName}`).toContain(mentionedName);+ }+ }+});++test("names the app with packageName in every app tool", async () => {+ const tools = await listToolDefinitions();++ for (const name of ["mobile_launch_app", "mobile_terminate_app", "mobile_uninstall_app"]) {+ expect(requiredParametersOf(findTool(tools, name)), name).toEqual(["device", "packageName"]);+ }+});++test("lets mobile_type_keys be called without submit", async () => {+ const tools = await listToolDefinitions();+ const typeKeys = findTool(tools, "mobile_type_keys");++ expect(parameterNamesOf(typeKeys)).toContain("submit");+ expect(requiredParametersOf(typeKeys)).toEqual(["device", "text"]);+ expect(typeKeys.inputSchema.properties!.submit.description).toContain("Defaults to false");+});++test("lets every tap gesture target an element ref instead of coordinates", async () => {+ const tools = await listToolDefinitions();++ for (const name of ["mobile_click_on_screen_at_coordinates", "mobile_double_tap_on_screen", "mobile_long_press_on_screen_at_coordinates"]) {+ const gesture = findTool(tools, name);+ expect(parameterNamesOf(gesture), name).toContain("ref");+ expect(requiredParametersOf(gesture), name).toEqual(["device"]);+ expect(gesture.description, name).toContain("by its ref");+ }+});++test("tells which tools mobile_batch_commands can run", async () => {+ const tools = await listToolDefinitions();+ const batch = findTool(tools, "mobile_batch_commands");+ const batchableNames = tools.map(tool => tool.name).filter(name => !TOOLS_THAT_CANNOT_RUN_IN_A_BATCH.includes(name));++ expect(toolNamesMentionedIn(batch.description ?? "").sort()).toEqual(batchableNames.sort());+});++test("says mobile_open_url only opens http and https urls by default", async () => {+ const tools = await listToolDefinitions();+ const openUrl = findTool(tools, "mobile_open_url");++ expect(openUrl.description).toContain("http:// or https://");+ expect(openUrl.description).toContain("MOBILEMCP_ALLOW_UNSAFE_URLS=1");+});