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: relying more on adb commands
gmegidishc40abfc04196
diff --git a/src/android.ts b/src/android.tsnew file mode 100644index 0000000..c9202e7--- /dev/null+++ b/src/android.ts@@ -0,0 +1,20 @@+import { execSync } from "child_process";++export const getConnectedDevices = () => {+ const devices = execSync(`adb devices`)+ .toString()+ .split("\n")+ .filter(line => !line.startsWith("List of devices attached"))+ .filter(line => line.trim() != "");++ return devices.length > 0;+};++export const resolveLaunchableActivities = async (packageName: string): Promise<string[]> => {+ return execSync(`adb shell cmd package resolve-activity ${packageName}`)+ .toString()+ .split("\n")+ .map(line => line.trim())+ .filter(line => line.startsWith("name="))+ .map(line => line.substring("name=".length));+}diff --git a/src/index.ts b/src/index.tsindex 87a543e..dd2b95e 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,357 +1,10 @@-import { McpServer, ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';-import { CallToolResult } from '@modelcontextprotocol/sdk/types';import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";-import { z, ZodRawShape } from "zod";--import { appendFileSync, writeFileSync } from 'fs';-import { execSync } from 'child_process';-import { remote } from 'webdriverio';--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)- }-};--const trace = (message: string) => {- writeLog(message);-};--const error = (message: string) => {- writeLog(message);-};--const createAppiumDriver = async (): Promise<WebdriverIO.Browser> => {- const capabilities = {- // platformName: 'iOS',- // 'appium:platformVersion': '18.3',- platformName: 'Android',- // 'appium:automationName': 'XCUITest',- 'appium:automationName': 'UiAutomator2',- };-- const wdOpts = {- hostname: process.env.APPIUM_HOST || 'localhost',- port: parseInt(process.env.APPIUM_PORT || "4723", 10) || 4723,- capabilities,- };-- trace("Connecting to Appium server with capabilities: " + JSON.stringify(capabilities));- const driver = await remote(wdOpts);- trace("Connected to Appium server with driver: " + JSON.stringify(driver));- return driver;-};--let driver: WebdriverIO.Browser;--const resolveLaunchableActivity = async (packageName: string): Promise<string> => {- const result1 = execSync(`adb shell cmd package resolve-activity ${packageName}`)- .toString()- .split("\n")- .map(line => line.trim())- .filter(line => line.startsWith("name="))- .map(line => line.substring("name=".length));-- if (result1.length !== 1) {- throw new Error(`Error launching app: ${packageName}, got too many entries with 'name': ${result1.join(",")}`);- }-- return result1[0];-}--const createMcpServer = async (): Promise<McpServer> => {-- let driver: WebdriverIO.Browser;-- createAppiumDriver().then(d => driver = d);-- const server = new McpServer({- name: "appium-mcp",- version: "1.0.0",- capabilities: {- resources: {},- tools: {},- },- });-- const tool = (name: string, description: string, paramsSchema: ZodRawShape, cb: (args: ZodRawShape) => Promise<string>) => {- const wrappedCb = async (args: ZodRawShape): Promise<CallToolResult> => {- try {- trace(`Invoking tool: ${description}`);- const response = await cb(args);- trace(`Tool ${description} returned: ${response}`);- return {- content: [{ type: 'text', text: response }],- };- } catch (error: any) {- 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 this packages on device: ${result.join(",")}`;- }- );-- server.tool(- "launch-app",- "Launch an app on mobile device",- {- packageName: z.string().describe("The package name of the app to launch"),- },- async ({ packageName }) => {- trace(`Launching packageName: "${packageName}"`);- try {- // FIXME: use appium or monkey for this- const activity = await resolveLaunchableActivity(packageName);- trace(`Found launchable activity: ${packageName}/${activity}`);-- await driver.startActivity(packageName, activity);-- return {- content: [{ type: 'text', text: `Launched app ${packageName}` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Error launching settings app: ${error.message}` }],- isError: true- };- }- }- );-- server.tool(- "click-on-screen-at-coordinates",- "Click on the screen at given x,y coordinates",- {- x: z.number().describe("The x coordinate to click"),- y: z.number().describe("The y coordinate to click"),- },- async ({ x, y }) => {- trace(`Clicking on screen at coordinates ${x},${y}`);- try {- execSync(`adb shell input tap ${x} ${y}`);-- return {- content: [{ type: 'text', text: `Clicked on screen at coordinates: ${x}, ${y}` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to click on screen at coordinates: ${x}, ${y}` }],- isError: true- };- }- }- );-- server.tool(- "click-element",- "Click on an element on device",- {- text: z.string().describe("Text of the element to click"),- },- async ({ text }) => {- try {- trace(`Clicking on element "${text}"`);- const element = await driver.$(`//*[contains(@text, "${text}")]`);-- if (!element) {- trace("Element not found on screen");- return {- content: [{ type: 'text', text: `Element with text "${text}" not found` }],- isError: true- };- }-- await element.click();-- return {- content: [{ type: 'text', text: `Clicked on element with text "${text}"` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Element with text "${text}" not found` }],- isError: true- };- }- }- );--- server.tool(- "press-back-button",- "Press the back button on device",- {},- async ({}) => {- try {- trace("Pressing back button");- await driver.back();-- return {- content: [{ type: 'text', text: `Pressed the back button` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to press the back button` }],- isError: true- };- }- }- );-- server.tool(- "open-url",- "Open a URL in browser on device",- {- url: z.string().describe("The URL to open"),- },- async ({ url }) => {- try {- trace(`Opening URL: ${url}`);- await driver.url(url);- return {- content: [{ type: 'text', text: `Opened URL: ${url}` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to open URL: ${url}` }],- isError: true,- };- }- }- );-- server.tool(- "swipe-down-on-screen",- "Swipe down on the screen",- {},- async ({}) => {- try {- const centerX = 200;- await driver.performActions([{- type: 'pointer',- id: 'finger1',- parameters: { pointerType: 'touch' },- actions: [- { type: 'pointerMove', duration: 0, x: centerX, y: 900 }, // start point- { type: 'pointerDown', button: 0 },- { type: 'pause', duration: 100 },- { type: 'pointerMove', duration: 500, x: centerX, y: 100 }, // swipe up- { type: 'pointerUp', button: 0 }- ]- }]);-- await driver.releaseActions();-- return {- content: [{ type: 'text', text: `Swiped down on screen` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to swipe down on screen` }],- isError: true,- }- }- }- );-- server.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 }) => {- try {- await driver.swipe({- direction: 'down',- duration: 1500,- percent: 0.95, // Using 95% of the screen to avoid triggering OS features- scrollableElement: await driver.$(`//*[contains(@text, "${text}")]`),- });-- return {- content: [{ type: 'text', text: `Swiped down on screen until element is visible: ${text}` }]- }-- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to swipe down on screen` }],- isError: true,- }- }- }- );-- server.tool(- 'type-text',- 'Type text into the focused element',- {- text: z.string().describe('The text to type'),- },- async ({ text }) => {- try {- await driver.keys(text);- return {- content: [{ type: 'text', text: `Typed text: ${text}` }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to type text: ${text}` }],- isError: true,- };- }- }- );-- server.tool(- 'take-app-screenshot',- 'Take a screenshot of the mobile device',- {},- async ({}) => {- try {- const screenshot64 = await driver.takeScreenshot();- writeFileSync('/tmp/screenshot.png', screenshot64);- return {- content: [{ type: 'image', data: screenshot64, mimeType: 'image/png' }]- };- } catch (error: any) {- return {- content: [{ type: 'text', text: `Failed to take app screenshot` }],- isError: true,- };- }- }- );-- return server;-}+import { createMcpServer } from "./server";async function main() {const transport = new StdioServerTransport();- const server = await createMcpServer();+ const server = createMcpServer();await server.connect(transport);console.error("Appium MCP Server running on stdio");diff --git a/src/iphone-simulator.ts b/src/iphone-simulator.tsnew file mode 100644index 0000000..c324253--- /dev/null+++ b/src/iphone-simulator.ts@@ -0,0 +1,27 @@+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;+ }++ const deviceName = match[1].trim();+ const deviceUuid = match[2];+ return {+ name: deviceName,+ uuid: deviceUuid,+ };+ })+ .filter(line => line !== null);+}diff --git a/src/logger.ts b/src/logger.tsnew file mode 100644index 0000000..4b1fe01--- /dev/null+++ b/src/logger.ts@@ -0,0 +1,20 @@+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)+ }+};++export const trace = (message: string) => {+ writeLog(message);+};++export const error = (message: string) => {+ writeLog(message);+};diff --git a/src/server.ts b/src/server.tsnew file mode 100644index 0000000..a455d4f--- /dev/null+++ b/src/server.ts@@ -0,0 +1,268 @@+import { McpServer, ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';+import { CallToolResult } from '@modelcontextprotocol/sdk/types';++import { appendFileSync, readFileSync, writeFileSync } from 'fs';+import { execSync } from 'child_process';+import { remote } from 'webdriverio';+import { trace } from './logger';+import { z, ZodRawShape, ZodTypeAny } from "zod";+import { resolveLaunchableActivities } from './android';++enum APPIUM_SERVER_STATE {+ STOPPED,+ STARTING,+ STARTED,+ STOPPING,+}++let appiumServerState: APPIUM_SERVER_STATE = APPIUM_SERVER_STATE.STOPPED;++const isSimulatorRunning = () => {+}++const createAppiumDriver = async (): Promise<WebdriverIO.Browser> => {++ const capabilities = {+ platformName: 'Android',+ 'appium:automationName': 'UiAutomator2',+ };++ const wdOpts = {+ hostname: process.env.APPIUM_HOST || 'localhost',+ port: parseInt(process.env.APPIUM_PORT || "4723", 10) || 4723,+ capabilities,+ };++ trace("Connecting to Appium server with capabilities: " + JSON.stringify(capabilities));+ const driver = await remote(wdOpts);+ trace("Connected to Appium server with driver: " + JSON.stringify(driver));++ return driver;+};++let driver: WebdriverIO.Browser;++const getAgentVersion = (): string => {+ const text = readFileSync('./package.json');+ const json = JSON.parse(text.toString());+ return json.version;+}++export const createMcpServer = (): McpServer => {++ let driver: WebdriverIO.Browser;++ appiumServerState = APPIUM_SERVER_STATE.STARTING;+ createAppiumDriver().then((d) => {+ driver = d;+ appiumServerState = APPIUM_SERVER_STATE.STARTED;+ });++ 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 tool: ${description}`);+ const response = await cb(args);+ trace(`Tool '${description}' returned: ${response}`);+ return {+ content: [{ type: 'text', text: response }],+ };+ } catch (error: any) {+ trace(`Tool '${description}' failed: ${error.message}`);+ 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 }) => {+ const activities = await resolveLaunchableActivities(packageName);+ trace(`Found launchable activities: ${activities.join(",")}`);++ if (activities.length === 0) {+ throw new Error(`No launchable activities found for package ${packageName}`);+ }++ if (activities.length > 1) {+ trace(`Found multiple launchable activities for package ${packageName}, please specify the activity to launch from this list: ${activities.join(",")}`);+ }++ execSync(`adb shell am start -n ${packageName}/${activities[0]}`);+ return `Launched app ${packageName}`;+ }+ );++ tool(+ "click-on-screen-at-coordinates",+ "Click on the screen at given x,y coordinates",+ {+ x: z.number().describe("The x coordinate to click"),+ y: z.number().describe("The y coordinate to click"),+ },+ async ({ x, y }) => {+ execSync(`adb shell input tap ${x} ${y}`);+ return `Clicked on screen at coordinates: ${x}, ${y}`;+ }+ );++ tool(+ "click-element",+ "Click on an element on device",+ {+ text: z.string().describe("Text of the element to click"),+ },+ async ({ text }) => {+ const element = await driver.$(`//*[contains(@text, "${text}")]`);++ if (!element) {+ trace("Element not found on screen");+ throw new Error(`Element with text "${text}" not found`);+ }++ await element.click();+ return `Clicked on element with text "${text}"`;+ }+ );++ tool(+ "press-back-button",+ "Press the back button on device",+ {},+ async ({}) => {+ execSync(`adb shell input keyevent 4`);+ return `Pressed the back 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-down-on-screen",+ "Swipe down on the screen",+ {},+ async ({}) => {+ const screenSize = await driver.getWindowSize();+ const centerX = screenSize.width / 2;+ const y0 = screenSize.height * 0.90;+ const y1 = screenSize.height * 0.10;++ await driver.performActions([{+ type: 'pointer',+ id: 'finger1',+ parameters: { pointerType: 'touch' },+ actions: [+ { type: 'pointerMove', duration: 0, x: centerX, y: y1 }, // start point+ { type: 'pointerDown', button: 0 },+ { type: 'pause', duration: 100 },+ { type: 'pointerMove', duration: 500, x: centerX, y: y0 }, // swipe up+ { type: 'pointerUp', button: 0 }+ ]+ }]);++ await driver.releaseActions();+ return `Swiped down 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 }) => {+ await driver.swipe({+ direction: 'down',+ duration: 1500,+ percent: 0.90, // Using 90% of the screen to avoid triggering OS features+ scrollableElement: await driver.$(`//*[contains(@text, "${text}")]`),+ });++ 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-app-screenshot',+ 'Take a screenshot of the mobile device',+ {},+ async ({}) => {+ try {+ const screenshot = execSync(`adb exec-out screencap -p`);+ writeFileSync('/tmp/screenshot.png', screenshot);++ const screenshot64 = screenshot.toString('base64');+ trace(`Screenshot taken: ${screenshot.length} bytes`);++ return {+ content: [{ type: 'image', data: screenshot64, mimeType: 'image/png' }]+ };+ } catch (error: any) {+ error(`Error taking screenshot: ${error.message} ${error.stack}`);+ return {+ content: [{ type: 'text', text: `Error: ${error.message}` }],+ isError: true,+ };+ }+ }+ );++ return server;+}\ No newline at end of file