Skip to main content
Glama

android-log

Retrieve Android device logs including system logs, app-specific logs, ANR reports, crash logs, and battery statistics for debugging and analysis.

Instructions

Perform various log retrieval operations on an Android device.

This single tool consolidates various log-related actions. The 'action' parameter determines the operation.

Args: serial: Device serial number. action: The specific log operation to perform. ctx: MCP Context for logging and interaction. package (Optional[str]): Package name for get_app_logs action. lines (int): Number of lines to fetch for logcat actions (default: 1000). filter_expr (Optional[str]): Logcat filter expression for get_device_logcat. buffer (Optional[str]): Logcat buffer for get_device_logcat (default: "main"). format_type (Optional[str]): Logcat output format for get_device_logcat (default: "threadtime"). max_size (Optional[int]): Max output size for get_device_logcat (default: 100KB).

Returns: A string message containing the requested logs or status.


Available Actions and their specific argument usage:

  1. action="get_device_logcat"

    • Optional: lines, filter_expr, buffer, format_type, max_size.

  2. action="get_app_logs"

    • Requires: package.

    • Optional: lines.

  3. action="get_anr_logs"

    • No specific arguments beyond serial and ctx.

  4. action="get_crash_logs"

    • No specific arguments beyond serial and ctx.

  5. action="get_battery_stats"

    • No specific arguments beyond serial and ctx.


Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serialYes
actionYes
packageNo
linesNo
filter_exprNo
bufferNomain
format_typeNothreadtime
max_sizeNo

Implementation Reference

  • Primary handler function for the 'android-log' MCP tool. Includes registration via @mcp.tool decorator and dispatches to specialized helper functions based on the action enum.
    @mcp.tool(name="android-log")
    async def android_log(
        serial: str,
        action: LogAction,
        ctx: Context,
        package: str | None = None,
        lines: int = 1000,
        filter_expr: str = "",
        buffer: str = "main",
        format_type: str = "threadtime",
        max_size: int | None = 100000,
    ) -> str:
        """
        Perform various log retrieval operations on an Android device.
    
        This single tool consolidates various log-related actions.
        The 'action' parameter determines the operation.
    
        Args:
            serial: Device serial number.
            action: The specific log operation to perform.
            ctx: MCP Context for logging and interaction.
            package (Optional[str]): Package name for `get_app_logs` action.
            lines (int): Number of lines to fetch for logcat actions (default: 1000).
            filter_expr (Optional[str]): Logcat filter expression for `get_device_logcat`.
            buffer (Optional[str]): Logcat buffer for `get_device_logcat` (default: "main").
            format_type (Optional[str]): Logcat output format for `get_device_logcat` (default: "threadtime").
            max_size (Optional[int]): Max output size for `get_device_logcat` (default: 100KB).
    
        Returns:
            A string message containing the requested logs or status.
    
        ---
        Available Actions and their specific argument usage:
    
        1.  `action="get_device_logcat"`
            - Optional: `lines`, `filter_expr`, `buffer`, `format_type`, `max_size`.
        2.  `action="get_app_logs"`
            - Requires: `package`.
            - Optional: `lines`.
        3.  `action="get_anr_logs"`
            - No specific arguments beyond `serial` and `ctx`.
        4.  `action="get_crash_logs"`
            - No specific arguments beyond `serial` and `ctx`.
        5.  `action="get_battery_stats"`
            - No specific arguments beyond `serial` and `ctx`.
        ---
        """
        try:
            if action == LogAction.GET_APP_LOGS and package is None:
                return "❌ Error: 'package' is required for action 'get_app_logs'."
    
            if action == LogAction.GET_DEVICE_LOGCAT:
                return await _get_device_logcat_impl(serial, ctx, lines, filter_expr, buffer, format_type, max_size)
            if action == LogAction.GET_APP_LOGS:
                return await _get_app_logs_impl(serial, package, ctx, lines)  # type: ignore
            if action == LogAction.GET_ANR_LOGS:
                return await _get_anr_logs_impl(serial, ctx)
            if action == LogAction.GET_CRASH_LOGS:
                return await _get_crash_logs_impl(serial, ctx)
            if action == LogAction.GET_BATTERY_STATS:
                return await _get_battery_stats_impl(serial, ctx)
    
            valid_actions = ", ".join([la.value for la in LogAction])
            logger.error("Invalid log action '%s' received. Valid actions are: %s.", action, valid_actions)
            return f"❌ Error: Unknown log action '{action}'. Valid actions are: {valid_actions}."
    
        except Exception as e:
            logger.exception("Unexpected error during log operation %s for serial '%s': %s", action, serial, e)
            return f"❌ Error: An unexpected error occurred during '{action.value}': {e!s}"
  • Enum type definition for the 'action' input parameter, specifying the sub-operations supported by the android-log tool.
    class LogAction(str, Enum):
        """Defines the available sub-actions for the 'android-log' tool."""
    
        GET_DEVICE_LOGCAT = "get_device_logcat"
        GET_APP_LOGS = "get_app_logs"
        GET_ANR_LOGS = "get_anr_logs"
        GET_CRASH_LOGS = "get_crash_logs"
        GET_BATTERY_STATS = "get_battery_stats"
  • Key helper function used by the handler to execute logcat commands on the Android device with filtering, buffering, and truncation options.
    async def _get_filtered_logcat(
        device: Any,
        filter_expr: str,
        lines: int = 1000,
        buffer: str = "main",
        format_type: str = "threadtime",
        max_size: int | None = 100000,
    ) -> str:
        """
        Helper function to get filtered logcat output in a consistent format.
    
        Args:
            device: Device instance
            filter_expr: Optional filter expression for logcat
            lines: Number of recent lines to fetch
            buffer: Logcat buffer to use (main, system, crash, etc.)
            format_type: Format for logcat output
            max_size: Maximum output size in characters
    
        Returns:
            Formatted logcat output
        """
        try:
            # Build logcat command
            cmd = ["logcat", "-d", "-v", format_type]
    
            # Specify buffer if not main
            if buffer != "main":
                cmd.extend(["-b", buffer])
    
            # Add line limit if specified
            if lines > 0:
                cmd.extend(["-t", str(lines)])
    
            # Add filter if specified
            if filter_expr:
                cmd.extend(filter_expr.split())
    
            # Join command parts
            logcat_cmd = " ".join(cmd)
    
            # Get logcat output
            output = await device.run_shell(logcat_cmd)
    
            # Truncate if needed
            if max_size and len(output) > max_size:
                output = output[:max_size] + "\n... [Output truncated due to size limit]"
    
            return output
        except Exception as e:
            logger.exception("Error getting logcat output")
            return f"Error retrieving logcat output: {e!s}"
  • Implementation helper for 'get_device_logcat' action, formats and retrieves device logcat output.
    async def _get_device_logcat_impl(
        serial: str,
        ctx: Context,
        lines: int = 1000,
        filter_expr: str = "",
        buffer: str = "main",
        format_type: str = "threadtime",
        max_size: int | None = 100000,
    ) -> str:
        """
        Get logcat output from a device with flexible filtering options.
    
        Args:
            serial: Device serial number
            lines: Number of recent lines to fetch (default: 1000)
                   Higher values may impact performance and context window limits.
            filter_expr: Optional filter expression (e.g., "ActivityManager:I *:S")
                         Use to focus on specific tags or priority levels
            buffer: Logcat buffer to use (main, system, crash, radio, events, etc.)
            format_type: Format for logcat output (threadtime, brief, tag, process, etc.)
            max_size: Maximum output size in characters (default: 100000)
                      Set to None for unlimited (not recommended)
    
        Returns:
            Recent logcat entries in markdown format
        """
        device = await get_device_manager().get_device(serial)
        if device is None:
            return f"Error: Device {serial} not found."
    
        await ctx.info(f"Retrieving logcat from device {serial} (buffer: {buffer})...")
    
        try:
            output = await _get_filtered_logcat(device, filter_expr, lines, buffer, format_type, max_size)
    
            # Format the output
            result = ["# Device Logcat Output 📱\n"]
            result.append(f"## Last {lines} Lines from '{buffer}' Buffer")
            if filter_expr:
                result.append(f"\nFilter: `{filter_expr}`")
            result.append("\n```log")
            result.append(output)
            result.append("```")
    
            return "\n".join(result)
    
        except Exception as e:
            logger.exception("Error getting logcat output in _get_device_logcat_impl")
            return f"Error retrieving logcat output: {e!s}"

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hyperb1iss/droidmind'

If you have feedback or need assistance with the MCP directory API, please join our Discord server