Skip to main content
Glama

android-screenshot

Capture a screenshot from an Android device by providing its serial number and optional JPEG quality setting. Returns the device screenshot as an image.

Instructions

Get a screenshot from a device.

Args: serial: Device serial number ctx: MCP context quality: JPEG quality (1-100, lower means smaller file size)

Returns: The device screenshot as an image

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serialYes
qualityNo

Implementation Reference

  • The MCP tool 'android-screenshot' is registered via the @mcp.tool(name="android-screenshot") decorator on the async function 'screenshot'. This file contains both the registration and the full handler implementation.
    """
    Media Tools - MCP tools for capturing media from Android devices.
    
    This module provides MCP tools for capturing screenshots and other media from Android devices.
    """
    
    import io
    
    from mcp.server.fastmcp import Context, Image
    from PIL import Image as PILImage, UnidentifiedImageError
    
    from droidmind.context import mcp
    from droidmind.devices import get_device_manager
    from droidmind.log import logger
    
    
    @mcp.tool(name="android-screenshot")
    async def screenshot(serial: str, ctx: Context, quality: int = 75) -> Image:
        """
        Get a screenshot from a device.
    
        Args:
            serial: Device serial number
            ctx: MCP context
            quality: JPEG quality (1-100, lower means smaller file size)
    
        Returns:
            The device screenshot as an image
        """
        try:
            # Get the device
            device = await get_device_manager().get_device(serial)
            if not device:
                await ctx.error(f"Device {serial} not connected or not found.")
                return Image(data=b"", format="png")
    
            # Take a screenshot using the Device abstraction
            await ctx.info(f"Capturing screenshot from device {serial}...")
            screenshot_data = await device.take_screenshot()
    
            # Check if we're in a test environment (FAKE_SCREENSHOT_DATA is a marker used in tests)
            if screenshot_data == b"FAKE_SCREENSHOT_DATA":
                await ctx.info("Using test screenshot data")
                return Image(data=screenshot_data, format="png")
    
            # Validate we have real image data to convert
            if not screenshot_data or len(screenshot_data) < 100:  # A real PNG should be larger than this
                await ctx.error("Invalid or empty screenshot data received")
                return Image(data=screenshot_data, format="png")
    
            try:
                # Convert PNG to JPEG to reduce size
                await ctx.info(f"Converting screenshot to JPEG (quality: {quality})...")
                buffer = io.BytesIO()
    
                # Load the PNG data into a PIL Image
                with PILImage.open(io.BytesIO(screenshot_data)) as img:
                    # Convert to RGB (removing alpha channel if present) and save as JPEG
                    converted_img = img.convert("RGB") if img.mode == "RGBA" else img
                    converted_img.save(buffer, format="JPEG", quality=quality, optimize=True)
                    jpeg_data = buffer.getvalue()
    
                # Get size reduction info for logging
                png_size = len(screenshot_data) / 1024
                jpg_size = len(jpeg_data) / 1024
                reduction = 100 - (jpg_size / png_size * 100) if png_size > 0 else 0
    
                await ctx.info(
                    f"Screenshot converted successfully: {png_size:.1f}KB → {jpg_size:.1f}KB ({reduction:.1f}% reduction)"
                )
                return Image(data=jpeg_data, format="jpeg")
            except UnidentifiedImageError:
                # If we can't parse the image data, return it as-is
                logger.warning("Could not identify image data, returning unprocessed")
                return Image(data=screenshot_data, format="png")
        except Exception as e:
            logger.exception("Error capturing screenshot: %s", e)
            await ctx.error(f"Error capturing screenshot: {e!s}")
            return Image(data=b"", format="png")
  • The handler function 'screenshot' implements the tool logic: gets a device by serial, takes a screenshot via device.take_screenshot(), converts PNG to JPEG with configurable quality, and returns an Image object. It handles test data, invalid images, and errors.
    @mcp.tool(name="android-screenshot")
    async def screenshot(serial: str, ctx: Context, quality: int = 75) -> Image:
        """
        Get a screenshot from a device.
    
        Args:
            serial: Device serial number
            ctx: MCP context
            quality: JPEG quality (1-100, lower means smaller file size)
    
        Returns:
            The device screenshot as an image
        """
        try:
            # Get the device
            device = await get_device_manager().get_device(serial)
            if not device:
                await ctx.error(f"Device {serial} not connected or not found.")
                return Image(data=b"", format="png")
    
            # Take a screenshot using the Device abstraction
            await ctx.info(f"Capturing screenshot from device {serial}...")
            screenshot_data = await device.take_screenshot()
    
            # Check if we're in a test environment (FAKE_SCREENSHOT_DATA is a marker used in tests)
            if screenshot_data == b"FAKE_SCREENSHOT_DATA":
                await ctx.info("Using test screenshot data")
                return Image(data=screenshot_data, format="png")
    
            # Validate we have real image data to convert
            if not screenshot_data or len(screenshot_data) < 100:  # A real PNG should be larger than this
                await ctx.error("Invalid or empty screenshot data received")
                return Image(data=screenshot_data, format="png")
    
            try:
                # Convert PNG to JPEG to reduce size
                await ctx.info(f"Converting screenshot to JPEG (quality: {quality})...")
                buffer = io.BytesIO()
    
                # Load the PNG data into a PIL Image
                with PILImage.open(io.BytesIO(screenshot_data)) as img:
                    # Convert to RGB (removing alpha channel if present) and save as JPEG
                    converted_img = img.convert("RGB") if img.mode == "RGBA" else img
                    converted_img.save(buffer, format="JPEG", quality=quality, optimize=True)
                    jpeg_data = buffer.getvalue()
    
                # Get size reduction info for logging
                png_size = len(screenshot_data) / 1024
                jpg_size = len(jpeg_data) / 1024
                reduction = 100 - (jpg_size / png_size * 100) if png_size > 0 else 0
    
                await ctx.info(
                    f"Screenshot converted successfully: {png_size:.1f}KB → {jpg_size:.1f}KB ({reduction:.1f}% reduction)"
                )
                return Image(data=jpeg_data, format="jpeg")
            except UnidentifiedImageError:
                # If we can't parse the image data, return it as-is
                logger.warning("Could not identify image data, returning unprocessed")
                return Image(data=screenshot_data, format="png")
        except Exception as e:
            logger.exception("Error capturing screenshot: %s", e)
            await ctx.error(f"Error capturing screenshot: {e!s}")
            return Image(data=b"", format="png")
  • Device.take_screenshot() is the helper method called by the tool handler. It creates a temp file, delegates to ADB's capture_screenshot, reads the file bytes, cleans up, and returns raw screenshot data.
    async def take_screenshot(self) -> bytes:
        """Take a screenshot of the device.
    
        Returns:
            Screenshot data as bytes
        """
        # Create a temporary file for the screenshot
        with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp:
            screenshot_path = temp.name
    
        try:
            # Use the ADB wrapper to take a screenshot
            local_path = await self._adb.capture_screenshot(self._serial, screenshot_path)
    
            # Read the screenshot file
            async with aiofiles.open(local_path, "rb") as f:
                screenshot_data = await f.read()
    
            # Clean up the temporary file
            try:
                os.unlink(local_path)
            except OSError:
                logger.warning("Failed to remove temporary screenshot file: %s", local_path)
    
            return screenshot_data
    
        except Exception as e:
            logger.exception("Error capturing screenshot: %s", e)
            # Clean up in case of error
            with contextlib.suppress(OSError):
                os.unlink(screenshot_path)
            raise
  • ADBClient.capture_screenshot() is the low-level ADB helper that runs 'screencap -p' on the device, pulls the resulting file, and cleans up the device-side temp file.
    async def capture_screenshot(self, serial: str, local_path: str | None = None) -> str:
        """Capture a screenshot from the device.
    
        Args:
            serial: The device serial number.
            local_path: Path to save the screenshot (optional).
    
        Returns:
            Path to the saved screenshot.
    
        Raises:
            ValueError: If device is not connected.
        """
        # Check if device is connected
        devices = await self.get_devices()
        device_serials = [d["serial"] for d in devices]
    
        if serial not in device_serials:
            raise ValueError(f"Device {serial} not connected")
    
        # Generate default path if not provided
        if not local_path:
            timestamp = asyncio.get_event_loop().time()
            local_path = f"screenshot_{serial.replace(':', '_')}_{int(timestamp)}.png"
    
        # Temp path on device - use /sdcard for better compatibility
        timestamp = int(time.time())
        random_suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))  # noqa: S311
        device_path = f"/sdcard/screenshot_{timestamp}_{random_suffix}.png"
    
        try:
            # Take screenshot using screencap command
            logger.info("Taking screenshot on %s", serial)
            await self.shell(serial, f"screencap -p {device_path}")
    
            # Pull screenshot to local machine
            await self.pull_file(serial, device_path, local_path)
    
            # Clean up on device
            await self.shell(serial, f"rm {device_path}")
    
            return local_path
    
        except Exception as e:
            logger.exception("Error capturing screenshot from %s: %s", serial, e)
            raise RuntimeError(f"Screenshot capture failed: {e!s}") from e
  • Test for the android-screenshot tool. It patches the device manager, calls capture_screenshot (imported as alias from droidmind.tools.media), and verifies the Image result contains the expected fake screenshot data.
    @pytest.mark.asyncio
    @patch("droidmind.tools.media.get_device_manager")
    async def test_capture_screenshot(mock_get_device, mock_context, mock_device):
        """Test the screenshot tool."""
        # Setup mock get_device_manager to return a mock that has get_device method
        mock_manager = MagicMock()
        mock_manager.get_device = AsyncMock(return_value=mock_device)
        mock_get_device.return_value = mock_manager
    
        # Call the tool
        result = await capture_screenshot(ctx=mock_context, serial="device1")
    
        # Verify the result is an Image object with the expected data
        assert isinstance(result, Image)
        assert result.data == b"FAKE_SCREENSHOT_DATA"
    
        # Verify the context methods were called
        mock_context.info.assert_called()
        assert "Capturing screenshot" in mock_context.info.call_args_list[0][0][0]
Behavior2/5

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

No annotations are provided. The description only states it gets a screenshot but does not disclose behavioral traits such as whether the device needs to be unlocked, any side effects, or latency considerations. For a read operation, this minimal disclosure is insufficient.

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 concise and uses a structured Args/Returns format, front-loading the purpose. It is slightly verbose due to docstring conventions but remains efficient. The inclusion of 'ctx' parameter not in schema is a minor inconsistency.

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

Completeness4/5

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

Given the tool's simplicity (screenshot) and lack of output schema, the description adequately covers functionality, parameters, and return type. It could mention prerequisites like device connection, but overall completeness is satisfactory.

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

Parameters4/5

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

With 0% schema description coverage, the description adds value by explaining 'serial: Device serial number' and 'quality: JPEG quality (1-100, lower means smaller file size)'. It partially compensates for missing schema descriptions, though the 'ctx' parameter in the docstring is not in the 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 'Get a screenshot from a device,' specifying the action and resource. It distinctly separates from sibling tools like android-app, android-device, etc., which focus on other device aspects.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It does not mention contexts where a screenshot is appropriate or when to use other tools like android-shell or android-file.

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