@mobilenext/mobile-mcp 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
File without changes
package/lib/mobilecli.js CHANGED
@@ -130,8 +130,17 @@ class Mobilecli {
130
130
  return JSON.parse(output.toString().trim());
131
131
  }
132
132
  agentStatus(deviceId) {
133
- const output = this.executeCommand(["agent", "status", "--device", deviceId]);
134
- return JSON.parse(output);
133
+ try {
134
+ const output = this.executeCommand(["agent", "status", "--device", deviceId]);
135
+ return JSON.parse(output);
136
+ }
137
+ catch (error) {
138
+ // mobilecli exits 1 when the agent is missing, but still prints the json status
139
+ if (!error.stdout) {
140
+ throw error;
141
+ }
142
+ return JSON.parse(error.stdout.toString());
143
+ }
135
144
  }
136
145
  agentInstall(deviceId) {
137
146
  this.executeCommand(["agent", "install", "--device", deviceId]);
package/lib/server.js CHANGED
@@ -570,7 +570,12 @@ const createMcpServer = () => {
570
570
  });
571
571
  tool("mobile_press_button", "Press Button", "Press a button on device", {
572
572
  device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
573
- button: zod_1.z.string().describe("The button to press. Supported buttons: BACK (android only), HOME, VOLUME_UP, VOLUME_DOWN, ENTER, DPAD_CENTER (android tv only), DPAD_UP (android tv only), DPAD_DOWN (android tv only), DPAD_LEFT (android tv only), DPAD_RIGHT (android tv only)"),
573
+ button: zod_1.z.string().describe([
574
+ "The button to press, in upper case. Supported buttons:",
575
+ "Android: HOME, BACK, VOLUME_UP, VOLUME_DOWN, ENTER, BACKSPACE, APP_SWITCH, POWER, DPAD_CENTER, DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT",
576
+ "iOS: HOME, VOLUME_UP, VOLUME_DOWN, ENTER, LOCK",
577
+ "BACKSPACE deletes the character before the cursor, APP_SWITCH opens the recent apps, POWER turns the screen on or off, LOCK locks the screen, and the DPAD buttons move focus on Android TV.",
578
+ ].join("\n")),
574
579
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, button }) => {
575
580
  const robot = getRobotFromDevice(device);
576
581
  await robot.pressButton(button);
@@ -581,11 +586,12 @@ const createMcpServer = () => {
581
586
  url: zod_1.z.string().describe("The URL to open, starting with http:// or https://"),
582
587
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, url }) => {
583
588
  const allowUnsafeUrls = process.env.MOBILEMCP_ALLOW_UNSAFE_URLS === "1";
584
- if (!allowUnsafeUrls && !url.startsWith("http://") && !url.startsWith("https://")) {
589
+ const normalizedUrl = (0, utils_1.withLowercaseScheme)(url);
590
+ if (!allowUnsafeUrls && !normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
585
591
  throw new robot_1.ActionableError("Only http:// and https:// URLs are allowed. Set MOBILEMCP_ALLOW_UNSAFE_URLS=1 to allow other URL schemes.");
586
592
  }
587
593
  const robot = getRobotFromDevice(device);
588
- await robot.openUrl(url);
594
+ await robot.openUrl(normalizedUrl);
589
595
  return `Opened URL: ${url}`;
590
596
  });
591
597
  tool("mobile_swipe_on_screen", "Swipe Screen", "Swipe on the screen", {
@@ -593,7 +599,7 @@ const createMcpServer = () => {
593
599
  direction: zod_1.z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
594
600
  x: zod_1.z.coerce.number().min(0).optional().describe("The x coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
595
601
  y: zod_1.z.coerce.number().min(0).optional().describe("The y coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
596
- distance: zod_1.z.coerce.number().optional().describe("The distance to swipe in pixels. Defaults to 400 pixels for iOS or 30% of screen dimension for Android"),
602
+ distance: zod_1.z.coerce.number().min(1).optional().describe("The distance to swipe in pixels. Defaults to 400 pixels for iOS or 30% of screen dimension for Android"),
597
603
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, direction, x, y, distance }) => {
598
604
  const robot = getRobotFromDevice(device);
599
605
  if (x !== undefined && y !== undefined) {
@@ -636,7 +642,7 @@ const createMcpServer = () => {
636
642
  if (format === "jpeg" && isPng) {
637
643
  throw new robot_1.ActionableError("This device only supports png screenshots, save to a .png file instead.");
638
644
  }
639
- node_fs_1.default.writeFileSync(saveTo, screenshot);
645
+ (0, utils_1.writeOutputFile)(saveTo, screenshot);
640
646
  return `Screenshot saved to: ${saveTo}`;
641
647
  });
642
648
  server.registerTool("mobile_take_screenshot", {
@@ -789,7 +795,7 @@ const createMcpServer = () => {
789
795
  if (!saveTo) {
790
796
  return logs || "No log entries received";
791
797
  }
792
- node_fs_1.default.writeFileSync(saveTo, logs + "\n");
798
+ (0, utils_1.writeOutputFile)(saveTo, logs + "\n");
793
799
  const lineCount = logs ? logs.split("\n").length : 0;
794
800
  return `Saved ${lineCount} log entries to: ${saveTo}`;
795
801
  });
@@ -813,8 +819,11 @@ const createMcpServer = () => {
813
819
  if (activeRecordings.has(device)) {
814
820
  throw new robot_1.ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
815
821
  }
816
- const outputPath = output || node_path_1.default.join(node_os_1.default.tmpdir(), `screen-recording-${Date.now()}.mp4`);
817
- const args = ["screenrecord", "--device", device, "--output", outputPath, "--silent"];
822
+ // mobilecli writes the file itself, so it records into a private directory
823
+ // and we move the result to `output` once it is done
824
+ const recordingPath = (0, utils_1.createPrivateOutputPath)(`screen-recording-${Date.now()}.mp4`);
825
+ const outputPath = output || recordingPath;
826
+ const args = ["screenrecord", "--device", device, "--output", recordingPath, "--silent"];
818
827
  if (timeLimit !== undefined) {
819
828
  args.push("--time-limit", String(timeLimit));
820
829
  }
@@ -822,13 +831,20 @@ const createMcpServer = () => {
822
831
  const cleanup = () => {
823
832
  activeRecordings.delete(device);
824
833
  };
825
- child.on("error", cleanup);
826
- child.on("exit", cleanup);
827
- activeRecordings.set(device, {
834
+ const recording = {
828
835
  process: child,
836
+ recordingPath,
829
837
  outputPath,
830
838
  startedAt: Date.now(),
839
+ };
840
+ // registered before mobile_stop_screen_recording waits on "close", so the
841
+ // file is already in place when stop reports it; also covers timeLimit
842
+ child.on("close", () => {
843
+ recording.moveError = (0, utils_1.finishRecording)(recordingPath, outputPath);
831
844
  });
845
+ child.on("error", cleanup);
846
+ child.on("exit", cleanup);
847
+ activeRecordings.set(device, recording);
832
848
  return `Screen recording started. Output will be saved to: ${outputPath}`;
833
849
  });
834
850
  tool("mobile_stop_screen_recording", "Stop Screen Recording", "Stop an active screen recording on a mobile device. Returns the file path, size, and approximate duration of the recording.", {
@@ -838,7 +854,7 @@ const createMcpServer = () => {
838
854
  if (!recording) {
839
855
  throw new robot_1.ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
840
856
  }
841
- const { process: child, outputPath, startedAt } = recording;
857
+ const { process: child, recordingPath, outputPath, startedAt } = recording;
842
858
  activeRecordings.delete(device);
843
859
  child.kill("SIGINT");
844
860
  await new Promise(resolve => {
@@ -852,6 +868,10 @@ const createMcpServer = () => {
852
868
  });
853
869
  });
854
870
  const durationSeconds = Math.round((Date.now() - startedAt) / 1000);
871
+ if (recording.moveError) {
872
+ const recovery = node_fs_1.default.existsSync(recordingPath) ? ` The recording is at: ${recordingPath}` : "";
873
+ return `Recording stopped after ~${durationSeconds}s but could not be saved to ${outputPath}: ${recording.moveError}.${recovery}`;
874
+ }
855
875
  if (!node_fs_1.default.existsSync(outputPath)) {
856
876
  return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
857
877
  }
package/lib/utils.js CHANGED
@@ -5,8 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.validatePackageName = validatePackageName;
7
7
  exports.validateLocale = validateLocale;
8
+ exports.withLowercaseScheme = withLowercaseScheme;
8
9
  exports.validateFileExtension = validateFileExtension;
9
10
  exports.validateOutputPath = validateOutputPath;
11
+ exports.writeOutputFile = writeOutputFile;
12
+ exports.createPrivateOutputPath = createPrivateOutputPath;
13
+ exports.moveOutputFile = moveOutputFile;
14
+ exports.finishRecording = finishRecording;
10
15
  const node_path_1 = __importDefault(require("node:path"));
11
16
  const node_os_1 = __importDefault(require("node:os"));
12
17
  const node_fs_1 = __importDefault(require("node:fs"));
@@ -24,6 +29,13 @@ function validateLocale(locale) {
24
29
  throw new robot_1.ActionableError(`Invalid locale: "${locale}"`);
25
30
  }
26
31
  }
32
+ // a url scheme per RFC 3986 section 3.1: a letter, then letters, digits, "+", "-" or "."
33
+ const URL_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
34
+ // url schemes are case-insensitive, but android matches an intent's scheme
35
+ // case-sensitively, so HTTPS://example.com would find no browser
36
+ function withLowercaseScheme(url) {
37
+ return url.replace(URL_SCHEME, scheme => scheme.toLowerCase());
38
+ }
27
39
  function resolveRoot(root) {
28
40
  const resolved = node_path_1.default.resolve(root);
29
41
  try {
@@ -33,11 +45,18 @@ function resolveRoot(root) {
33
45
  return resolved;
34
46
  }
35
47
  }
48
+ // the filesystem root, the home directory, or anything above it would make
49
+ // almost every file the user owns writable, so it is never an implicit root
50
+ function isTooBroadToAllow(dir) {
51
+ const resolvedDir = resolveRoot(dir);
52
+ const home = resolveRoot(node_os_1.default.homedir());
53
+ return resolvedDir === home || isPathUnderRoot(home, resolvedDir);
54
+ }
36
55
  function getAllowedRoots() {
37
- const roots = [
38
- node_os_1.default.tmpdir(),
39
- process.cwd(),
40
- ];
56
+ const roots = [node_os_1.default.tmpdir()];
57
+ if (!isTooBroadToAllow(process.cwd())) {
58
+ roots.push(process.cwd());
59
+ }
41
60
  // macOS /tmp is a symlink to /private/tmp, add both to be safe
42
61
  if (process.platform === "darwin") {
43
62
  roots.push("/tmp");
@@ -67,16 +86,49 @@ function validateFileExtension(filePath, allowedExtensions, toolName) {
67
86
  throw new robot_1.ActionableError(`${toolName} requires a ${allowedExtensions.join(", ")} file extension, got: "${ext || "(none)"}"`);
68
87
  }
69
88
  }
89
+ // windows follows up to 63 reparse points per path, linux 40 and macos 32;
90
+ // anything longer is rejected rather than handed to the write
91
+ const MAX_SYMLINK_HOPS = 64;
92
+ // Walk `filePath` to the real location a write would land on, following a
93
+ // symlink in EVERY component - not just the parent directory. Resolving only the
94
+ // parent let a symlink at, or before, the final component redirect the write
95
+ // while the check still saw an in-root path: a single final-component link was
96
+ // covered, but a chain whose intermediate link sits inside an allowed root and
97
+ // whose final target is dangling (the file a write would create) was not, so the
98
+ // write escaped. Follow each hop to its target until a component that either
99
+ // exists as a real file or does not exist at all, and hand that to the root check.
70
100
  function resolveWithSymlinks(filePath) {
71
- const resolved = node_path_1.default.resolve(filePath);
72
- const dir = node_path_1.default.dirname(resolved);
73
- const filename = node_path_1.default.basename(resolved);
74
- try {
75
- return node_path_1.default.join(node_fs_1.default.realpathSync(dir), filename);
76
- }
77
- catch {
78
- return resolved;
101
+ let current = node_path_1.default.resolve(filePath);
102
+ // bound the walk so a symlink cycle cannot spin forever
103
+ for (let hops = 0; hops < MAX_SYMLINK_HOPS; hops++) {
104
+ const dir = node_path_1.default.dirname(current);
105
+ const filename = node_path_1.default.basename(current);
106
+ // resolve the containing directory first (it may be a symlink itself,
107
+ // e.g. /tmp and /var on macOS) so it lines up with the allowed roots
108
+ let realDir;
109
+ try {
110
+ realDir = node_fs_1.default.realpathSync(dir);
111
+ }
112
+ catch {
113
+ realDir = dir;
114
+ }
115
+ const candidate = node_path_1.default.join(realDir, filename);
116
+ let stat;
117
+ try {
118
+ stat = node_fs_1.default.lstatSync(candidate);
119
+ }
120
+ catch {
121
+ // nothing there yet, it will be created at `candidate`
122
+ return candidate;
123
+ }
124
+ if (!stat.isSymbolicLink()) {
125
+ return candidate;
126
+ }
127
+ // follow the link to its target - which may itself be a link, or may not
128
+ // exist yet (exactly where a write would create the file) - and resolve again
129
+ current = node_path_1.default.resolve(realDir, node_fs_1.default.readlinkSync(candidate));
79
130
  }
131
+ throw new robot_1.ActionableError(`"${filePath}" has too many levels of symbolic links.`);
80
132
  }
81
133
  function validateOutputPath(filePath) {
82
134
  const resolved = resolveWithSymlinks(filePath);
@@ -90,6 +142,69 @@ function validateOutputPath(filePath) {
90
142
  });
91
143
  if (!isAllowed) {
92
144
  const dir = node_path_1.default.dirname(resolved);
93
- throw new robot_1.ActionableError(`"${dir}" is not in the list of allowed directories. Allowed directories include the current directory and the temp directory on this host.`);
145
+ throw new robot_1.ActionableError(`"${dir}" is not in the list of allowed directories. Allowed directories: ${allowedRoots.join(", ")}.`);
146
+ }
147
+ }
148
+ // O_NOFOLLOW makes the open itself refuse a symlink at the final component, so a
149
+ // link planted after validateOutputPath cannot redirect the write.
150
+ // ponytail: windows has no O_NOFOLLOW, there we rely on validateOutputPath alone
151
+ const WRITE_NO_FOLLOW_FLAGS = node_fs_1.default.constants.O_WRONLY | node_fs_1.default.constants.O_CREAT | node_fs_1.default.constants.O_TRUNC | (node_fs_1.default.constants.O_NOFOLLOW ?? 0);
152
+ function writeOutputFile(filePath, data) {
153
+ const fd = node_fs_1.default.openSync(filePath, WRITE_NO_FOLLOW_FLAGS);
154
+ try {
155
+ node_fs_1.default.writeFileSync(fd, data);
156
+ }
157
+ finally {
158
+ node_fs_1.default.closeSync(fd);
159
+ }
160
+ }
161
+ // a fresh 0700 directory nobody else can plant a symlink in, for files written
162
+ // by mobilecli rather than by us
163
+ function createPrivateOutputPath(filename) {
164
+ const dir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "mobile-mcp-"));
165
+ return node_path_1.default.join(dir, filename);
166
+ }
167
+ // rename replaces a symlink at `to` instead of following it. Across filesystems
168
+ // rename fails with EXDEV, so copy next to `to` first (COPYFILE_EXCL refuses an
169
+ // existing path) and rename that over `to`, keeping `to` intact if the copy fails
170
+ function moveOutputFile(from, to) {
171
+ try {
172
+ node_fs_1.default.renameSync(from, to);
173
+ return;
174
+ }
175
+ catch (error) {
176
+ if (error.code !== "EXDEV") {
177
+ throw error;
178
+ }
179
+ }
180
+ const partial = node_path_1.default.join(node_path_1.default.dirname(to), `.${node_path_1.default.basename(to)}.${process.pid}-${Date.now()}.partial`);
181
+ try {
182
+ node_fs_1.default.copyFileSync(from, partial, node_fs_1.default.constants.COPYFILE_EXCL);
183
+ node_fs_1.default.renameSync(partial, to);
184
+ }
185
+ catch (error) {
186
+ node_fs_1.default.rmSync(partial, { force: true });
187
+ throw error;
188
+ }
189
+ node_fs_1.default.rmSync(from);
190
+ }
191
+ // moves a finished recording from its private directory to the requested
192
+ // output; returns an error message when that fails, so stop can report it
193
+ function finishRecording(recordingPath, outputPath) {
194
+ if (!node_fs_1.default.existsSync(recordingPath)) {
195
+ return "mobilecli did not produce a recording";
196
+ }
197
+ if (recordingPath === outputPath) {
198
+ return undefined;
199
+ }
200
+ try {
201
+ validateOutputPath(outputPath);
202
+ moveOutputFile(recordingPath, outputPath);
203
+ }
204
+ catch (error) {
205
+ // keep the private directory, the recording is still in it
206
+ return error.message;
94
207
  }
208
+ node_fs_1.default.rmSync(node_path_1.default.dirname(recordingPath), { recursive: true, force: true });
209
+ return undefined;
95
210
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mobilenext/mobile-mcp",
3
3
  "mcpName": "io.github.mobile-next/mobile-mcp",
4
- "version": "1.0.10",
4
+ "version": "1.0.11",
5
5
  "description": "Mobile MCP",
6
6
  "repository": {
7
7
  "type": "git",
@@ -12,7 +12,7 @@
12
12
  },
13
13
  "license": "Apache-2.0",
14
14
  "scripts": {
15
- "build": "tsc && chmod +x lib/index.js",
15
+ "build": "tsc",
16
16
  "start": "node lib/index.js",
17
17
  "lint": "eslint .",
18
18
  "fixlint": "eslint . --fix",
@@ -32,7 +32,7 @@
32
32
  "commander": "14.0.0",
33
33
  "express": "5.1.0",
34
34
  "fast-xml-parser": "5.8.0",
35
- "mobilewright": "0.0.65",
35
+ "mobilewright": "0.0.66",
36
36
  "qs": "^6.15.0",
37
37
  "zod": "^4.2.0",
38
38
  "zod-to-json-schema": "3.25.0"