Skip to content

Mobile MCP: let AI agents drive your iOS and Android apps. MCP server for simulators, emulators and real devices. Works with Claude Code, Codex, Cursor and any MCP client.

feat: scale screenshots natively via mobilecli, drop sips/imagemagick (#418)

Gil Megidish86687b17e843
diff --git a/src/image-utils.ts b/src/image-utils.ts
deleted file mode 100644
index e4ce545..0000000
--- a/src/image-utils.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { execFileSync, spawnSync } from "child_process";
-import os from "node:os";
-import fs from "node:fs";
-import path from "node:path";
-import { trace } from "./logger";
-
-const DEFAULT_JPEG_QUALITY = 75;
-
-export class ImageTransformer {
-
- private newWidth: number = 0;
- private newFormat: "jpg" | "png" = "png";
- private jpegOptions: { quality: number } = { quality: DEFAULT_JPEG_QUALITY };
-
- constructor(private buffer: Buffer) {}
-
- public resize(width: number): ImageTransformer {
- this.newWidth = width;
- return this;
- }
-
- public jpeg(options: { quality: number }): ImageTransformer {
- this.newFormat = "jpg";
- this.jpegOptions = options;
- return this;
- }
-
- public png(): ImageTransformer {
- this.newFormat = "png";
- return this;
- }
-
- public toBuffer(): Buffer {
- if (isSipsInstalled()) {
- try {
- return this.toBufferWithSips();
- } catch (error) {
- trace(`Sips failed, falling back to ImageMagick: ${error}`);
- }
- }
-
- try {
- return this.toBufferWithImageMagick();
- } catch (error) {
- trace(`ImageMagick failed: ${error}`);
- throw new Error("Image scaling unavailable (requires Sips or ImageMagick).");
- }
- }
-
- private qualityToSips(q: number): "low" | "normal" | "high" | "best" {
- if (q >= 90) {
- return "best";
- }
-
- if (q >= 75) {
- return "high";
- }
-
- if (q >= 50) {
- return "normal";
- }
-
- return "low";
- }
-
- private toBufferWithSips(): Buffer {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "image-"));
- const inputFile = path.join(tempDir, "input");
- const outputFile = path.join(tempDir, `output.${this.newFormat === "jpg" ? "jpg" : "png"}`);
-
- try {
- fs.writeFileSync(inputFile, this.buffer);
-
- const args = ["-s", "format", this.newFormat === "jpg" ? "jpeg" : "png"];
- if (this.newFormat === "jpg") {
- args.push("-s", "formatOptions", this.qualityToSips(this.jpegOptions.quality));
- }
-
- args.push("-Z", `${this.newWidth}`);
- args.push("--out", outputFile);
- args.push(inputFile);
-
- trace(`Running sips command: /usr/bin/sips ${args.join(" ")}`);
- const proc = spawnSync("/usr/bin/sips", args, {
- maxBuffer: 8 * 1024 * 1024
- });
-
- if (proc.status !== 0) {
- throw new Error(`Sips failed with status ${proc.status}`);
- }
-
- const outputBuffer = fs.readFileSync(outputFile);
- trace("Sips returned buffer of size: " + outputBuffer.length);
- return outputBuffer;
- } finally {
- try {
- fs.rmSync(tempDir, { recursive: true, force: true });
- } catch (error) {
- // Ignore cleanup errors
- }
- }
- }
-
- private toBufferWithImageMagick(): Buffer {
- const magickArgs = ["-", "-resize", `${this.newWidth}x`, "-quality", `${this.jpegOptions.quality}`, `${this.newFormat}:-`];
- trace(`Running magick command: magick ${magickArgs.join(" ")}`);
-
- const proc = spawnSync("magick", magickArgs, {
- maxBuffer: 8 * 1024 * 1024,
- input: this.buffer
- });
-
- return proc.stdout;
- }
-}
-
-export class Image {
- constructor(private buffer: Buffer) {}
-
- public static fromBuffer(buffer: Buffer): Image {
- return new Image(buffer);
- }
-
- public resize(width: number): ImageTransformer {
- return new ImageTransformer(this.buffer).resize(width);
- }
-
- public jpeg(options: { quality: number }): ImageTransformer {
- return new ImageTransformer(this.buffer).jpeg(options);
- }
-}
-
-const isDarwin = (): boolean => {
- return os.platform() === "darwin";
-};
-
-export const isSipsInstalled = (): boolean => {
- if (!isDarwin()) {
- return false;
- }
-
- try {
- execFileSync("/usr/bin/sips", ["--version"]);
- return true;
- } catch (error) {
- return false;
- }
-};
-
-export const isImageMagickInstalled = (): boolean => {
- try {
- return execFileSync("magick", ["--version"])
- .toString()
- .split("\n")
- .filter(line => line.includes("Version: ImageMagick"))
- .length > 0;
- } catch (error) {
- return false;
- }
-};
-
-export const isScalingAvailable = (): boolean => {
- return isImageMagickInstalled() || isSipsInstalled();
-};
diff --git a/src/mobile-device.ts b/src/mobile-device.ts
index e5b5dda..8758b5d 100644
--- a/src/mobile-device.ts
+++ b/src/mobile-device.ts
@@ -1,5 +1,5 @@
import { Mobilecli } from "./mobilecli";
-import { Button, InstalledApp, Orientation, Robot, ScreenElement, ScreenSize, SwipeDirection } from "./robot";
+import { Button, InstalledApp, Orientation, Robot, ScreenElement, ScreenSize, ScreenshotOptions, SwipeDirection } from "./robot";
interface InstalledAppsResponse {
status: "ok",
@@ -178,8 +178,21 @@ export class MobileDevice implements Robot {
this.runCommand(["io", "swipe", `${Math.round(x)},${Math.round(y)},${Math.round(endX)},${Math.round(endY)}`]);
}
- public async getScreenshot(): Promise<Buffer> {
- const fullArgs = ["screenshot", "--device", this.deviceId, "--format", "png", "--output", "-"];
+ public async getScreenshot(options?: ScreenshotOptions): Promise<Buffer> {
+ const format = options?.format || "png";
+ const fullArgs = ["screenshot", "--device", this.deviceId, "--format", format, "--output", "-"];
+ if (format === "jpeg" && options?.quality !== undefined) {
+ fullArgs.push("--quality", `${options.quality}`);
+ }
+
+ if (options?.maxSize !== undefined) {
+ fullArgs.push("--max-size", `${options.maxSize}`);
+ }
+
+ if (options?.scale !== undefined && options.scale !== 1) {
+ fullArgs.push("--scale", `${options.scale}`);
+ }
+
return this.mobilecli.executeCommandBuffer(fullArgs);
}
diff --git a/src/robot.ts b/src/robot.ts
index 14b0de6..bee9b08 100644
--- a/src/robot.ts
+++ b/src/robot.ts
@@ -51,6 +51,13 @@ export class ActionableError extends Error {
export type Orientation = "portrait" | "landscape";
+export interface ScreenshotOptions {
+ format?: "png" | "jpeg";
+ quality?: number;
+ scale?: number;
+ maxSize?: number;
+}
+
export interface Robot {
/**
* Get the screen size of the device in pixels.
@@ -68,10 +75,11 @@ export interface Robot {
swipeFromCoordinate(x: number, y: number, direction: SwipeDirection, distance?: number): Promise<void>;
/**
- * Get a screenshot of the screen. Returns a Buffer that contains
- * a PNG image of the screen. Will be same dimensions as getScreenSize().
+ * Get a screenshot of the screen. Returns a PNG image by default.
+ * Robots that support it may honor options (format, quality, scale,
+ * maxSize); others ignore them and return a full-size PNG.
*/
- getScreenshot(): Promise<Buffer>;
+ getScreenshot(options?: ScreenshotOptions): Promise<Buffer>;
/**
* List all installed apps on the device. Returns an array of package names (or
diff --git a/src/server.ts b/src/server.ts
index 1b70976..5ebcec6 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -8,10 +8,9 @@ import { ChildProcess } from "node:child_process";
import { error, trace } from "./logger";
import { AndroidRobot, AndroidDeviceManager } from "./android";
-import { ActionableError, Robot } from "./robot";
+import { ActionableError, Robot, ScreenshotOptions } from "./robot";
import { IosManager, IosRobot } from "./ios";
import { PNG } from "./png";
-import { isScalingAvailable, Image } from "./image-utils";
import { Mobilecli } from "./mobilecli";
import { MobileDevice } from "./mobile-device";
import { validateOutputPath, validateFileExtension } from "./utils";
@@ -22,6 +21,7 @@ const MAX_DEVICE_LOG_ENTRIES = 10000;
const DEVICE_LOG_TIMEOUT_MS = 30000;
const DEVICE_LOG_FILTER_PATTERN = /^(pid|process|tag|level|subsystem|category|message)!?=.+$/;
const ALLOWED_SCREENSHOT_EXTENSIONS = [".png", ".jpg", ".jpeg"];
+const DEFAULT_SCREENSHOT_MAX_SIZE = 1024;
const ALLOWED_RECORDING_EXTENSIONS = [".mp4"];
const LOGIN_PROMPT_TIMEOUT_MS = 15000;
@@ -762,15 +762,25 @@ export const createMcpServer = (): McpServer => {
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
saveTo: z.string().describe("The path to save the screenshot to. Filename must end with .png, .jpg, or .jpeg"),
+ maxSize: z.number().int().positive().optional().describe("Maximum width/height in pixels, keeping aspect ratio. Omit for full size."),
+ scale: z.number().gt(0).max(1).optional().describe("Scale factor (0.0-1.0). Ignored if maxSize is provided."),
},
{ readOnlyHint: false, destructiveHint: false, openWorldHint: false },
- async ({ device, saveTo }) => {
+ async ({ device, saveTo, maxSize, scale }) => {
validateFileExtension(saveTo, ALLOWED_SCREENSHOT_EXTENSIONS, "save_screenshot");
validateOutputPath(saveTo);
const robot = getRobotFromDevice(device);
- const screenshot = await robot.getScreenshot();
+ const format = saveTo.toLowerCase().endsWith(".png") ? "png" : "jpeg";
+ const screenshot = await robot.getScreenshot({ format, maxSize, scale });
+
+ // legacy robots ignore the requested format and always return a png
+ const isPng = screenshot.length > 0 && screenshot[0] === 0x89;
+ if (format === "jpeg" && isPng) {
+ throw new ActionableError("This device only supports png screenshots, save to a .png file instead.");
+ }
+
fs.writeFileSync(saveTo, screenshot);
return `Screenshot saved to: ${saveTo}`;
}
@@ -782,40 +792,44 @@ export const createMcpServer = (): McpServer => {
title: "Take Screenshot",
description: "Take a screenshot of the mobile device. Use this to understand what's on screen, if you need to press an element that is available through view hierarchy then you must list elements on screen instead. Do not cache this result.",
inputSchema: {
- device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
+ device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
+ maxSize: z.number().int().positive().optional().describe(`Maximum width/height in pixels, keeping aspect ratio. Defaults to ${DEFAULT_SCREENSHOT_MAX_SIZE}.`),
+ scale: z.number().gt(0).max(1).optional().describe("Scale factor (0.0-1.0). Ignored if maxSize is provided."),
},
annotations: {
readOnlyHint: true,
openWorldHint: true,
},
},
- async ({ device }) => {
+ async ({ device, maxSize, scale }) => {
try {
const robot = getRobotFromDevice(device);
- const screenSize = await robot.getScreenSize();
- let screenshot = await robot.getScreenshot();
- let mimeType = "image/png";
-
- // validate we received a png, will throw exception otherwise
- const image = new PNG(screenshot);
- const pngSize = image.getDimensions();
- if (pngSize.width <= 0 || pngSize.height <= 0) {
- throw new ActionableError("Screenshot is invalid. Please try again.");
+ // mobilecli scales and converts natively; legacy robots ignore the options and return a full-size png
+ // maxSize wins over scale (same precedence as mobilecli); the default applies only when neither is given
+ const options: ScreenshotOptions = { format: "jpeg", quality: 75 };
+ if (maxSize !== undefined) {
+ options.maxSize = maxSize;
+ } else if (scale !== undefined) {
+ options.scale = scale;
+ } else {
+ options.maxSize = DEFAULT_SCREENSHOT_MAX_SIZE;
}
- if (isScalingAvailable()) {
- trace("Image scaling is available, resizing screenshot");
- const image = Image.fromBuffer(screenshot);
- const beforeSize = screenshot.length;
- screenshot = image.resize(Math.floor(pngSize.width / screenSize.scale))
- .jpeg({ quality: 75 })
- .toBuffer();
+ const screenshot = await robot.getScreenshot(options);
- const afterSize = screenshot.length;
- trace(`Screenshot resized from ${beforeSize} bytes to ${afterSize} bytes`);
+ const isJpeg = screenshot.length > 2 && screenshot[0] === 0xff && screenshot[1] === 0xd8;
+ let mimeType = "image/jpeg";
+ if (!isJpeg) {
+ mimeType = "image/png";
+
+ // validate we received a png, will throw exception otherwise
+ const image = new PNG(screenshot);
+ const pngSize = image.getDimensions();
+ if (pngSize.width <= 0 || pngSize.height <= 0) {
+ throw new ActionableError("Screenshot is invalid. Please try again.");
+ }
- mimeType = "image/jpeg";
}
const screenshot64 = screenshot.toString("base64");
@@ -824,8 +838,6 @@ export const createMcpServer = (): McpServer => {
"ToolName": "mobile_take_screenshot",
"ScreenshotFilesize": screenshot64.length,
"ScreenshotMimeType": mimeType,
- "ScreenshotWidth": pngSize.width,
- "ScreenshotHeight": pngSize.height,
}).then();
return {