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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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}"
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It does well by explaining this is a 'retrieval' operation (implying read-only), listing all available actions with their specific argument requirements, and providing default values for parameters. However, it doesn't mention potential side effects like device performance impact or permission requirements.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections: purpose statement, parameter explanation, return value, and detailed action breakdown. While comprehensive, some redundancy exists (e.g., repeating default values in both the Args section and action list). Every sentence serves a purpose in clarifying this multi-action tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (8 parameters, 5 distinct actions), no annotations, and 0% schema description coverage, the description provides complete contextual information. It explains the multi-action nature, documents all parameters with defaults, specifies action-specific requirements, and mentions the return format - adequately compensating for the lack of structured metadata.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description fully compensates by providing comprehensive parameter documentation. It explains the purpose of the 'action' parameter, lists all available actions, specifies required vs. optional arguments for each action, documents default values, and clarifies argument usage patterns - adding significant value beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Perform various log retrieval operations on an Android device.' It specifies the verb ('retrieval operations'), resource ('Android device logs'), and scope ('various'), distinguishing it from siblings like android-file or android-shell that handle different device operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool versus alternatives: it consolidates 'various log-related actions' under one tool, with the 'action' parameter determining the specific operation. The detailed action list shows exactly which operations are available, preventing confusion with other Android tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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