@mobilenext/mobile-mcp 1.0.10 → 1.0.12

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/android.js CHANGED
@@ -374,7 +374,9 @@ class AndroidRobot {
374
374
  }
375
375
  escapeShellText(text) {
376
376
  // escape all shell special characters that could be used for injection
377
- return text.replace(/[\\'"` \t\n\r|&;()<>{}[\]$*?]/g, "\\$&");
377
+ // # and ~ are also escaped: they start a comment / a home-path expansion
378
+ // when they open a word, and a backslash before them is inert elsewhere.
379
+ return text.replace(/[\\'"` \t\n\r|&;()<>{}[\]$*?#~]/g, "\\$&");
378
380
  }
379
381
  async isDeviceKitInstalled() {
380
382
  const packages = await this.listPackages();
package/lib/index.js CHANGED
File without changes
@@ -122,10 +122,14 @@ class MobileDevice {
122
122
  }
123
123
  async getForegroundApp() {
124
124
  const response = this.runJsonCommand(["apps", "foreground"]);
125
- return {
125
+ const app = {
126
126
  appName: response.data.appName || response.data.packageName,
127
127
  packageName: response.data.packageName,
128
128
  };
129
+ if (response.data.activity) {
130
+ app.activity = response.data.activity;
131
+ }
132
+ return app;
129
133
  }
130
134
  async launchApp(packageName, locale) {
131
135
  const args = ["apps", "launch", packageName];
package/lib/mobilecli.js CHANGED
@@ -18,7 +18,7 @@ class Mobilecli {
18
18
  }
19
19
  executeCommand(args, timeoutMs) {
20
20
  const path = this.getPath();
21
- const options = { encoding: "utf8" };
21
+ const options = { encoding: "utf8", maxBuffer: MAX_BUFFER_SIZE };
22
22
  if (timeoutMs !== undefined) {
23
23
  options.timeout = timeoutMs;
24
24
  }
@@ -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
@@ -444,7 +444,7 @@ const createMcpServer = () => {
444
444
  const result = await robot.listApps();
445
445
  return `Found these apps on device: ${result.map(app => `${app.appName} (${app.packageName})`).join(", ")}`;
446
446
  });
447
- tool("mobile_get_foreground_app", "Get Foreground App", "Get the app currently in the foreground on the device. Use this to verify which app or screen you are on before interacting with it.", {
447
+ tool("mobile_get_foreground_app", "Get Foreground App", "Get the app currently in the foreground on the device, including the focused activity class on Android or view controller class on iOS when available. Use this to verify which app or screen you are on before interacting with it.", {
448
448
  device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
449
449
  }, { readOnlyHint: true, openWorldHint: false }, async ({ device }) => {
450
450
  const robot = getRobotFromDevice(device);
@@ -452,7 +452,8 @@ const createMcpServer = () => {
452
452
  throw new robot_1.ActionableError("Getting the foreground app is not supported in legacy robot mode");
453
453
  }
454
454
  const app = await robot.getForegroundApp();
455
- return `Foreground app: ${app.appName} (${app.packageName})`;
455
+ const activity = app.activity ? `, activity: ${app.activity}` : "";
456
+ return `Foreground app: ${app.appName} (${app.packageName})${activity}`;
456
457
  });
457
458
  tool("mobile_launch_app", "Launch App", "Launch an app on mobile device. Use this to open a specific app. You can find the package name of the app by calling mobile_list_apps.", {
458
459
  device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
@@ -570,7 +571,12 @@ const createMcpServer = () => {
570
571
  });
571
572
  tool("mobile_press_button", "Press Button", "Press a button on device", {
572
573
  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)"),
574
+ button: zod_1.z.string().describe([
575
+ "The button to press, in upper case. Supported buttons:",
576
+ "Android: HOME, BACK, VOLUME_UP, VOLUME_DOWN, ENTER, BACKSPACE, APP_SWITCH, POWER, DPAD_CENTER, DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT",
577
+ "iOS: HOME, VOLUME_UP, VOLUME_DOWN, ENTER, LOCK",
578
+ "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.",
579
+ ].join("\n")),
574
580
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, button }) => {
575
581
  const robot = getRobotFromDevice(device);
576
582
  await robot.pressButton(button);
@@ -581,20 +587,24 @@ const createMcpServer = () => {
581
587
  url: zod_1.z.string().describe("The URL to open, starting with http:// or https://"),
582
588
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, url }) => {
583
589
  const allowUnsafeUrls = process.env.MOBILEMCP_ALLOW_UNSAFE_URLS === "1";
584
- if (!allowUnsafeUrls && !url.startsWith("http://") && !url.startsWith("https://")) {
590
+ const normalizedUrl = (0, utils_1.withLowercaseScheme)(url);
591
+ if (!allowUnsafeUrls && !normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
585
592
  throw new robot_1.ActionableError("Only http:// and https:// URLs are allowed. Set MOBILEMCP_ALLOW_UNSAFE_URLS=1 to allow other URL schemes.");
586
593
  }
587
594
  const robot = getRobotFromDevice(device);
588
- await robot.openUrl(url);
595
+ await robot.openUrl(normalizedUrl);
589
596
  return `Opened URL: ${url}`;
590
597
  });
591
598
  tool("mobile_swipe_on_screen", "Swipe Screen", "Swipe on the screen", {
592
599
  device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
593
600
  direction: zod_1.z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
594
- 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
- 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"),
601
+ x: zod_1.z.coerce.number().min(0).optional().describe("The x coordinate to start the swipe from, in pixels. Give both x and y, or neither to start from the center of screen"),
602
+ y: zod_1.z.coerce.number().min(0).optional().describe("The y coordinate to start the swipe from, in pixels. Give both x and y, or neither to start from the center of screen"),
603
+ 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
604
  }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async ({ device, direction, x, y, distance }) => {
605
+ if ((x === undefined) !== (y === undefined)) {
606
+ throw new robot_1.ActionableError("Provide both x and y to start the swipe from a point, or neither to start from the center of the screen");
607
+ }
598
608
  const robot = getRobotFromDevice(device);
599
609
  if (x !== undefined && y !== undefined) {
600
610
  // Use coordinate-based swipe
@@ -636,7 +646,7 @@ const createMcpServer = () => {
636
646
  if (format === "jpeg" && isPng) {
637
647
  throw new robot_1.ActionableError("This device only supports png screenshots, save to a .png file instead.");
638
648
  }
639
- node_fs_1.default.writeFileSync(saveTo, screenshot);
649
+ (0, utils_1.writeOutputFile)(saveTo, screenshot);
640
650
  return `Screenshot saved to: ${saveTo}`;
641
651
  });
642
652
  server.registerTool("mobile_take_screenshot", {
@@ -789,7 +799,7 @@ const createMcpServer = () => {
789
799
  if (!saveTo) {
790
800
  return logs || "No log entries received";
791
801
  }
792
- node_fs_1.default.writeFileSync(saveTo, logs + "\n");
802
+ (0, utils_1.writeOutputFile)(saveTo, logs + "\n");
793
803
  const lineCount = logs ? logs.split("\n").length : 0;
794
804
  return `Saved ${lineCount} log entries to: ${saveTo}`;
795
805
  });
@@ -813,8 +823,11 @@ const createMcpServer = () => {
813
823
  if (activeRecordings.has(device)) {
814
824
  throw new robot_1.ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
815
825
  }
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"];
826
+ // mobilecli writes the file itself, so it records into a private directory
827
+ // and we move the result to `output` once it is done
828
+ const recordingPath = (0, utils_1.createPrivateOutputPath)(`screen-recording-${Date.now()}.mp4`);
829
+ const outputPath = output || recordingPath;
830
+ const args = ["screenrecord", "--device", device, "--output", recordingPath, "--silent"];
818
831
  if (timeLimit !== undefined) {
819
832
  args.push("--time-limit", String(timeLimit));
820
833
  }
@@ -822,13 +835,20 @@ const createMcpServer = () => {
822
835
  const cleanup = () => {
823
836
  activeRecordings.delete(device);
824
837
  };
825
- child.on("error", cleanup);
826
- child.on("exit", cleanup);
827
- activeRecordings.set(device, {
838
+ const recording = {
828
839
  process: child,
840
+ recordingPath,
829
841
  outputPath,
830
842
  startedAt: Date.now(),
843
+ };
844
+ // registered before mobile_stop_screen_recording waits on "close", so the
845
+ // file is already in place when stop reports it; also covers timeLimit
846
+ child.on("close", () => {
847
+ recording.moveError = (0, utils_1.finishRecording)(recordingPath, outputPath);
831
848
  });
849
+ child.on("error", cleanup);
850
+ child.on("exit", cleanup);
851
+ activeRecordings.set(device, recording);
832
852
  return `Screen recording started. Output will be saved to: ${outputPath}`;
833
853
  });
834
854
  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 +858,7 @@ const createMcpServer = () => {
838
858
  if (!recording) {
839
859
  throw new robot_1.ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
840
860
  }
841
- const { process: child, outputPath, startedAt } = recording;
861
+ const { process: child, recordingPath, outputPath, startedAt } = recording;
842
862
  activeRecordings.delete(device);
843
863
  child.kill("SIGINT");
844
864
  await new Promise(resolve => {
@@ -852,6 +872,10 @@ const createMcpServer = () => {
852
872
  });
853
873
  });
854
874
  const durationSeconds = Math.round((Date.now() - startedAt) / 1000);
875
+ if (recording.moveError) {
876
+ const recovery = node_fs_1.default.existsSync(recordingPath) ? ` The recording is at: ${recordingPath}` : "";
877
+ return `Recording stopped after ~${durationSeconds}s but could not be saved to ${outputPath}: ${recording.moveError}.${recovery}`;
878
+ }
855
879
  if (!node_fs_1.default.existsSync(outputPath)) {
856
880
  return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
857
881
  }
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.12",
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.67",
36
36
  "qs": "^6.15.0",
37
37
  "zod": "^4.2.0",
38
38
  "zod-to-json-schema": "3.25.0"