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:
action="list_directory": Lists contents of a directory.Requires:
path(directory path on device).Returns: Formatted string of directory contents.
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.
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.
action="delete_file": Deletes a file or directory from the device.Requires:
path(path to delete on device).Returns: String message confirming deletion.
action="create_directory": Creates a directory on the device.Requires:
path(directory path to create on device).Returns: String message confirming creation.
action="file_exists": Checks if a file or directory exists on the device.Requires:
path(path to check on device).Returns:
Trueif exists,Falseotherwise.
action="read_file": Reads the contents of a file from the device.Requires:
device_path(orpath) for the file on device.Optional:
max_size(defaults to 100KB).Returns: String containing file contents or error message.
action="write_file": Writes text content to a file on the device.Requires:
device_path(orpath) for the file on device,content(text to write).Returns: String message confirming write.
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
| Name | Required | Description | Default |
|---|---|---|---|
| serial | Yes | ||
| action | Yes | ||
| path | No | ||
| local_path | No | ||
| device_path | No | ||
| content | No | ||
| max_size | No |
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"
- droidmind/tools/file_operations.py:335-335 (registration)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} """