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.

chore: lint fixes and indentation

gmegidishba76f68275ad
diff --git a/screen.png b/screen.png
deleted file mode 100644
index 36ae23e..0000000
Binary files a/screen.png and /dev/null differ
diff --git a/src/android.ts b/src/android.ts
index 4fcffa0..94d6ff7 100644
--- a/src/android.ts
+++ b/src/android.ts
@@ -1,4 +1,4 @@
-import { exec, execSync } from "child_process";
+import { execSync } from "child_process";
import * as xml from "fast-xml-parser";
import { readFileSync, unlinkSync } from "fs";
@@ -12,14 +12,14 @@ interface Bounds {
interface ElementCoordinates {
x: number,
y: number;
-};
+}
export const getConnectedDevices = (): string[] => {
return execSync(`adb devices`)
.toString()
.split("\n")
.filter(line => !line.startsWith("List of devices attached"))
- .filter(line => line.trim() != "");
+ .filter(line => line.trim() !== "");
};
export const resolveLaunchableActivities = (packageName: string): string[] => {
@@ -29,10 +29,10 @@ export const resolveLaunchableActivities = (packageName: string): string[] => {
.map(line => line.trim())
.filter(line => line.startsWith("name="))
.map(line => line.substring("name=".length));
-}
+};
export const getScreenSize = (): [number, number] => {
- const screenSize = execSync('adb shell wm size')
+ const screenSize = execSync("adb shell wm size")
.toString()
.split(" ")
.pop();
@@ -43,7 +43,7 @@ export const getScreenSize = (): [number, number] => {
const [width, height] = screenSize.split("x").map(Number);
return [width, height];
-}
+};
export const getElementCoordinates = (text: string): ElementCoordinates => {
const dump = execSync(`adb exec-out uiautomator dump /dev/tty`);
@@ -78,9 +78,8 @@ export const getElementCoordinates = (text: string): ElementCoordinates => {
return result;
}
}
- }
- // If node.node is an object, recurse on it
- else {
+ } else {
+ // if node.node is an object, recurse on it
const result = findTextElement(node.node);
if (result) {
return result;
@@ -100,32 +99,32 @@ export const getElementCoordinates = (text: string): ElementCoordinates => {
const getCoordinates = (element: any): Bounds => {
const bounds = String(element.bounds);
- const [_, left, top, right, bottom] = bounds.match(/^\[(\d+),(\d+)\]\[(\d+),(\d+)\]$/)?.map(Number) || [];
+
+ 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),
};
- }
+ };
return getCenter(getCoordinates(textElement));
-
/*
const jsonOutput = JSON.stringify(textElement, null, 2);
console.dir(jsonOutput.toString());
console.dir(getCoordinates(textElement));
console.dir(getCenter(getCoordinates(textElement)));
*/
-}
+};
export const swipe = (direction: "up" | "down" | "left" | "right") => {
const screenSize = getScreenSize();
const centerX = screenSize[0] >> 1;
- const centerY = screenSize[1] >> 1;
+ // const centerY = screenSize[1] >> 1;
let x0, y0, x1, y1: number;
@@ -145,7 +144,7 @@ export const swipe = (direction: "up" | "down" | "left" | "right") => {
}
execSync(`adb shell input swipe ${x0} ${y0} ${x1} ${y1} 1000`);
-}
+};
export const takeScreenshot = async (): Promise<Buffer> => {
const randomFilename = `screenshot-${Date.now()}.png`;
@@ -162,4 +161,4 @@ export const takeScreenshot = async (): Promise<Buffer> => {
const screenshot = readFileSync(localFilename);
unlinkSync(localFilename);
return screenshot;
-}
+};
diff --git a/src/index.ts b/src/index.ts
index b03c1b3..d98c45e 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -11,7 +11,7 @@ async function main() {
error("Appium MCP Server running on stdio");
}
-main().catch((err) => {
+main().catch(err => {
console.error("Fatal error in main():", err);
error("Fatal error in main(): " + JSON.stringify(err.stack));
process.exit(1);
diff --git a/src/iphone-simulator.ts b/src/iphone-simulator.ts
index 67a238d..70b1f45 100644
--- a/src/iphone-simulator.ts
+++ b/src/iphone-simulator.ts
@@ -3,41 +3,41 @@ import { execSync } from "child_process";
export interface Simulator {
name: string;
uuid: string;
-};
+}
export const getConnectedDevices = (): Simulator[] => {
- return execSync(`xcrun simctl list devices`)
- .toString()
- .split("\n")
- .map(line => {
- // extract device name and UUID from the line
- const match = line.match(/(.*?)\s+\(([\w-]+)\)\s+\(Booted\)/);
- if (!match) {
- return null;
- }
+ return execSync(`xcrun simctl list devices`)
+ .toString()
+ .split("\n")
+ .map(line => {
+ // extract device name and UUID from the line
+ const match = line.match(/(.*?)\s+\(([\w-]+)\)\s+\(Booted\)/);
+ if (!match) {
+ return null;
+ }
- const deviceName = match[1].trim();
- const deviceUuid = match[2];
- return {
- name: deviceName,
- uuid: deviceUuid,
- };
- })
- .filter(line => line !== null);
-}
+ const deviceName = match[1].trim();
+ const deviceUuid = match[2];
+ return {
+ name: deviceName,
+ uuid: deviceUuid,
+ };
+ })
+ .filter(line => line !== null);
+};
export const getScreenshot = (simulatorUuid: string): Buffer => {
- return execSync(`xcrun simctl io "${simulatorUuid}" screenshot -`);
-}
+ return execSync(`xcrun simctl io "${simulatorUuid}" screenshot -`);
+};
export const openUrl = (simulatorUuid: string, url: string) => {
- return execSync(`xcrun simctl openurl "${simulatorUuid}" "${url}"`);
-}
+ return execSync(`xcrun simctl openurl "${simulatorUuid}" "${url}"`);
+};
export const launchApp = (simulatorUuid: string, packageName: string) => {
- return execSync(`xcrun simctl launch "${simulatorUuid}" "${packageName}"`);
-}
+ return execSync(`xcrun simctl launch "${simulatorUuid}" "${packageName}"`);
+};
export const listApps = (simulatorUuid: string) => {
- return execSync(`xcrun simctl list apps "${simulatorUuid}"`);
-}
+ return execSync(`xcrun simctl list apps "${simulatorUuid}"`);
+};
diff --git a/src/logger.ts b/src/logger.ts
index 4b1fe01..af2ae07 100644
--- a/src/logger.ts
+++ b/src/logger.ts
@@ -1,20 +1,21 @@
import { appendFileSync } from "fs";
const writeLog = (message: string) => {
- if (process.env.LOG_FILE) {
- const logfile = process.env.LOG_FILE;
- const timestamp = new Date().toISOString();
- const levelStr = 'INFO';
- const logMessage = `[${timestamp}] ${levelStr} ${message}`;
- appendFileSync(logfile, logMessage + '\n');
- console.error(logMessage)
- }
+ if (process.env.LOG_FILE) {
+ const logfile = process.env.LOG_FILE;
+ const timestamp = new Date().toISOString();
+ const levelStr = "INFO";
+ const logMessage = `[${timestamp}] ${levelStr} ${message}`;
+ appendFileSync(logfile, logMessage + "\n");
+ }
+
+ console.error(message);
};
export const trace = (message: string) => {
- writeLog(message);
+ writeLog(message);
};
export const error = (message: string) => {
- writeLog(message);
+ writeLog(message);
};
diff --git a/src/server.ts b/src/server.ts
index 45e4155..ba94696 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -1,235 +1,235 @@
-import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
-import { CallToolResult } from '@modelcontextprotocol/sdk/types';
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { CallToolResult } from "@modelcontextprotocol/sdk/types";
-import { writeFileSync } from 'fs';
-import { execSync } from 'child_process';
-import { error, trace } from './logger';
+import { execSync } from "child_process";
+import { error, trace } from "./logger";
import { z, ZodRawShape, ZodTypeAny } from "zod";
-import { getElementCoordinates, getScreenSize, resolveLaunchableActivities, swipe, takeScreenshot } from './android';
+import { getElementCoordinates, getScreenSize, swipe, takeScreenshot } from "./android";
-import sharp from 'sharp';
+import sharp from "sharp";
const getAgentVersion = (): string => {
- const json = require('../package.json');
- return json.version;
-}
+ const json = require("../package.json");
+ return json.version;
+};
export const createMcpServer = (): McpServer => {
- const server = new McpServer({
- name: "appium-mcp",
- version: getAgentVersion(),
- capabilities: {
- resources: {},
- tools: {},
- },
- });
-
- const tool = (name: string, description: string, paramsSchema: ZodRawShape, cb: (args: z.objectOutputType<ZodRawShape, ZodTypeAny>) => Promise<string>) => {
- const wrappedCb = async (args: ZodRawShape): Promise<CallToolResult> => {
- try {
- trace(`Invoking ${name} with args: ${JSON.stringify(args)}`);
- const response = await cb(args);
- trace(`=> ${response}`);
- return {
- 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,
- };
- }
- };
-
- server.tool(name, description, paramsSchema, (args) => wrappedCb(args));
- };
-
- tool(
- "list-apps-on-device",
- "List all apps on device",
- {},
- async ({}) => {
- const result = execSync(`adb shell pm list packages`)
- .toString()
- .split("\n")
- .filter(line => line.startsWith("package:"))
- .map(line => line.substring("package:".length));
-
- return `Found these packages on device: ${result.join(",")}`;
- }
- );
-
- tool(
- "launch-app",
- "Launch an app on mobile device",
- {
- packageName: z.string().describe("The package name of the app to launch"),
- },
- async ({ packageName }) => {
- execSync(`adb shell monkey -p "${packageName}" -c android.intent.category.LAUNCHER 1`);
- return `Launched app ${packageName}`;
- }
- );
-
- tool(
- "get-screen-size",
- "Get the screen size of the mobile device in pixels",
- {},
- async ({}) => {
- const screenSize = getScreenSize();
- return `Screen size is ${screenSize[0]}x${screenSize[1]} pixels`;
- }
- );
-
- tool(
- "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"),
- },
- async ({ x, y }) => {
- const screenSize = getScreenSize();
- const x0 = Math.floor(screenSize[0] * x);
- const y0 = Math.floor(screenSize[1] * y);
- execSync(`adb shell input tap ${x0} ${y0}`);
- return `Clicked on screen at coordinates: ${x}, ${y}`;
- }
- );
-
- tool(
- "find-element-on-screen",
- "Find coordinates of an element on device by text",
- {
- text: z.string().describe("Text of the element to find"),
- },
- async ({ text }) => {
- const coordinates = getElementCoordinates(text);
- const screenSize = getScreenSize();
- const x = coordinates.x / screenSize[0];
- const y = coordinates.y / screenSize[1];
- return `Found element with text "${text}" at coordinates: ${x},${y}`;
- }
- );
-
- tool(
- "press-button",
- "Press a button on device",
- {
- button: z.string().describe("The button to press. Supported buttons: KEYCODE_BACK, KEYCODE_HOME, KEYCODE_MENU, KEYCODE_VOLUME_UP, KEYCODE_VOLUME_DOWN, KEYCODE_ENTER"),
- },
- async ({ button }) => {
- execSync(`adb shell input keyevent ${button}`);
- return `Pressed the button: ${button}`;
- }
- );
-
- tool(
- "open-url",
- "Open a URL in browser on device",
- {
- url: z.string().describe("The URL to open"),
- },
- async ({ url }) => {
- execSync(`adb shell am start -a android.intent.action.VIEW -d "${url}"`);
- return `Opened URL: ${url}`;
- }
- );
-
- tool(
- "swipe-on-screen",
- "Swipe on the screen",
- {
- direction: z.enum(["up", "down"]).describe("The direction to swipe"),
- },
- async ({ direction }) => {
- swipe(direction);
- return `Swiped ${direction} on screen`;
- }
- );
-
- tool(
- "swipe-down-until-element-is-visible",
- "Swipe down on the screen until an element is visible",
- {
- text: z.string().describe("The text of the element to swipe down until"),
- },
- async ({ text }) => {
- let found = false;
- for (let i = 0; i < 10; i++) {
- try {
- const coordinates = getElementCoordinates(text);
- // element is visible on screen, break
- found = true;
- break;
- } catch (error: any) {
- trace(`Element with text "${text}" not found on screen, retrying...`);
- swipe("down");
- }
- }
-
- if (!found) {
- throw new Error(`Element with text "${text}" not found on screen after scrolling down 10 times`);
- }
-
- return `Swiped down on screen until element is visible: ${text}`;
- }
- );
-
- tool(
- 'type-text',
- 'Type text into the focused element',
- {
- text: z.string().describe('The text to type'),
- },
- async ({ text }) => {
- const _text = text.replace(/ /g, '\\ ');
- execSync(`adb shell input text "${_text}"`);
- return `Typed text: ${text}`;
- }
- );
-
- server.tool(
- 'take-device-screenshot',
- 'Take a screenshot of the mobile device',
- {},
- async ({}) => {
- try {
- const screenshot = await takeScreenshot();
-
- // Scale down the screenshot by 50%
- const image = sharp(screenshot);
- const metadata = await image.metadata();
- if (!metadata.width) {
- throw new Error("Failed to get screenshot metadata");
- }
-
- const resizedScreenshot = await image
- .resize(Math.floor(metadata.width / 2))
- .jpeg({ quality: 75 })
- .toBuffer();
-
- // debug:
- // writeFileSync('/tmp/screenshot.png', screenshot);
- // writeFileSync('/tmp/screenshot-scaled.jpg', resizedScreenshot);
-
- const screenshot64 = resizedScreenshot.toString('base64');
- trace(`Screenshot taken: ${screenshot.length} bytes`);
-
- return {
- content: [{ type: 'image', data: screenshot64, mimeType: 'image/jpeg' }]
- };
- } catch (err: any) {
- error(`Error taking screenshot: ${err.message} ${err.stack}`);
- return {
- content: [{ type: 'text', text: `Error: ${err.message}` }],
- isError: true,
- };
- }
- }
- );
-
- return server;
-}
\ No newline at end of file
+ const server = new McpServer({
+ name: "appium-mcp",
+ version: getAgentVersion(),
+ capabilities: {
+ resources: {},
+ tools: {},
+ },
+ });
+
+ const tool = (name: string, description: string, paramsSchema: ZodRawShape, cb: (args: z.objectOutputType<ZodRawShape, ZodTypeAny>) => Promise<string>) => {
+ const wrappedCb = async (args: ZodRawShape): Promise<CallToolResult> => {
+ try {
+ trace(`Invoking ${name} with args: ${JSON.stringify(args)}`);
+ const response = await cb(args);
+ trace(`=> ${response}`);
+ return {
+ 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,
+ };
+ }
+ };
+
+ server.tool(name, description, paramsSchema, args => wrappedCb(args));
+ };
+
+ tool(
+ "list-apps-on-device",
+ "List all apps on device",
+ {},
+ async ({}) => {
+ const result = execSync(`adb shell pm list packages`)
+ .toString()
+ .split("\n")
+ .filter(line => line.startsWith("package:"))
+ .map(line => line.substring("package:".length));
+
+ return `Found these packages on device: ${result.join(",")}`;
+ }
+ );
+
+ tool(
+ "launch-app",
+ "Launch an app on mobile device",
+ {
+ packageName: z.string().describe("The package name of the app to launch"),
+ },
+ async ({ packageName }) => {
+ execSync(`adb shell monkey -p "${packageName}" -c android.intent.category.LAUNCHER 1`);
+ return `Launched app ${packageName}`;
+ }
+ );
+
+ tool(
+ "get-screen-size",
+ "Get the screen size of the mobile device in pixels",
+ {},
+ async ({}) => {
+ const screenSize = getScreenSize();
+ return `Screen size is ${screenSize[0]}x${screenSize[1]} pixels`;
+ }
+ );
+
+ tool(
+ "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"),
+ },
+ async ({ x, y }) => {
+ const screenSize = getScreenSize();
+ const x0 = Math.floor(screenSize[0] * x);
+ const y0 = Math.floor(screenSize[1] * y);
+ execSync(`adb shell input tap ${x0} ${y0}`);
+ return `Clicked on screen at coordinates: ${x}, ${y}`;
+ }
+ );
+
+ tool(
+ "find-element-on-screen",
+ "Find coordinates of an element on device by text",
+ {
+ text: z.string().describe("Text of the element to find"),
+ },
+ async ({ text }) => {
+ const coordinates = getElementCoordinates(text);
+ const screenSize = getScreenSize();
+ const x = coordinates.x / screenSize[0];
+ const y = coordinates.y / screenSize[1];
+ return `Found element with text "${text}" at coordinates: ${x},${y}`;
+ }
+ );
+
+ tool(
+ "press-button",
+ "Press a button on device",
+ {
+ button: z.string().describe("The button to press. Supported buttons: KEYCODE_BACK, KEYCODE_HOME, KEYCODE_MENU, KEYCODE_VOLUME_UP, KEYCODE_VOLUME_DOWN, KEYCODE_ENTER"),
+ },
+ async ({ button }) => {
+ execSync(`adb shell input keyevent ${button}`);
+ return `Pressed the button: ${button}`;
+ }
+ );
+
+ tool(
+ "open-url",
+ "Open a URL in browser on device",
+ {
+ url: z.string().describe("The URL to open"),
+ },
+ async ({ url }) => {
+ execSync(`adb shell am start -a android.intent.action.VIEW -d "${url}"`);
+ return `Opened URL: ${url}`;
+ }
+ );
+
+ tool(
+ "swipe-on-screen",
+ "Swipe on the screen",
+ {
+ direction: z.enum(["up", "down"]).describe("The direction to swipe"),
+ },
+ async ({ direction }) => {
+ swipe(direction);
+ return `Swiped ${direction} on screen`;
+ }
+ );
+
+ tool(
+ "swipe-down-until-element-is-visible",
+ "Swipe down on the screen until an element is visible",
+ {
+ text: z.string().describe("The text of the element to swipe down until"),
+ },
+ async ({ text }) => {
+ let found = false;
+ for (let i = 0; i < 10; i++) {
+ try {
+ getElementCoordinates(text);
+
+ // element is visible on screen, break
+ found = true;
+ break;
+ } catch (error: any) {
+ trace(`Element with text "${text}" not found on screen, retrying...`);
+ swipe("down");
+ }
+ }
+
+ if (!found) {
+ throw new Error(`Element with text "${text}" not found on screen after scrolling down 10 times`);
+ }
+
+ return `Swiped down on screen until element is visible: ${text}`;
+ }
+ );
+
+ tool(
+ "type-text",
+ "Type text into the focused element",
+ {
+ text: z.string().describe("The text to type"),
+ },
+ async ({ text }) => {
+ const _text = text.replace(/ /g, "\\ ");
+ execSync(`adb shell input text "${_text}"`);
+ return `Typed text: ${text}`;
+ }
+ );
+
+ server.tool(
+ "take-device-screenshot",
+ "Take a screenshot of the mobile device",
+ {},
+ async ({}) => {
+ try {
+ const screenshot = await takeScreenshot();
+
+ // Scale down the screenshot by 50%
+ const image = sharp(screenshot);
+ const metadata = await image.metadata();
+ if (!metadata.width) {
+ throw new Error("Failed to get screenshot metadata");
+ }
+
+ const resizedScreenshot = await image
+ .resize(Math.floor(metadata.width / 2))
+ .jpeg({ quality: 75 })
+ .toBuffer();
+
+ // debug:
+ // writeFileSync('/tmp/screenshot.png', screenshot);
+ // writeFileSync('/tmp/screenshot-scaled.jpg', resizedScreenshot);
+
+ const screenshot64 = resizedScreenshot.toString("base64");
+ trace(`Screenshot taken: ${screenshot.length} bytes`);
+
+ return {
+ content: [{ type: "image", data: screenshot64, mimeType: "image/jpeg" }]
+ };
+ } catch (err: any) {
+ error(`Error taking screenshot: ${err.message} ${err.stack}`);
+ return {
+ content: [{ type: "text", text: `Error: ${err.message}` }],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ return server;
+};
diff --git a/tsconfig.json b/tsconfig.json
index 7bc09d3..04116e1 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -11,4 +11,4 @@
"include": [
"src",
],
-}
+}
\ No newline at end of file