Skip to main content
Glama

android-file

Manage files on Android devices through DroidMind. Perform operations like upload, download, delete, create directories, check existence, read, write, and get file statistics.

Instructions

Perform file and directory operations on an Android device.

This single tool consolidates various file system actions. The 'action' parameter determines the operation.

Args: serial: Device serial number. action: The specific file operation to perform. See available actions below. ctx: MCP Context for logging and interaction. path (Optional[str]): General path argument on the device. Used by: list_directory, delete_file, create_directory, file_exists, file_stats. Can also be used by read_file and write_file as an alternative to 'device_path'. local_path (Optional[str]): Path on the DroidMind server machine. Used by: push_file (source), pull_file (destination). device_path (Optional[str]): Path on the Android device. Used by: push_file (destination), pull_file (source), read_file (source), write_file (destination). If 'path' is also provided for read/write, 'device_path' takes precedence. content (Optional[str]): Text content to write. Used by: write_file. max_size (Optional[int]): Maximum file size in bytes for read_file (default: 100KB). Used by: read_file.

Returns: Union[str, bool]: A string message indicating the result or status for most actions. Returns a boolean for the 'file_exists' action.


Available Actions and their specific argument usage:

  1. action="list_directory": Lists contents of a directory.

    • Requires: path (directory path on device).

    • Returns: Formatted string of directory contents.

  2. action="push_file": Uploads a file from the local server to the device.

    • Requires: local_path (source on server), device_path (destination on device).

    • Returns: String message confirming upload.

  3. action="pull_file": Downloads a file from the device to the local server.

    • Requires: device_path (source on device), local_path (destination on server).

    • Returns: String message confirming download.

  4. action="delete_file": Deletes a file or directory from the device.

    • Requires: path (path to delete on device).

    • Returns: String message confirming deletion.

  5. action="create_directory": Creates a directory on the device.

    • Requires: path (directory path to create on device).

    • Returns: String message confirming creation.

  6. action="file_exists": Checks if a file or directory exists on the device.

    • Requires: path (path to check on device).

    • Returns: True if exists, False otherwise.

  7. action="read_file": Reads the contents of a file from the device.

    • Requires: device_path (or path) for the file on device.

    • Optional: max_size (defaults to 100KB).

    • Returns: String containing file contents or error message.

  8. action="write_file": Writes text content to a file on the device.

    • Requires: device_path (or path) for the file on device, content (text to write).

    • Returns: String message confirming write.

  9. action="file_stats": Gets detailed statistics for a file or directory.

    • Requires: path (path on device).

    • Returns: Markdown-formatted string of file/directory statistics.


Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serialYes
actionYes
pathNo
local_pathNo
device_pathNo
contentNo
max_sizeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main execution handler for the 'android-file' MCP tool. Decorated with @mcp.tool(name="android-file"), it dispatches file operations (list, push, pull, delete, etc.) based on the 'action' parameter to internal helper functions, using the connected Android device.
    @mcp.tool(name="android-file")
    async def file_operations(
        serial: str,
        action: FileAction,
        ctx: Context,
        path: str | None = None,
        local_path: str | None = None,
        device_path: str | None = None,
        content: str | None = None,
        max_size: int | None = 100000,  # Default from original read_file
    ) -> str | bool:
        """
        Perform file and directory operations on an Android device.
    
        This single tool consolidates various file system actions.
        The 'action' parameter determines the operation.
    
        Args:
            serial: Device serial number.
            action: The specific file operation to perform. See available actions below.
            ctx: MCP Context for logging and interaction.
            path (Optional[str]): General path argument on the device.
                                   Used by: list_directory, delete_file, create_directory, file_exists, file_stats.
                                   Can also be used by read_file and write_file as an alternative to 'device_path'.
            local_path (Optional[str]): Path on the DroidMind server machine.
                                        Used by: push_file (source), pull_file (destination).
            device_path (Optional[str]): Path on the Android device.
                                         Used by: push_file (destination), pull_file (source), read_file (source),
                                         write_file (destination).
                                         If 'path' is also provided for read/write, 'device_path' takes precedence.
            content (Optional[str]): Text content to write.
                                     Used by: write_file.
            max_size (Optional[int]): Maximum file size in bytes for read_file (default: 100KB).
                                      Used by: read_file.
    
        Returns:
            Union[str, bool]: A string message indicating the result or status for most actions.
                              Returns a boolean for the 'file_exists' action.
    
        ---
        Available Actions and their specific argument usage:
    
        1.  `action="list_directory"`: Lists contents of a directory.
            - Requires: `path` (directory path on device).
            - Returns: Formatted string of directory contents.
    
        2.  `action="push_file"`: Uploads a file from the local server to the device.
            - Requires: `local_path` (source on server), `device_path` (destination on device).
            - Returns: String message confirming upload.
    
        3.  `action="pull_file"`: Downloads a file from the device to the local server.
            - Requires: `device_path` (source on device), `local_path` (destination on server).
            - Returns: String message confirming download.
    
        4.  `action="delete_file"`: Deletes a file or directory from the device.
            - Requires: `path` (path to delete on device).
            - Returns: String message confirming deletion.
    
        5.  `action="create_directory"`: Creates a directory on the device.
            - Requires: `path` (directory path to create on device).
            - Returns: String message confirming creation.
    
        6.  `action="file_exists"`: Checks if a file or directory exists on the device.
            - Requires: `path` (path to check on device).
            - Returns: `True` if exists, `False` otherwise.
    
        7.  `action="read_file"`: Reads the contents of a file from the device.
            - Requires: `device_path` (or `path`) for the file on device.
            - Optional: `max_size` (defaults to 100KB).
            - Returns: String containing file contents or error message.
    
        8.  `action="write_file"`: Writes text content to a file on the device.
            - Requires: `device_path` (or `path`) for the file on device, `content` (text to write).
            - Returns: String message confirming write.
    
        9.  `action="file_stats"`: Gets detailed statistics for a file or directory.
            - Requires: `path` (path on device).
            - Returns: Markdown-formatted string of file/directory statistics.
        ---
        """
        # Declare here so it's always bound for exception logging
        _effective_device_path: str | None = None
        try:
            # Initialize _effective_device_path early for robust logging
            _effective_device_path = device_path if device_path is not None else path
    
            device = await get_device_manager().get_device(serial)
            if not device:
                if action == FileAction.FILE_EXISTS:
                    logger.warning("Device %s not found for file_exists check.", serial)
                    return False
                return f"❌ Error: Device {serial} not found or not connected."
    
            # Use device_path if provided, otherwise fall back to path for relevant actions
            # _effective_device_path assignment moved above
    
            if action == FileAction.LIST_DIRECTORY:
                if path is None:
                    return "❌ Error: 'path' is required for list_directory."
                return await _list_directory_impl(device, path, ctx)
            if action == FileAction.PUSH_FILE:
                if local_path is None or device_path is None:
                    return "❌ Error: 'local_path' and 'device_path' are required for push_file."
                return await _push_file_impl(device, local_path, device_path, ctx)
            if action == FileAction.PULL_FILE:
                if device_path is None or local_path is None:
                    return "❌ Error: 'device_path' and 'local_path' are required for pull_file."
                return await _pull_file_impl(device, device_path, local_path, ctx)
            if action == FileAction.DELETE_FILE:
                if path is None:
                    return "❌ Error: 'path' is required for delete_file."
                return await _delete_file_impl(device, path, ctx)
            if action == FileAction.CREATE_DIRECTORY:
                if path is None:
                    return "❌ Error: 'path' is required for create_directory."
                return await _create_directory_impl(device, path, ctx)
            if action == FileAction.FILE_EXISTS:
                if path is None:
                    return "❌ Error: 'path' is required for file_exists."
                return await _file_exists_impl(device, path, ctx)
            if action == FileAction.READ_FILE:
                if _effective_device_path is None:
                    return "❌ Error: 'device_path' or 'path' is required for read_file."
                return await _read_file_impl(device, _effective_device_path, ctx, max_size or 100000)
            if action == FileAction.WRITE_FILE:
                if _effective_device_path is None or content is None:
                    return "❌ Error: ('device_path' or 'path') and 'content' are required for write_file."
                return await _write_file_impl(device, _effective_device_path, content, ctx)
            if action == FileAction.FILE_STATS:
                if path is None:
                    return "❌ Error: 'path' is required for file_stats."
                return await _file_stats_impl(device, path, ctx)
    
            # Default case for invalid actions
            valid_actions = ", ".join([act.value for act in FileAction])
            logger.error("Invalid file action '%s' received. Valid actions are: %s", action, valid_actions)
            return f"❌ Error: Unknown file action '{action}'. Valid actions are: {valid_actions}."
    
        except ValueError as ve:
            logger.warning("ValueError during file operation %s for device %s: %s", action, serial, ve)
            if action == FileAction.FILE_EXISTS:
                return False
            return f"❌ Error: {ve}"
        except Exception as e:
            # Log with a fallback for _effective_device_path if necessary
            log_path_info = _effective_device_path if _effective_device_path is not None else "[path not determinable]"
            logger.exception(
                "Unexpected error during file operation %s on %s with path/device_path '%s': %s",
                action,
                serial,
                log_path_info,
                e,
            )
            if action == FileAction.FILE_EXISTS:
                return False
            return f"❌ Error: An unexpected error occurred: {e!s}"
  • Type definition (Enum) for the 'action' parameter, defining all supported sub-operations of the android-file tool. Serves as input schema validation.
    class FileAction(str, Enum):
        """Defines the available sub-commands for the 'android-file' tool."""
    
        LIST_DIRECTORY = "list_directory"
        PUSH_FILE = "push_file"
        PULL_FILE = "pull_file"
        DELETE_FILE = "delete_file"
        CREATE_DIRECTORY = "create_directory"
        FILE_EXISTS = "file_exists"
        READ_FILE = "read_file"
        WRITE_FILE = "write_file"
        FILE_STATS = "file_stats"
  • MCP tool registration decorator applied to the handler function, naming it 'android-file'.
    @mcp.tool(name="android-file")
  • Helper function for LIST_DIRECTORY action: lists and formats directory contents.
    async def _list_directory_impl(device: "Device", path: str, ctx: Context) -> str:
        """Implementation for listing directory contents."""
        if ctx:
            await ctx.info(f"Listing directory {path}...")
    
        dir_resource = DirectoryResource(path, device)
        contents = await dir_resource.list_contents()
    
        formatted_output = f"# 📁 Directory: {path}\n\n"
        files = [item for item in contents if item.__class__.__name__ == "FileResource"]
        dirs = [item for item in contents if item.__class__.__name__ == "DirectoryResource"]
    
        formatted_output += f"**{len(files)} files, {len(dirs)} directories**\n\n"
    
        if dirs:
            formatted_output += "## Directories\n\n"
            for dir_item in sorted(dirs, key=lambda x: x.name):
                formatted_output += f"📁 `{dir_item.name}`\n"
            formatted_output += "\n"
    
        if files:
            formatted_output += "## Files\n\n"
            for file_item in sorted(files, key=lambda x: x.name):
                size_str = file_item.to_dict().get("size", "unknown")
                formatted_output += f"📄 `{file_item.name}` ({size_str})\n"
    
        return formatted_output
  • Helper function for PUSH_FILE action: uploads local file to device.
    async def _push_file_impl(device: "Device", local_path: str, device_path: str, ctx: Context) -> str:
        """Implementation for uploading a file."""
        if not os.path.exists(local_path):
            return f"❌ Error: Local file {local_path} does not exist."
    
        size = os.path.getsize(local_path)
        size_str = format_file_size(size)
    
        if ctx:
            await ctx.info(f"Pushing file {os.path.basename(local_path)} ({size_str}) to {device_path}...")
    
        result = await device.push_file(local_path, device_path)
        return f"""
    # ✅ File Uploaded Successfully
    
    The file `{os.path.basename(local_path)}` ({size_str}) has been uploaded to `{device_path}` on device {device.serial}.
    
    **Details**: {result}
    """
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 the multi-action nature of the tool, specifying which parameters are required for each action, describing precedence rules (device_path over path), default values (max_size defaults to 100KB), and return types (string or boolean). It doesn't mention error handling, permissions, or rate limits, but provides substantial operational context.

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 (overview, args, returns, action details) and uses bullet points effectively. While comprehensive, it's appropriately sized for a 7-parameter multi-action tool. Some redundancy exists (e.g., repeating parameter usage in both the Args section and action details), but overall information density is high.

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 (7 parameters, 9 possible actions, no annotations, 0% schema coverage), the description provides complete operational context. It covers all parameters, all actions, return types, precedence rules, and default values. The existence of an output schema means the description doesn't need to detail return value structures, and it appropriately focuses on usage semantics.

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 detailed parameter semantics. It explains all 7 parameters, their purposes, which actions they're used for, optional/required status, precedence rules, and default values. The action-by-action breakdown gives precise context for parameter usage beyond what the bare schema provides.

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 as 'Perform file and directory operations on an Android device' with the specific verb 'perform' and resource 'file and directory operations'. It distinguishes itself from sibling tools like android-app, android-device, etc. by focusing exclusively on file system operations.

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

Usage Guidelines3/5

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

The description implies usage through the action parameter breakdown, showing when different parameters are needed for each action. However, it doesn't provide explicit guidance on when to choose this tool versus other Android tools like android-shell for file operations, nor does it mention any prerequisites or exclusions.

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