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
feat: add location, clipboard and device logs tools (#423)
Gil Megidishea36aa570747
diff --git a/src/mobile-device.ts b/src/mobile-device.tsindex 3600b7b..e5b5dda 100644--- a/src/mobile-device.ts+++ b/src/mobile-device.ts@@ -72,6 +72,12 @@ interface OrientationResponse {};}+interface ClipboardResponse {+ data: {+ text: string;+ };+}+const flattenUIElement = (element: UIElementResponse): ScreenElement[] => {const screenElement: ScreenElement = {type: element.type,@@ -254,4 +260,62 @@ export class MobileDevice implements Robot {const response = JSON.parse(this.runCommand(["device", "orientation", "get"])) as OrientationResponse;return response.data.orientation;}++ public async setLocation(latitude: number, longitude: number): Promise<void> {+ this.runCommand(["device", "location", "set", `${latitude},${longitude}`]);+ }++ public async clearLocation(): Promise<void> {+ this.runCommand(["device", "location", "clear"]);+ }++ public async getClipboard(): Promise<string> {+ const response = JSON.parse(this.runCommand(["io", "clipboard", "get"])) as ClipboardResponse;+ return response.data.text;+ }++ public async setClipboard(text: string): Promise<void> {+ this.runCommand(["io", "clipboard", "set", text]);+ }++ public getLogs(limit: number, filters: string[], timeoutMs: number): Promise<string> {+ const args = ["device", "logs", "--limit", String(limit), ...filters.flatMap(filter => ["--filter", filter]), "--device", this.deviceId];+ const child = this.mobilecli.spawnCommand(args, true);++ return new Promise((resolve, reject) => {+ const stdout: Buffer[] = [];+ const stderr: Buffer[] = [];+ let silenceTimer: NodeJS.Timeout;++ // kill the stream once no log entry arrived for timeoutMs, then return what was captured+ const restartSilenceTimer = () => {+ clearTimeout(silenceTimer);+ silenceTimer = setTimeout(() => child.kill(), timeoutMs);+ };++ child.stdout?.on("data", (chunk: Buffer) => {+ stdout.push(chunk);+ restartSilenceTimer();+ });++ child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk));++ child.on("error", err => {+ clearTimeout(silenceTimer);+ reject(err);+ });++ child.on("close", code => {+ clearTimeout(silenceTimer);+ if (code !== 0 && !child.killed) {+ reject(new Error(`mobilecli device logs failed with code ${code}: ${Buffer.concat(stderr).toString().trim()}`));+ return;+ }++ resolve(Buffer.concat(stdout).toString().trim());+ });++ restartSilenceTimer();+ });+ }}diff --git a/src/mobilecli.ts b/src/mobilecli.tsindex 48b91fe..047a25a 100644--- a/src/mobilecli.ts+++ b/src/mobilecli.ts@@ -91,10 +91,10 @@ export class Mobilecli {return execFileSync(path, args, options).toString().trim();}- public spawnCommand(args: string[]): ChildProcess {+ public spawnCommand(args: string[], captureOutput = false): ChildProcess {const binaryPath = this.getPath();return spawn(binaryPath, args, {- stdio: ["ignore", "ignore", "ignore"],+ stdio: ["ignore", captureOutput ? "pipe" : "ignore", captureOutput ? "pipe" : "ignore"],});}diff --git a/src/robot.ts b/src/robot.tsindex fc32312..14b0de6 100644--- a/src/robot.ts+++ b/src/robot.ts@@ -84,6 +84,32 @@ export interface Robot {*/getForegroundApp?(): Promise<InstalledApp>;+ /**+ * Override the GPS location reported by the device. Optional, not all robots support it.+ */+ setLocation?(latitude: number, longitude: number): Promise<void>;++ /**+ * Remove the GPS location override. Optional, not all robots support it.+ */+ clearLocation?(): Promise<void>;++ /**+ * Read the device clipboard. Optional, not all robots support it.+ */+ getClipboard?(): Promise<string>;++ /**+ * Replace the device clipboard. Optional, not all robots support it.+ */+ setClipboard?(text: string): Promise<void>;++ /**+ * Collect device logs until `limit` entries arrive or `timeoutMs` passes. Returns raw NDJSON lines.+ * Filters use key=value or key!=value syntax. Optional, not all robots support it.+ */+ getLogs?(limit: number, filters: string[], timeoutMs: number): Promise<string>;+/*** Launch an app.*/diff --git a/src/server.ts b/src/server.tsindex 600b3aa..1b70976 100644--- a/src/server.ts+++ b/src/server.ts@@ -16,6 +16,11 @@ import { Mobilecli } from "./mobilecli";import { MobileDevice } from "./mobile-device";import { validateOutputPath, validateFileExtension } from "./utils";+const ALLOWED_LOG_EXTENSIONS = [".log", ".txt", ".jsonl"];+const DEFAULT_DEVICE_LOG_ENTRIES = 100;+const MAX_DEVICE_LOG_ENTRIES = 10000;+const DEVICE_LOG_TIMEOUT_MS = 30000;+const DEVICE_LOG_FILTER_PATTERN = /^(pid|process|tag|level|subsystem|category|message)!?=.+$/;const ALLOWED_SCREENSHOT_EXTENSIONS = [".png", ".jpg", ".jpeg"];const ALLOWED_RECORDING_EXTENSIONS = [".mp4"];const LOGIN_PROMPT_TIMEOUT_MS = 15000;@@ -852,6 +857,93 @@ export const createMcpServer = (): McpServer => {});+ tool(+ "mobile_set_location",+ "Set Location",+ "Override the GPS location reported by the device, or clear the override to restore the real location. Omit latitude and longitude to clear.",+ {+ device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),+ latitude: z.number().min(-90).max(90).optional().describe("Latitude in decimal degrees, e.g. 37.7749. Omit together with longitude to clear the override."),+ longitude: z.number().min(-180).max(180).optional().describe("Longitude in decimal degrees, e.g. -122.4194. Omit together with latitude to clear the override."),+ },+ { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ async ({ device, latitude, longitude }) => {+ const robot = getRobotFromDevice(device);+ if (!robot.setLocation || !robot.clearLocation) {+ throw new ActionableError("Setting location is not supported in legacy robot mode");+ }++ if (latitude === undefined && longitude === undefined) {+ await robot.clearLocation();+ return "Cleared location override";+ }++ if (latitude === undefined || longitude === undefined) {+ throw new ActionableError("Both latitude and longitude are required to set a location");+ }++ await robot.setLocation(latitude, longitude);+ return `Set device location to ${latitude},${longitude}`;+ }+ );++ tool(+ "mobile_clipboard",+ "Clipboard",+ "Read or replace the device clipboard. Pass text to set the clipboard, omit it to read the current clipboard.",+ {+ 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().optional().describe("Text to place on the clipboard. Omit to read the clipboard instead."),+ },+ { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ async ({ device, text }) => {+ const robot = getRobotFromDevice(device);+ if (!robot.getClipboard || !robot.setClipboard) {+ throw new ActionableError("Clipboard is not supported in legacy robot mode");+ }++ if (text === undefined) {+ return await robot.getClipboard();+ }++ await robot.setClipboard(text);+ return "Clipboard updated";+ }+ );++ tool(+ "mobile_get_device_logs",+ "Get Device Logs",+ "Collect live device logs (logcat on Android, unified log on iOS) as one JSON object per line. Only logs emitted after the call starts are captured, so trigger the behavior you want to observe right before or during the call. Stops after `limit` entries or after 30 seconds of silence. Each line of a stack trace counts as one entry, so filter by process or tag to avoid filling the limit with noise. Start with a small limit (20-50) for a quick look. For large captures, pass `saveTo` to write logs to a file and only the entry count is returned.",+ {+ device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),+ limit: z.number().int().min(1).max(MAX_DEVICE_LOG_ENTRIES).default(DEFAULT_DEVICE_LOG_ENTRIES).describe("Stop after this many log entries"),+ filter: z.array(z.string().regex(DEVICE_LOG_FILTER_PATTERN, "Filter must be key=value or key!=value with key in: pid, process, tag, level, subsystem, category, message")).default([]).describe("Filters, ANDed together. key=value includes, key!=value excludes. Keys: pid, process, tag, level, subsystem, category, message. Example: [\"tag=ActivityManager\", \"level=Error\", \"process!=SpringBoard\"]"),+ saveTo: z.string().optional().describe("Path to write the logs to instead of returning them. Filename must end with .log, .txt, or .jsonl"),+ },+ { readOnlyHint: true, openWorldHint: true },+ async ({ device, limit, filter, saveTo }) => {+ if (saveTo) {+ validateFileExtension(saveTo, ALLOWED_LOG_EXTENSIONS, "get_device_logs");+ validateOutputPath(saveTo);+ }++ const robot = getRobotFromDevice(device);+ if (!robot.getLogs) {+ throw new ActionableError("Device logs are not supported in legacy robot mode");+ }++ const logs = await robot.getLogs(limit, filter, DEVICE_LOG_TIMEOUT_MS);+ if (!saveTo) {+ return logs || "No log entries received";+ }++ fs.writeFileSync(saveTo, logs + "\n");+ const lineCount = logs ? logs.split("\n").length : 0;+ return `Saved ${lineCount} log entries to: ${saveTo}`;+ }+ );+tool("mobile_get_orientation","Get Orientation",diff --git a/test/mobile-device.test.ts b/test/mobile-device.test.tsindex b77f908..3525dff 100644--- a/test/mobile-device.test.ts+++ b/test/mobile-device.test.ts@@ -1,4 +1,5 @@import { test, expect } from "@playwright/test";+import { EventEmitter } from "node:events";import { MobileDevice } from "../src/mobile-device";@@ -77,4 +78,87 @@ test.describe("MobileDevice", () => {expect(app).toEqual({ appName: "com.example.app", packageName: "com.example.app" });});});++ test.describe("location", () => {++ test("setLocation should call mobilecli device location set with lat,lng", async () => {+ const { device, calls } = createMockMobileDevice("");+ await device.setLocation(37.7749, -122.4194);++ expect(calls[0]).toEqual(["device", "location", "set", "37.7749,-122.4194", "--device", "test-device"]);+ });++ test("clearLocation should call mobilecli device location clear", async () => {+ const { device, calls } = createMockMobileDevice("");+ await device.clearLocation();++ expect(calls[0]).toEqual(["device", "location", "clear", "--device", "test-device"]);+ });+ });++ test.describe("clipboard", () => {++ test("getClipboard should call mobilecli io clipboard get and return the text", async () => {+ const { device, calls } = createMockMobileDevice(JSON.stringify({ status: "ok", data: { text: "hello" } }));+ const text = await device.getClipboard();++ expect(calls[0]).toEqual(["io", "clipboard", "get", "--device", "test-device"]);+ expect(text).toBe("hello");+ });++ test("setClipboard should call mobilecli io clipboard set with the text", async () => {+ const { device, calls } = createMockMobileDevice("");+ await device.setClipboard("hello");++ expect(calls[0]).toEqual(["io", "clipboard", "set", "hello", "--device", "test-device"]);+ });+ });++ test.describe("logs", () => {++ function createMockLogStream(exitCode: number | null): { device: MobileDevice; calls: string[][]; child: any } {+ const { device, calls } = createMockMobileDevice("");+ const child = new EventEmitter() as any;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.killed = false;+ child.kill = () => {+ child.killed = true;+ child.emit("close", null);+ };+ (device as any).mobilecli.spawnCommand = function(args: string[]): any {+ calls.push(args);+ if (exitCode !== null) {+ setImmediate(() => child.emit("close", exitCode));+ }+ return child;+ };++ return { device, calls, child };+ }++ test("getLogs should pass limit and each filter as a repeated --filter flag", async () => {+ const { device, calls } = createMockLogStream(0);+ await device.getLogs(50, ["tag=ActivityManager", "level!=Debug"], 1000);++ expect(calls[0]).toEqual(["device", "logs", "--limit", "50", "--filter", "tag=ActivityManager", "--filter", "level!=Debug", "--device", "test-device"]);+ });++ test("getLogs should return captured output once the stream goes silent for timeoutMs", async () => {+ const { device, child } = createMockLogStream(null);+ const pending = device.getLogs(50, [], 50);+ child.stdout.emit("data", Buffer.from("{\"a\":1}\n"));++ expect(await pending).toBe("{\"a\":1}");+ expect(child.killed).toBe(true);+ });++ test("getLogs should reject when mobilecli exits with an error", async () => {+ const { device, child } = createMockLogStream(1);+ const pending = device.getLogs(5, [], 1000);+ child.stderr.emit("data", Buffer.from("no such device"));++ await expect(pending).rejects.toThrow("no such device");+ });+ });});diff --git a/test/server-annotations.test.ts b/test/server-annotations.test.tsindex 5200990..8c14bda 100644--- a/test/server-annotations.test.ts+++ b/test/server-annotations.test.ts@@ -31,6 +31,9 @@ const expectedAnnotations: ToolAnnotationMatrix = {mobile_save_screenshot: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },mobile_take_screenshot: { readOnlyHint: true, openWorldHint: true },mobile_set_orientation: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ mobile_set_location: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ mobile_clipboard: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ mobile_get_device_logs: { readOnlyHint: true, openWorldHint: true },mobile_get_orientation: { readOnlyHint: true, openWorldHint: false },mobile_start_screen_recording: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },mobile_stop_screen_recording: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },