@mobilenext/mobile-mcp 1.0.9 → 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
@@ -175,10 +175,11 @@ class MobileDevice {
175
175
  await this.doubleTap(x + width / 2, y + height / 2);
176
176
  }
177
177
  async longPress(x, y, duration) {
178
- this.runCommand(["io", "longpress", `${Math.round(x)},${Math.round(y)}`, "--duration", `${duration}`]);
178
+ // mobilecli rejects fractional coordinates and durations, both are parsed as integers
179
+ this.runCommand(["io", "longpress", `${Math.round(x)},${Math.round(y)}`, "--duration", `${Math.round(duration)}`]);
179
180
  }
180
181
  async longPressByRef(ref, duration) {
181
- this.runCommand(["io", "longpress", ref, "--duration", `${duration}`]);
182
+ this.runCommand(["io", "longpress", ref, "--duration", `${Math.round(duration)}`]);
182
183
  }
183
184
  async getElementsOnScreen() {
184
185
  const response = this.runJsonCommand(["dump", "ui"]);
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
@@ -124,6 +124,7 @@ const createMcpServer = () => {
124
124
  if (error instanceof robot_1.ActionableError) {
125
125
  return {
126
126
  content: [{ type: "text", text: `${error.message}. Please fix the issue and try again.` }],
127
+ isError: true,
127
128
  };
128
129
  }
129
130
  else {
@@ -257,6 +258,17 @@ const createMcpServer = () => {
257
258
  }
258
259
  throw new robot_1.ActionableError(`Device "${deviceId}" not found. Use the mobile_list_available_devices tool to see available devices.`);
259
260
  };
261
+ // ponytail: same tool as @posthog/mcp's reportMissing, without pulling in the sdk
262
+ // nothing to report to when telemetry is off, so don't advertise the tool at all
263
+ if (!process.env.MOBILEMCP_DISABLE_TELEMETRY) {
264
+ tool("get_more_tools", "Get More Tools", "Check for additional tools whenever your task might benefit from specialized capabilities - even if existing tools could work as a fallback. " +
265
+ "The context is sent to the mobile-mcp developers, so never include PII, secrets, credentials or other private information in it.", {
266
+ context: zod_1.z.string().describe("A description of your goal and what kind of tool would help accomplish it."),
267
+ }, { readOnlyHint: true, openWorldHint: true }, async ({ context }) => {
268
+ posthog("$mcp_missing_capability", { "$mcp_intent": context }).then();
269
+ return "Unfortunately, we have shown you the full tool list. We have noted your feedback and will work to improve the tool list in the future.";
270
+ });
271
+ }
260
272
  tool("mobile_list_available_devices", "List Devices", "List all available devices. This includes both physical mobile devices and mobile simulators and emulators. It returns both Android and iOS devices. " +
261
273
  "These are local devices already connected to this machine, ready to use immediately at no cost - for devices from the shared remote cloud fleet, use mobile_list_remote_devices instead.", {}, { readOnlyHint: true, openWorldHint: false }, async ({}, telemetry) => {
262
274
  // from today onward, we must have mobilecli working
@@ -558,7 +570,12 @@ const createMcpServer = () => {
558
570
  });
559
571
  tool("mobile_press_button", "Press Button", "Press a button on device", {
560
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."),
561
- 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")),
562
579
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, button }) => {
563
580
  const robot = getRobotFromDevice(device);
564
581
  await robot.pressButton(button);
@@ -569,11 +586,12 @@ const createMcpServer = () => {
569
586
  url: zod_1.z.string().describe("The URL to open, starting with http:// or https://"),
570
587
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, url }) => {
571
588
  const allowUnsafeUrls = process.env.MOBILEMCP_ALLOW_UNSAFE_URLS === "1";
572
- 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://")) {
573
591
  throw new robot_1.ActionableError("Only http:// and https:// URLs are allowed. Set MOBILEMCP_ALLOW_UNSAFE_URLS=1 to allow other URL schemes.");
574
592
  }
575
593
  const robot = getRobotFromDevice(device);
576
- await robot.openUrl(url);
594
+ await robot.openUrl(normalizedUrl);
577
595
  return `Opened URL: ${url}`;
578
596
  });
579
597
  tool("mobile_swipe_on_screen", "Swipe Screen", "Swipe on the screen", {
@@ -581,7 +599,7 @@ const createMcpServer = () => {
581
599
  direction: zod_1.z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
582
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"),
583
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"),
584
- 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"),
585
603
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, direction, x, y, distance }) => {
586
604
  const robot = getRobotFromDevice(device);
587
605
  if (x !== undefined && y !== undefined) {
@@ -624,7 +642,7 @@ const createMcpServer = () => {
624
642
  if (format === "jpeg" && isPng) {
625
643
  throw new robot_1.ActionableError("This device only supports png screenshots, save to a .png file instead.");
626
644
  }
627
- node_fs_1.default.writeFileSync(saveTo, screenshot);
645
+ (0, utils_1.writeOutputFile)(saveTo, screenshot);
628
646
  return `Screenshot saved to: ${saveTo}`;
629
647
  });
630
648
  server.registerTool("mobile_take_screenshot", {
@@ -777,7 +795,7 @@ const createMcpServer = () => {
777
795
  if (!saveTo) {
778
796
  return logs || "No log entries received";
779
797
  }
780
- node_fs_1.default.writeFileSync(saveTo, logs + "\n");
798
+ (0, utils_1.writeOutputFile)(saveTo, logs + "\n");
781
799
  const lineCount = logs ? logs.split("\n").length : 0;
782
800
  return `Saved ${lineCount} log entries to: ${saveTo}`;
783
801
  });
@@ -801,8 +819,11 @@ const createMcpServer = () => {
801
819
  if (activeRecordings.has(device)) {
802
820
  throw new robot_1.ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
803
821
  }
804
- const outputPath = output || node_path_1.default.join(node_os_1.default.tmpdir(), `screen-recording-${Date.now()}.mp4`);
805
- 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"];
806
827
  if (timeLimit !== undefined) {
807
828
  args.push("--time-limit", String(timeLimit));
808
829
  }
@@ -810,13 +831,20 @@ const createMcpServer = () => {
810
831
  const cleanup = () => {
811
832
  activeRecordings.delete(device);
812
833
  };
813
- child.on("error", cleanup);
814
- child.on("exit", cleanup);
815
- activeRecordings.set(device, {
834
+ const recording = {
816
835
  process: child,
836
+ recordingPath,
817
837
  outputPath,
818
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);
819
844
  });
845
+ child.on("error", cleanup);
846
+ child.on("exit", cleanup);
847
+ activeRecordings.set(device, recording);
820
848
  return `Screen recording started. Output will be saved to: ${outputPath}`;
821
849
  });
822
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.", {
@@ -826,7 +854,7 @@ const createMcpServer = () => {
826
854
  if (!recording) {
827
855
  throw new robot_1.ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
828
856
  }
829
- const { process: child, outputPath, startedAt } = recording;
857
+ const { process: child, recordingPath, outputPath, startedAt } = recording;
830
858
  activeRecordings.delete(device);
831
859
  child.kill("SIGINT");
832
860
  await new Promise(resolve => {
@@ -840,6 +868,10 @@ const createMcpServer = () => {
840
868
  });
841
869
  });
842
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
+ }
843
875
  if (!node_fs_1.default.existsSync(outputPath)) {
844
876
  return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
845
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
  }
@@ -231,7 +231,7 @@ class WebDriverAgent {
231
231
  return output;
232
232
  }
233
233
  async getPageSource() {
234
- const url = `http://${this.host}:${this.port}/source/?format=json`;
234
+ const url = `http://${this.host}:${this.port}/source?format=json`;
235
235
  const response = await fetch(url);
236
236
  const json = await response.json();
237
237
  return json;
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.9",
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.64",
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"