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: adding mobile_get_logs
Benjamin Myers5368364decd6
diff --git a/src/android.ts b/src/android.tsindex eaa6fd5..8c9f0ea 100644--- a/src/android.ts+++ b/src/android.ts@@ -375,6 +375,122 @@ export class AndroidRobot implements Robot {return rotation === "0" ? "portrait" : "landscape";}+ public async getDeviceLogs(options?: { timeWindow?: string; filter?: string; process?: string }): Promise<string> {+ const timeWindow = options?.timeWindow || "1m";+ const filter = options?.filter;+ const processFilter = options?.process;+ let packageFilter: string | null = null;+ let searchQuery: string | null = null;+ let effectiveFilter = filter;+ // For Android: if both process and filter are provided, combine them as "package:<process> <filter>"+ if (processFilter && filter && !filter.includes("package:")) {+ effectiveFilter = `package:${processFilter} ${filter}`;+ } else if (processFilter && !filter) {+ effectiveFilter = `package:${processFilter}`;+ }+ // Handle Android package filtering syntax+ if (effectiveFilter) {+ if (effectiveFilter.startsWith("package:mine")) {+ // Filter to user apps only+ const query = effectiveFilter.replace("package:mine", "").trim();+ searchQuery = query || null;+ // Will filter user packages in post-processing+ } else if (effectiveFilter.includes("package:")) {+ // Handle specific package filters like package:com.example.app search_term+ const packageMatch = effectiveFilter.match(/package:([^\s]+)(?:\s+(.+))?/);+ if (packageMatch) {+ packageFilter = packageMatch[1];+ searchQuery = packageMatch[2] || null;+ }+ } else {+ // Regular search filter+ searchQuery = effectiveFilter;+ }+ }++ const args = ["shell", "logcat"];+ if (timeWindow) {+ // Calculate timestamp for time-based filtering using -T+ const timeInSeconds = this.parseTimeWindow(timeWindow);+ const startTime = new Date(Date.now() - (timeInSeconds * 1000));+ // Format as MM-dd HH:mm:ss.mmm+ const month = String(startTime.getMonth() + 1).padStart(2, "0");+ const day = String(startTime.getDate()).padStart(2, "0");+ const hours = String(startTime.getHours()).padStart(2, "0");+ const minutes = String(startTime.getMinutes()).padStart(2, "0");+ const seconds = String(startTime.getSeconds()).padStart(2, "0");+ const milliseconds = String(startTime.getMilliseconds()).padStart(3, "0");++ const timeFormat = `${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;+ args.push("-T", timeFormat);+ } else {+ args.push("-d");+ }+ // Add package filtering directly to logcat if we have a specific package+ if (packageFilter && packageFilter !== "mine") {+ // Use logcat's native package filtering with --pid+ try {+ // First get the PID(s) for this package+ const pidOutput = this.adb("shell", "pidof", packageFilter).toString().trim();+ if (pidOutput) {+ const pids = pidOutput.split(/\s+/);+ for (const pid of pids) {+ args.push("--pid", pid);+ }+ }+ } catch (error) {+ // If pidof fails, fall back to post-processing+ }+ }+ const output = this.adb(...args).toString();++ // Post-process filtering+ const lines = output.split("\n").filter(line => line.trim());+ let filteredLines = lines;+ // Filter by specific package if provided (fallback if --pid didn't work)+ if (packageFilter && packageFilter !== "mine") {+ filteredLines = filteredLines.filter(line => {+ return line.includes(packageFilter!);+ });+ }+ // Filter for user packages if package:mine+ if (filter && filter.startsWith("package:mine")) {+ filteredLines = filteredLines.filter(line => {+ // Look for user app indicators - avoid system/Android logs+ return !line.includes("com.android.") &&+ !line.includes("android.") &&+ !line.includes("system_") &&+ (line.includes("com.") || line.includes("io.") || line.includes("net.") || line.includes("app."));+ });+ }+ // Apply text search if provided+ if (searchQuery) {+ filteredLines = filteredLines.filter(line => {+ return line.toLowerCase().includes(searchQuery!.toLowerCase());+ });+ }+ return filteredLines.join("\n");+ }++ private parseTimeWindow(timeWindow: string): number {+ const match = timeWindow.match(/^(\d+)([smh])$/);+ if (!match) {+ return 60;+ }+ const value = parseInt(match[1], 10);+ const unit = match[2];+ switch (unit) {+ case "s":+ return value;+ case "m":+ return value * 60;+ case "h":+ return value * 3600;+ default:+ return 60;+ }+ }+private async getUiAutomatorDump(): Promise<string> {for (let tries = 0; tries < 10; tries++) {const dump = this.adb("exec-out", "uiautomator", "dump", "/dev/tty").toString();diff --git a/src/ios.ts b/src/ios.tsindex ca0d10b..718b998 100644--- a/src/ios.ts+++ b/src/ios.ts@@ -200,6 +200,46 @@ export class IosRobot implements Robot {const wda = await this.wda();return await wda.getOrientation();}++ public async getDeviceLogs(options?: { timeWindow?: string; filter?: string; process?: string }): Promise<string> {+ await this.assertTunnelRunning();+ const timeWindow = options?.timeWindow || "1m";+ const filter = options?.filter;+ const args = ["syslog"];+ if (timeWindow) {+ const timeInSeconds = this.parseTimeWindow(timeWindow);+ args.push("--since");+ args.push(`${timeInSeconds}s`);+ }+ let output = await this.ios(...args);+ if (filter) {+ const lines = output.split("\n");+ const filteredLines = lines.filter(line =>+ line.toLowerCase().includes(filter.toLowerCase())+ );+ output = filteredLines.join("\n");+ }+ return output;+ }++ private parseTimeWindow(timeWindow: string): number {+ const match = timeWindow.match(/^(\d+)([smh])$/);+ if (!match) {+ return 60;+ }+ const value = parseInt(match[1], 10);+ const unit = match[2];+ switch (unit) {+ case "s":+ return value;+ case "m":+ return value * 60;+ case "h":+ return value * 3600;+ default:+ return 60;+ }+ }}export class IosManager {diff --git a/src/iphone-simulator.ts b/src/iphone-simulator.tsindex 430f080..6f694ed 100644--- a/src/iphone-simulator.ts+++ b/src/iphone-simulator.ts@@ -179,6 +179,69 @@ export class Simctl implements Robot {const wda = await this.wda();return wda.getOrientation();}++ public async getDeviceLogs(options?: { timeWindow?: string; filter?: string; process?: string }): Promise<string> {+ const timeWindow = options?.timeWindow || "1m";+ const filter = options?.filter;+ const processFilter = options?.process;+ const deviceUuid = this.simulatorUuid;++ let predicate = "";+ let currentApp: string | null = null;++ // If a specific process is provided, use that+ if (processFilter) {+ currentApp = processFilter;+ predicate = `subsystem == "${processFilter}"`;+ } else {+ // Try to detect currently running user apps from installed apps+ try {+ const runningApps = await this.listApps();++ // Filter to non-Apple user apps+ const userApps = runningApps+ .map((app: InstalledApp) => app.packageName)+ .filter((appId: string) => !appId.startsWith("com.apple.") && appId.includes("."));++ if (userApps.length > 0) {+ // For now, just use the first user app found+ // In the future, we could try to detect which is actually running+ currentApp = userApps[0];+ predicate = `subsystem == "${currentApp}"`;+ }+ } catch (error) {+ // Failed to get apps, continue with fallback+ }++ // If no user app detected, use broader filter for non-Apple apps+ if (!predicate) {+ predicate = "subsystem CONTAINS \"com.\" AND NOT subsystem BEGINSWITH \"com.apple.\"";+ }+ }+ if (filter) {+ predicate += ` AND composedMessage CONTAINS[c] "${filter}"`;+ }++ const args = [+ "spawn", deviceUuid, "log", "show",+ "--last", timeWindow,+ "--predicate", predicate,+ "--info",+ "--debug"+ ];++ try {+ const logs = this.simctl(...args).toString();+ const appInfo = currentApp ? ` (focused on: ${currentApp})` : " (all non-Apple apps)";+ const debugInfo = `DEBUG: Using predicate: ${predicate}${appInfo}\n\n`;+ return `${debugInfo}${logs}`;+ } catch (error) {+ if (error instanceof Error && error.message.includes("No logging subsystem")) {+ return "No logs found for the current running applications.";+ }+ throw error;+ }+ }}export class SimctlManager {diff --git a/src/robot.ts b/src/robot.tsindex a7c3446..45a92b3 100644--- a/src/robot.ts+++ b/src/robot.ts@@ -125,4 +125,9 @@ export interface Robot {* Get the current screen orientation.*/getOrientation(): Promise<Orientation>;++ /**+ * Get device logs with optional filtering.+ */+ getDeviceLogs(options?: { timeWindow?: string; filter?: string; process?: string }): Promise<string>;}diff --git a/src/server.ts b/src/server.tsindex 4d56a82..288fd6e 100644--- a/src/server.ts+++ b/src/server.ts@@ -502,6 +502,24 @@ export const createMcpServer = (): McpServer => {});+ tool(+ "mobile_get_logs",+ "Get device logs",+ {+ timeWindow: z.string().optional().describe("Time window to look back (e.g., '5m' for 5 minutes, '1h' for 1 hour). Defaults to '1m'"),+ filter: z.string().optional().describe("Filter logs containing this query (case-insensitive). For Android: supports 'package:mine <query>' (user apps only), 'package:com.app.bundle <query>' (specific app), or '<query>' (text search). For iOS: simple text search only."),+ process: z.string().optional().describe("Filter logs to a specific process/app bundle ID")+ },+ async ({ timeWindow, filter, process }) => {+ requireRobot();+ const logs = await robot!.getDeviceLogs({ timeWindow, filter, process });+ const filterText = filter ? ` (filtered by: ${filter})` : "";+ const processText = process ? ` (process: ${process})` : "";+ const timeText = timeWindow ? ` from last ${timeWindow}` : "";+ return `Device logs${timeText}${filterText}${processText}:\n${logs}`;+ }+ );+// async check for latest agent versioncheckForLatestAgentVersion().then();