Skip to content

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.

fix: improve tapping on x,y coordinates with respect to scale (#26)

Gil Megidish7baf3e4ce0fd
diff --git a/src/android.ts b/src/android.ts
index 4da5cef..2898bf4 100644
--- a/src/android.ts
+++ b/src/android.ts
@@ -3,7 +3,14 @@ import { execFileSync } from "child_process";
import * as xml from "fast-xml-parser";
-import { ActionableError, Bounds, Button, Dimensions, ElementCoordinates, InstalledApp, Robot, SwipeDirection } from "./robot";
+import { ActionableError, Button, Dimensions, InstalledApp, Robot, ScreenSize, SwipeDirection } from "./robot";
+
+interface UiAutomatorBounds {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
interface UiAutomatorXmlNode {
node: UiAutomatorXmlNode[];
@@ -50,7 +57,7 @@ export class AndroidRobot implements Robot {
});
}
- public async getScreenSize(): Promise<Dimensions> {
+ public async getScreenSize(): Promise<ScreenSize> {
const screenSize = this.adb("shell", "wm", "size")
.toString()
.split(" ")
@@ -60,8 +67,9 @@ export class AndroidRobot implements Robot {
throw new Error("Failed to get screen size");
}
+ const scale = 1;
const [width, height] = screenSize.split("x").map(Number);
- return { width, height };
+ return { width, height, scale };
}
public async listApps(): Promise<InstalledApp[]> {
@@ -114,27 +122,13 @@ export class AndroidRobot implements Robot {
private collectElements(node: UiAutomatorXmlNode, screenSize: Dimensions): any[] {
const elements: any[] = [];
- const getCoordinates = (element: UiAutomatorXmlNode): Bounds => {
+ const getCoordinates = (element: UiAutomatorXmlNode): UiAutomatorBounds => {
const bounds = String(element.bounds);
const [, left, top, right, bottom] = bounds.match(/^\[(\d+),(\d+)\]\[(\d+),(\d+)\]$/)?.map(Number) || [];
return { left, top, right, bottom };
};
- const getCenter = (coordinates: Bounds): ElementCoordinates => {
- return {
- x: Math.floor((coordinates.left + coordinates.right) / 2),
- y: Math.floor((coordinates.top + coordinates.bottom) / 2),
- };
- };
-
- const normalizeCoordinates = (coordinates: ElementCoordinates, screenSize: Dimensions): ElementCoordinates => {
- return {
- x: Number((coordinates.x / screenSize.width).toFixed(3)),
- y: Number((coordinates.y / screenSize.height).toFixed(3)),
- };
- };
-
if (node.node) {
if (Array.isArray(node.node)) {
for (const childNode of node.node) {
@@ -148,14 +142,14 @@ export class AndroidRobot implements Robot {
if (node.text) {
elements.push({
"text": node.text,
- "coordinates": normalizeCoordinates(getCenter(getCoordinates(node)), screenSize),
+ "coordinates": getCoordinates(node),
});
}
if (node["content-desc"]) {
elements.push({
"text": node["content-desc"],
- "coordinates": normalizeCoordinates(getCenter(getCoordinates(node)), screenSize),
+ "coordinates": getCoordinates(node),
});
}
diff --git a/src/ios.ts b/src/ios.ts
index 67537a0..5df4105 100644
--- a/src/ios.ts
+++ b/src/ios.ts
@@ -1,12 +1,12 @@
+import path from "path";
import { tmpdir } from "os";
-import { join } from "path";
import { randomBytes } from "crypto";
import { readFileSync, unlinkSync } from "fs";
import { execFileSync } from "child_process";
import { Socket } from "net";
import { ScreenElement, WebDriverAgent } from "./webdriver-agent";
-import { ActionableError, Button, Dimensions, InstalledApp, Robot, SwipeDirection } from "./robot";
+import { ActionableError, Button, InstalledApp, Robot, ScreenSize, SwipeDirection } from "./robot";
const WDA_PORT = 8100;
const IOS_TUNNEL_PORT = 60105;
@@ -96,7 +96,7 @@ export class IosRobot implements Robot {
return parseInt(args[0], 10) >= 17;
}
- public async getScreenSize(): Promise<Dimensions> {
+ public async getScreenSize(): Promise<ScreenSize> {
const wda = await this.wda();
return await wda.getScreenSize();
}
@@ -158,7 +158,7 @@ export class IosRobot implements Robot {
public async getScreenshot(): Promise<Buffer> {
await this.assertTunnelRunning();
- const tmpFilename = join(tmpdir(), `screenshot-${randomBytes(8).toString("hex")}.png`);
+ const tmpFilename = path.join(tmpdir(), `screenshot-${randomBytes(8).toString("hex")}.png`);
await this.ios("screenshot", "--output", tmpFilename);
const buffer = readFileSync(tmpFilename);
unlinkSync(tmpFilename);
@@ -170,9 +170,9 @@ export class IosManager {
public async isGoIosInstalled(): Promise<boolean> {
try {
- const output = execFileSync(getGoIosPath(), ["--version"], { stdio: ["pipe", "pipe", "ignore"] }).toString();
+ const output = execFileSync(getGoIosPath(), ["version"], { stdio: ["pipe", "pipe", "ignore"] }).toString();
const json: VersionCommandOutput = JSON.parse(output);
- return json.version !== undefined && json.version.startsWith("v");
+ return json.version !== undefined && (json.version.startsWith("v") || json.version === "local-build");
} catch (error) {
return false;
}
diff --git a/src/iphone-simulator.ts b/src/iphone-simulator.ts
index 7f6fa9f..f051524 100644
--- a/src/iphone-simulator.ts
+++ b/src/iphone-simulator.ts
@@ -1,7 +1,7 @@
-import { execFileSync, execSync } from "child_process";
+import { execFileSync } from "child_process";
import { WebDriverAgent } from "./webdriver-agent";
-import { Button, Dimensions, InstalledApp, Robot, SwipeDirection } from "./robot";
+import { Button, InstalledApp, Robot, ScreenSize, SwipeDirection } from "./robot";
export interface Simulator {
name: string;
@@ -9,6 +9,17 @@ export interface Simulator {
state: string;
}
+interface ListDevicesResponse {
+ devices: {
+ [key: string]: Array<{
+ state: string;
+ name: string;
+ isAvailable: boolean;
+ udid: string;
+ }>,
+ },
+}
+
interface AppInfo {
ApplicationType: string;
Bundle: string;
@@ -110,7 +121,7 @@ export class Simctl implements Robot {
}));
}
- public async getScreenSize(): Promise<Dimensions> {
+ public async getScreenSize(): Promise<ScreenSize> {
return this.wda.getScreenSize();
}
@@ -137,30 +148,18 @@ export class Simctl implements Robot {
export class SimctlManager {
- private parseSimulator(line: string): Simulator | null {
- // extract device name and UUID from the line
- const match = line.match(/(.*?)\s+\(([\w-]+)\)\s+\((\w+)\)/);
- if (!match) {
- return null;
- }
-
- const deviceName = match[1].trim();
- const deviceUuid = match[2];
- const deviceState = match[3];
-
- return {
- name: deviceName,
- uuid: deviceUuid,
- state: deviceState,
- };
- }
-
public listSimulators(): Simulator[] {
- return execSync(`xcrun simctl list devices`)
- .toString()
- .split("\n")
- .map(line => this.parseSimulator(line))
- .filter(simulator => simulator !== null);
+ const text = execFileSync("xcrun", ["simctl", "list", "devices", "-j"]).toString();
+ const json: ListDevicesResponse = JSON.parse(text);
+ return Object.values(json.devices).flatMap(device => {
+ return device.map(d => {
+ return {
+ name: d.name,
+ uuid: d.udid,
+ state: d.state,
+ };
+ });
+ });
}
public listBootedSimulators(): Simulator[] {
diff --git a/src/robot.ts b/src/robot.ts
index fbcf62a..c07589c 100644
--- a/src/robot.ts
+++ b/src/robot.ts
@@ -1,9 +1,3 @@
-export interface Bounds {
- left: number;
- top: number;
- right: number;
- bottom: number;
-}
export interface ElementCoordinates {
x: number,
@@ -15,6 +9,10 @@ export interface Dimensions {
height: number;
}
+export interface ScreenSize extends Dimensions {
+ scale: number;
+}
+
export interface InstalledApp {
packageName: string;
appName: string;
@@ -34,7 +32,7 @@ export interface Robot {
/**
* Get the screen size of the device in pixels.
*/
- getScreenSize(): Promise<Dimensions>;
+ getScreenSize(): Promise<ScreenSize>;
/**
* Swipe in a direction.
diff --git a/src/server.ts b/src/server.ts
index 11754dd..a6da7fe 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -152,15 +152,12 @@ export const createMcpServer = (): McpServer => {
"mobile_click_on_screen_at_coordinates",
"Click on the screen at given x,y coordinates",
{
- x: z.number().describe("The x coordinate to click between 0 and 1"),
- y: z.number().describe("The y coordinate to click between 0 and 1"),
+ x: z.number().describe("The x coordinate to click on the screen, in pixels"),
+ y: z.number().describe("The y coordinate to click on the screen, in pixels"),
},
async ({ x, y }) => {
requireRobot();
- const screenSize = await robot!.getScreenSize();
- const x0 = Math.floor(screenSize.width * x);
- const y0 = Math.floor(screenSize.height * y);
- await robot!.tap(x0, y0);
+ await robot!.tap(x, y);
return `Clicked on screen at coordinates: ${x}, ${y}`;
}
);
@@ -172,20 +169,15 @@ export const createMcpServer = (): McpServer => {
},
async ({}) => {
requireRobot();
- const screenSize = await robot!.getScreenSize();
const elements = await robot!.getElementsOnScreen();
const result = elements.map(element => {
- const x0 = element.rect.x0 / screenSize.width;
- const y0 = element.rect.y0 / screenSize.height;
- const x1 = element.rect.x1 / screenSize.width;
- const y1 = element.rect.y1 / screenSize.height;
+ const x = Number((element.rect.x0 + element.rect.x1) / 2).toFixed(3);
+ const y = Number((element.rect.y0 + element.rect.y1) / 2).toFixed(3);
+
return {
text: element.label,
- coordinates: {
- x: Number((x0 + x1) / 2).toFixed(3),
- y: Number((y0 + y1) / 2).toFixed(3),
- }
+ coordinates: { x, y }
};
});
diff --git a/src/webdriver-agent.ts b/src/webdriver-agent.ts
index ea4b792..5900789 100644
--- a/src/webdriver-agent.ts
+++ b/src/webdriver-agent.ts
@@ -1,16 +1,19 @@
-import { Dimensions, ActionableError, SwipeDirection } from "./robot";
+import { ActionableError, SwipeDirection, ScreenSize } from "./robot";
+
+export interface SourceTreeElementRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
export interface SourceTreeElement {
type: string;
label?: string;
name?: string;
+ value?: string;
rawIdentifier?: string;
- rect: {
- x: number;
- y: number;
- width: number;
- height: number;
- };
+ rect: SourceTreeElementRect;
children?: Array<SourceTreeElement>;
}
@@ -23,6 +26,7 @@ export interface ScreenElement {
type: string;
label?: string;
name?: string;
+ value?: string;
rect: {
x0: number;
y0: number;
@@ -75,7 +79,7 @@ export class WebDriverAgent {
return result;
}
- public async getScreenSize(): Promise<Dimensions> {
+ public async getScreenSize(): Promise<ScreenSize> {
return this.withinSession(async sessionUrl => {
const url = `${sessionUrl}/wda/screen`;
const response = await fetch(url);
@@ -83,6 +87,7 @@ export class WebDriverAgent {
return {
width: json.value.screenSize.width * json.value.scale,
height: json.value.screenSize.height * json.value.scale,
+ scale: json.value.scale || 1,
};
});
}
@@ -160,23 +165,31 @@ export class WebDriverAgent {
});
}
- private filterSourceElements(source: SourceTreeElement): Array<ScreenElement> {
+ private isVisible(rect: SourceTreeElementRect): boolean {
+ return rect.x >= 0 && rect.y >= 0;
+ }
+ private filterSourceElements(source: SourceTreeElement): Array<ScreenElement> {
const output: ScreenElement[] = [];
- if (["TextField", "Button", "Switch", "Icon", "SearchField"].includes(source.type)) {
- if (source.label !== null || source.name !== null) {
- output.push({
- type: source.type,
- label: source.label,
- name: source.name,
- rect: {
- x0: source.rect.x,
- y0: source.rect.y,
- x1: source.rect.x + source.rect.width,
- y1: source.rect.y + source.rect.height,
- },
- });
+ const acceptedTypes = ["TextField", "Button", "Switch", "Icon", "SearchField"];
+
+ if (acceptedTypes.includes(source.type)) {
+ if (this.isVisible(source.rect)) {
+ if (source.label !== null || source.name !== null) {
+ output.push({
+ type: source.type,
+ label: source.label,
+ name: source.name,
+ value: source.value,
+ rect: {
+ x0: source.rect.x,
+ y0: source.rect.y,
+ x1: source.rect.x + source.rect.width,
+ y1: source.rect.y + source.rect.height,
+ },
+ });
+ }
}
}
diff --git a/test/iphone-simulator.ts b/test/iphone-simulator.ts
index 110cc9b..2b1c6c2 100644
--- a/test/iphone-simulator.ts
+++ b/test/iphone-simulator.ts
@@ -81,8 +81,8 @@ describe("iphone-simulator", () => {
const image = sharp(screenshot);
const metadata = await image.metadata();
const screenSize = await simctl.getScreenSize();
- assert.equal(metadata.width, screenSize.width);
- assert.equal(metadata.height, screenSize.height);
+ assert.equal(metadata.width, screenSize.width * screenSize.scale);
+ assert.equal(metadata.height, screenSize.height * screenSize.scale);
});
it("should be able to open url", async function() {