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.

fix: record screen into a private directory and move it to the output (#510)

Gil Megidish17bd1f8024de
diff --git a/src/server.ts b/src/server.ts
index 1dadad5..348abe1 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -15,7 +15,7 @@ import { getJpegDimensions } from "./jpeg";
import { describeCoordinateMapping } from "./coordinate-mapping";
import { Mobilecli } from "./mobilecli";
import { MobileDevice } from "./mobile-device";
-import { validateOutputPath, validateFileExtension, withLowercaseScheme, writeOutputFile } from "./utils";
+import { validateOutputPath, validateFileExtension, withLowercaseScheme, writeOutputFile, createPrivateOutputPath, finishRecording } from "./utils";
import { formatElements } from "./format-elements";
type ScreenshotContent = { type: "text", text: string } | { type: "image", data: string, mimeType: string };
@@ -59,8 +59,10 @@ export const formatAvailableDevices = (devices: MobilecliDevice[]): string => {
interface ActiveRecording {
process: ChildProcess;
+ recordingPath: string;
outputPath: string;
startedAt: number;
+ moveError?: string;
}
export const getAgentVersion = (): string => {
@@ -1160,9 +1162,12 @@ export const createMcpServer = (): McpServer => {
throw new ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
}
- const outputPath = output || path.join(os.tmpdir(), `screen-recording-${Date.now()}.mp4`);
+ // mobilecli writes the file itself, so it records into a private directory
+ // and we move the result to `output` once it is done
+ const recordingPath = createPrivateOutputPath(`screen-recording-${Date.now()}.mp4`);
+ const outputPath = output || recordingPath;
- const args = ["screenrecord", "--device", device, "--output", outputPath, "--silent"];
+ const args = ["screenrecord", "--device", device, "--output", recordingPath, "--silent"];
if (timeLimit !== undefined) {
args.push("--time-limit", String(timeLimit));
}
@@ -1173,15 +1178,24 @@ export const createMcpServer = (): McpServer => {
activeRecordings.delete(device);
};
- child.on("error", cleanup);
- child.on("exit", cleanup);
-
- activeRecordings.set(device, {
+ const recording: ActiveRecording = {
process: child,
+ recordingPath,
outputPath,
startedAt: Date.now(),
+ };
+
+ // registered before mobile_stop_screen_recording waits on "close", so the
+ // file is already in place when stop reports it; also covers timeLimit
+ child.on("close", () => {
+ recording.moveError = finishRecording(recordingPath, outputPath);
});
+ child.on("error", cleanup);
+ child.on("exit", cleanup);
+
+ activeRecordings.set(device, recording);
+
return `Screen recording started. Output will be saved to: ${outputPath}`;
}
);
@@ -1200,7 +1214,7 @@ export const createMcpServer = (): McpServer => {
throw new ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
}
- const { process: child, outputPath, startedAt } = recording;
+ const { process: child, recordingPath, outputPath, startedAt } = recording;
activeRecordings.delete(device);
child.kill("SIGINT");
@@ -1219,6 +1233,11 @@ export const createMcpServer = (): McpServer => {
const durationSeconds = Math.round((Date.now() - startedAt) / 1000);
+ if (recording.moveError) {
+ const recovery = fs.existsSync(recordingPath) ? ` The recording is at: ${recordingPath}` : "";
+ return `Recording stopped after ~${durationSeconds}s but could not be saved to ${outputPath}: ${recording.moveError}.${recovery}`;
+ }
+
if (!fs.existsSync(outputPath)) {
return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
}
diff --git a/src/utils.ts b/src/utils.ts
index b43abbe..801f42e 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -164,3 +164,59 @@ export function writeOutputFile(filePath: string, data: string | Buffer): void {
fs.closeSync(fd);
}
}
+
+// a fresh 0700 directory nobody else can plant a symlink in, for files written
+// by mobilecli rather than by us
+export function createPrivateOutputPath(filename: string): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mobile-mcp-"));
+ return path.join(dir, filename);
+}
+
+// rename replaces a symlink at `to` instead of following it. Across filesystems
+// rename fails with EXDEV, so copy next to `to` first (COPYFILE_EXCL refuses an
+// existing path) and rename that over `to`, keeping `to` intact if the copy fails
+export function moveOutputFile(from: string, to: string): void {
+ try {
+ fs.renameSync(from, to);
+ return;
+ } catch (error: any) {
+ if (error.code !== "EXDEV") {
+ throw error;
+ }
+
+ }
+
+ const partial = path.join(path.dirname(to), `.${path.basename(to)}.${process.pid}-${Date.now()}.partial`);
+ try {
+ fs.copyFileSync(from, partial, fs.constants.COPYFILE_EXCL);
+ fs.renameSync(partial, to);
+ } catch (error) {
+ fs.rmSync(partial, { force: true });
+ throw error;
+ }
+
+ fs.rmSync(from);
+}
+
+// moves a finished recording from its private directory to the requested
+// output; returns an error message when that fails, so stop can report it
+export function finishRecording(recordingPath: string, outputPath: string): string | undefined {
+ if (!fs.existsSync(recordingPath)) {
+ return "mobilecli did not produce a recording";
+ }
+
+ if (recordingPath === outputPath) {
+ return undefined;
+ }
+
+ try {
+ validateOutputPath(outputPath);
+ moveOutputFile(recordingPath, outputPath);
+ } catch (error: any) {
+ // keep the private directory, the recording is still in it
+ return error.message;
+ }
+
+ fs.rmSync(path.dirname(recordingPath), { recursive: true, force: true });
+ return undefined;
+}
diff --git a/test/utils.ts b/test/utils.ts
index 7b649ae..9a62d17 100644
--- a/test/utils.ts
+++ b/test/utils.ts
@@ -9,6 +9,9 @@ import {
validateOutputPath,
withLowercaseScheme,
writeOutputFile,
+ moveOutputFile,
+ finishRecording,
+ createPrivateOutputPath,
} from "../src/utils";
test.describe("utils", () => {
@@ -235,4 +238,113 @@ test.describe("utils", () => {
}
});
});
+
+ // screen recordings are written by mobilecli, so they land in a private
+ // directory first and are moved to the requested output afterwards
+ test.describe("moveOutputFile", () => {
+ test.skip(process.platform === "win32", "creating a symlink needs elevated rights on windows");
+
+ const uniqueTempPath = (name: string): string => path.join(os.tmpdir(), `mobile-mcp-${process.pid}-${Date.now()}-${name}`);
+
+ test("should not move a recording through a symlink planted at the output path", () => {
+ const victim = uniqueTempPath("victim.txt");
+ const recording = uniqueTempPath("recording.mp4");
+ const output = uniqueTempPath("output.mp4");
+ fs.writeFileSync(victim, "ORIGINAL");
+ fs.writeFileSync(recording, "VIDEO");
+ fs.symlinkSync(victim, output);
+ try {
+ moveOutputFile(recording, output);
+
+ expect(fs.readFileSync(victim, "utf8")).toBe("ORIGINAL");
+ expect(fs.lstatSync(output).isSymbolicLink()).toBe(false);
+ expect(fs.readFileSync(output, "utf8")).toBe("VIDEO");
+ } finally {
+ fs.rmSync(output, { force: true });
+ fs.rmSync(recording, { force: true });
+ fs.rmSync(victim, { force: true });
+ }
+ });
+
+ test("should move a recording to a new output path", () => {
+ const recording = uniqueTempPath("recording.mp4");
+ const output = uniqueTempPath("output.mp4");
+ fs.writeFileSync(recording, "VIDEO");
+ try {
+ moveOutputFile(recording, output);
+
+ expect(fs.readFileSync(output, "utf8")).toBe("VIDEO");
+ expect(fs.existsSync(recording)).toBe(false);
+ } finally {
+ fs.rmSync(output, { force: true });
+ fs.rmSync(recording, { force: true });
+ }
+ });
+ });
+
+ test.describe("finishRecording", () => {
+ const uniqueTempPath = (name: string): string => path.join(os.tmpdir(), `mobile-mcp-${process.pid}-${Date.now()}-${name}`);
+
+ // rename fails with EXDEV when the private directory and the output live on
+ // different filesystems; simulate that and a copy that fails halfway
+ const whileRenameCrossesFilesystemsAndCopyFails = (check: () => void) => {
+ const originalRename = fs.renameSync;
+ const originalCopy = fs.copyFileSync;
+ fs.renameSync = () => {
+ throw Object.assign(new Error("cross-device link not permitted"), { code: "EXDEV" });
+ };
+ fs.copyFileSync = () => {
+ throw new Error("disk full");
+ };
+ try {
+ check();
+ } finally {
+ fs.renameSync = originalRename;
+ fs.copyFileSync = originalCopy;
+ }
+ };
+
+ test("should report a failure when mobilecli never created the recording", () => {
+ const recording = createPrivateOutputPath("recording.mp4");
+ const output = uniqueTempPath("previous.mp4");
+ fs.writeFileSync(output, "PREVIOUS RECORDING");
+ try {
+ expect(finishRecording(recording, output)).toBeDefined();
+ } finally {
+ fs.rmSync(output, { force: true });
+ fs.rmSync(path.dirname(recording), { recursive: true, force: true });
+ }
+ });
+
+ test("should remove the private directory after moving the recording", () => {
+ const recording = createPrivateOutputPath("recording.mp4");
+ const output = uniqueTempPath("output.mp4");
+ fs.writeFileSync(recording, "VIDEO");
+ try {
+ expect(finishRecording(recording, output)).toBeUndefined();
+ expect(fs.readFileSync(output, "utf8")).toBe("VIDEO");
+ expect(fs.existsSync(path.dirname(recording))).toBe(false);
+ } finally {
+ fs.rmSync(output, { force: true });
+ fs.rmSync(path.dirname(recording), { recursive: true, force: true });
+ }
+ });
+
+ test("should keep the existing output when a cross-filesystem copy fails", () => {
+ const recording = uniqueTempPath("recording.mp4");
+ const output = uniqueTempPath("existing.mp4");
+ fs.writeFileSync(recording, "VIDEO");
+ fs.writeFileSync(output, "EXISTING");
+ try {
+ whileRenameCrossesFilesystemsAndCopyFails(() => {
+ expect(() => moveOutputFile(recording, output)).toThrow();
+ });
+ expect(fs.readFileSync(output, "utf8")).toBe("EXISTING");
+ expect(fs.readFileSync(recording, "utf8")).toBe("VIDEO");
+ } finally {
+ fs.rmSync(output, { force: true });
+ fs.rmSync(recording, { force: true });
+ }
+ });
+ });
});