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.

7.4 KB
Raw Blame
import { existsSync } from "node:fs";
import { dirname, join, sep } from "node:path";
import { execFileSync, spawn, ChildProcess } from "node:child_process";

export interface MobilecliCrashEntry {
	processName: string;
	timestamp: string;
	id: string;
}

export interface MobilecliCrashesListResponse {
	status: "ok";
	data: MobilecliCrashEntry[];
}

export interface MobilecliCrashGetResponse {
	status: "ok";
	data: {
		content: string;
		id: string;
	};
}

export interface MobilecliAgentStatusResponse {
	status: "ok" | "fail";
	data: {
		message: string;
	};
}

export interface MobilecliDevicesOptions {
	includeOffline?: boolean;
	platform?: "ios" | "android";
	type?: "real" | "emulator" | "simulator";
}

export interface MobilecliRemoteAllocateOptions {
	platform: "ios" | "android";
	name?: string;
	version?: string[];
	type?: "real";
	wait?: boolean;
	timeoutSeconds?: number;
}

export interface MobilecliDeviceProvider {
	type: string; // e.g. "mobilefleet" for remote devices
	allocationId?: string;
}

export interface MobilecliDevice {
	id: string;
	name: string;
	platform: "android" | "ios";
	type: "real" | "emulator" | "simulator";
	version: string;
	state: "online" | "offline";
	provider?: MobilecliDeviceProvider;
}

export interface MobilecliDevicesResponse {
	status: "ok";
	data: {
		devices: MobilecliDevice[];
	};
}

const TIMEOUT = 30000;
const MAX_BUFFER_SIZE = 1024 * 1024 * 8;
const DEFAULT_ALLOCATE_TIMEOUT_SECONDS = 900; // matches mobilecli's own "remote allocate --wait" default

export class Mobilecli {
	private path: string | null = null;

	constructor() { }

	private getPath(): string {
		if (!this.path) {
			this.path = Mobilecli.getMobilecliPath();
		}
		return this.path;
	}

	public executeCommand(args: string[], timeoutMs?: number): string {
		const path = this.getPath();
		const options: { encoding: "utf8"; maxBuffer: number; timeout?: number } = { encoding: "utf8", maxBuffer: MAX_BUFFER_SIZE };
		if (timeoutMs !== undefined) {
			options.timeout = timeoutMs;
		}

		return execFileSync(path, args, options).toString().trim();
	}

	public spawnCommand(args: string[], captureOutput = false): ChildProcess {
		const binaryPath = this.getPath();
		return spawn(binaryPath, args, {
			stdio: ["ignore", captureOutput ? "pipe" : "ignore", captureOutput ? "pipe" : "ignore"],
		});
	}

	public executeCommandBuffer(args: string[]): Buffer {
		const path = this.getPath();
		return execFileSync(path, args, {
			encoding: "buffer",
			maxBuffer: MAX_BUFFER_SIZE,
			timeout: TIMEOUT,
		}) as Buffer;
	}

	private static getMobilecliPath(): string {
		if (process.env.MOBILECLI_PATH) {
			return process.env.MOBILECLI_PATH;
		}

		const platform = process.platform;
		const arch = process.arch;

		const normalizedPlatform = platform === "win32" ? "windows" : platform;
		const normalizedArch = arch === "arm64" ? "arm64" : "amd64";
		const ext = platform === "win32" ? ".exe" : "";
		const scopedPackage = `mobilecli-${normalizedPlatform}-${normalizedArch}`;
		const binaryName = `${scopedPackage}${ext}`;

		const nodeModulesRoots: string[] = [];

		// Check if mobile-mcp is installed as a package
		const currentPath = __filename;
		const pathParts = currentPath.split(sep);
		const lastNodeModulesIndex = pathParts.lastIndexOf("node_modules");

		if (lastNodeModulesIndex !== -1) {
			// We're inside node_modules, go to the last node_modules in the path
			nodeModulesRoots.push(pathParts.slice(0, lastNodeModulesIndex + 1).join(sep));
		}

		// Not in node_modules, look one directory up from current script
		nodeModulesRoots.push(join(dirname(dirname(__filename)), "node_modules"));

		for (const root of nodeModulesRoots) {
			// mobilecli <= 1.0.6 shipped the binary in its own bin directory
			const legacyPath = join(root, "mobilecli", "bin", binaryName);
			if (existsSync(legacyPath)) {
				return legacyPath;
			}

			// mobilecli >= 1.0.7 ships per-platform binaries in scoped packages
			const scopedPath = join(root, "@mobilenext", scopedPackage, binaryName);
			if (existsSync(scopedPath)) {
				return scopedPath;
			}

		}

		throw new Error(`Could not find mobilecli binary for platform: ${platform}`);
	}

	getVersion(): string {
		try {
			const output = this.executeCommand(["--version"]);
			if (output.startsWith("mobilecli version ")) {
				return output.substring("mobilecli version ".length);
			}

			return "failed";
		} catch (error: any) {
			return "failed " + error.message;
		}
	}

	spawnRemoteLogin(): ChildProcess {
		const binaryPath = this.getPath();
		return spawn(binaryPath, ["auth", "login", "--provider", "mobilenext"], {
			stdio: ["ignore", "pipe", "pipe"],
		});
	}

	remoteListDevices(): string {
		return this.executeCommand(["remote", "list-devices"]);
	}

	remoteAllocate(options: MobilecliRemoteAllocateOptions): string {
		const args = ["remote", "allocate", "--platform", options.platform];

		if (options.name) {
			args.push("--name", options.name);
		}

		for (const version of options.version ?? []) {
			args.push("--version", version);
		}

		if (options.type) {
			args.push("--type", options.type);
		}

		if (options.wait) {
			args.push("--wait");
		}

		if (options.timeoutSeconds !== undefined) {
			args.push("--timeout", String(options.timeoutSeconds));
		}

		// only "--wait" makes this call block for as long as mobilecli's own allocation timeout
		const execTimeoutMs = options.wait
			? (options.timeoutSeconds ?? DEFAULT_ALLOCATE_TIMEOUT_SECONDS) * 1000 + 5000
			: undefined;

		return this.executeCommand(args, execTimeoutMs);
	}

	remoteRelease(deviceId: string): string {
		return this.executeCommand(["remote", "release", "--device", deviceId]);
	}

	crashesList(deviceId: string): MobilecliCrashesListResponse {
		const output = this.executeCommand(["device", "crashes", "list", "--device", deviceId]);
		return JSON.parse(output) as MobilecliCrashesListResponse;
	}

	crashesGet(deviceId: string, id: string): MobilecliCrashGetResponse {
		const output = this.executeCommandBuffer(["device", "crashes", "get", id, "--device", deviceId]);
		return JSON.parse(output.toString().trim()) as MobilecliCrashGetResponse;
	}

	agentStatus(deviceId: string): MobilecliAgentStatusResponse {
		try {
			const output = this.executeCommand(["agent", "status", "--device", deviceId]);
			return JSON.parse(output) as MobilecliAgentStatusResponse;
		} catch (error: any) {
			// mobilecli exits 1 when the agent is missing, but still prints the json status
			if (!error.stdout) {
				throw error;
			}

			return JSON.parse(error.stdout.toString()) as MobilecliAgentStatusResponse;
		}
	}

	agentInstall(deviceId: string): void {
		this.executeCommand(["agent", "install", "--device", deviceId]);
	}

	getDevices(options?: MobilecliDevicesOptions): MobilecliDevicesResponse {
		const args = ["devices"];

		if (options) {
			if (options.includeOffline) {
				args.push("--include-offline");
			}

			if (options.platform) {
				if (options.platform !== "ios" && options.platform !== "android") {
					throw new Error(`Invalid platform: ${options.platform}. Must be "ios" or "android"`);
				}

				args.push("--platform", options.platform);
			}

			if (options.type) {
				if (options.type !== "real" && options.type !== "emulator" && options.type !== "simulator") {
					throw new Error(`Invalid type: ${options.type}. Must be "real", "emulator", or "simulator"`);
				}

				args.push("--type", options.type);
			}
		}

		const mobilecliOutput = this.executeCommand(args);
		return JSON.parse(mobilecliOutput) as MobilecliDevicesResponse;
	}
}