@panicgit/android-test-pilot 0.1.0

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.
Files changed (65) hide show
  1. package/.claude/skills/atp/analyze-app/SKILL.md +86 -0
  2. package/.claude/skills/atp/app-map/SKILL.md +36 -0
  3. package/.claude/skills/atp/check-logs/SKILL.md +77 -0
  4. package/.claude/skills/atp/run-test/SKILL.md +92 -0
  5. package/README.ko.md +241 -0
  6. package/README.md +241 -0
  7. package/lib/android.d.ts +96 -0
  8. package/lib/android.js +740 -0
  9. package/lib/android.js.map +1 -0
  10. package/lib/image-utils.d.ts +28 -0
  11. package/lib/image-utils.js +156 -0
  12. package/lib/image-utils.js.map +1 -0
  13. package/lib/index.d.ts +2 -0
  14. package/lib/index.js +90 -0
  15. package/lib/index.js.map +1 -0
  16. package/lib/ios.d.ts +54 -0
  17. package/lib/ios.js +241 -0
  18. package/lib/ios.js.map +1 -0
  19. package/lib/iphone-simulator.d.ts +34 -0
  20. package/lib/iphone-simulator.js +227 -0
  21. package/lib/iphone-simulator.js.map +1 -0
  22. package/lib/logger.d.ts +2 -0
  23. package/lib/logger.js +23 -0
  24. package/lib/logger.js.map +1 -0
  25. package/lib/mobile-device.d.ts +25 -0
  26. package/lib/mobile-device.js +141 -0
  27. package/lib/mobile-device.js.map +1 -0
  28. package/lib/mobilecli.d.ts +32 -0
  29. package/lib/mobilecli.js +113 -0
  30. package/lib/mobilecli.js.map +1 -0
  31. package/lib/png.d.ts +9 -0
  32. package/lib/png.js +20 -0
  33. package/lib/png.js.map +1 -0
  34. package/lib/robot.d.ts +116 -0
  35. package/lib/robot.js +10 -0
  36. package/lib/robot.js.map +1 -0
  37. package/lib/server.d.ts +3 -0
  38. package/lib/server.js +692 -0
  39. package/lib/server.js.map +1 -0
  40. package/lib/tiers/abstract-tier.d.ts +48 -0
  41. package/lib/tiers/abstract-tier.js +35 -0
  42. package/lib/tiers/abstract-tier.js.map +1 -0
  43. package/lib/tiers/screenshot-tier.d.ts +19 -0
  44. package/lib/tiers/screenshot-tier.js +53 -0
  45. package/lib/tiers/screenshot-tier.js.map +1 -0
  46. package/lib/tiers/text-tier.d.ts +20 -0
  47. package/lib/tiers/text-tier.js +138 -0
  48. package/lib/tiers/text-tier.js.map +1 -0
  49. package/lib/tiers/tier-runner.d.ts +27 -0
  50. package/lib/tiers/tier-runner.js +91 -0
  51. package/lib/tiers/tier-runner.js.map +1 -0
  52. package/lib/tiers/types.d.ts +100 -0
  53. package/lib/tiers/types.js +12 -0
  54. package/lib/tiers/types.js.map +1 -0
  55. package/lib/tiers/uiautomator-tier.d.ts +16 -0
  56. package/lib/tiers/uiautomator-tier.js +91 -0
  57. package/lib/tiers/uiautomator-tier.js.map +1 -0
  58. package/lib/utils.d.ts +4 -0
  59. package/lib/utils.js +81 -0
  60. package/lib/utils.js.map +1 -0
  61. package/lib/webdriver-agent.d.ts +45 -0
  62. package/lib/webdriver-agent.js +400 -0
  63. package/lib/webdriver-agent.js.map +1 -0
  64. package/package.json +50 -0
  65. package/templates/scenario.md +49 -0
package/lib/server.js ADDED
@@ -0,0 +1,692 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createMcpServer = exports.getAgentVersion = void 0;
7
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
8
+ const zod_1 = require("zod");
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_os_1 = __importDefault(require("node:os"));
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ const node_crypto_1 = __importDefault(require("node:crypto"));
13
+ const logger_1 = require("./logger");
14
+ const android_1 = require("./android");
15
+ const robot_1 = require("./robot");
16
+ const ios_1 = require("./ios");
17
+ const png_1 = require("./png");
18
+ const image_utils_1 = require("./image-utils");
19
+ const mobilecli_1 = require("./mobilecli");
20
+ const mobile_device_1 = require("./mobile-device");
21
+ const utils_1 = require("./utils");
22
+ const tier_runner_1 = require("./tiers/tier-runner");
23
+ const text_tier_1 = require("./tiers/text-tier");
24
+ const uiautomator_tier_1 = require("./tiers/uiautomator-tier");
25
+ const screenshot_tier_1 = require("./tiers/screenshot-tier");
26
+ const ALLOWED_SCREENSHOT_EXTENSIONS = [".png", ".jpg", ".jpeg"];
27
+ const ALLOWED_RECORDING_EXTENSIONS = [".mp4"];
28
+ const getAgentVersion = () => {
29
+ const json = require("../package.json");
30
+ return json.version;
31
+ };
32
+ exports.getAgentVersion = getAgentVersion;
33
+ const createMcpServer = () => {
34
+ const server = new mcp_js_1.McpServer({
35
+ name: "android-test-pilot",
36
+ version: (0, exports.getAgentVersion)(),
37
+ });
38
+ const getClientName = () => {
39
+ try {
40
+ const clientInfo = server.server.getClientVersion();
41
+ const clientName = clientInfo?.name || "unknown";
42
+ return clientName;
43
+ }
44
+ catch (error) {
45
+ return "unknown";
46
+ }
47
+ };
48
+ const tool = (name, title, description, paramsSchema, annotations, cb) => {
49
+ server.registerTool(name, {
50
+ title,
51
+ description,
52
+ inputSchema: paramsSchema,
53
+ annotations,
54
+ }, (async (args, _extra) => {
55
+ try {
56
+ (0, logger_1.trace)(`Invoking ${name} with args: ${JSON.stringify(args)}`);
57
+ const start = +new Date();
58
+ const response = await cb(args);
59
+ const duration = +new Date() - start;
60
+ (0, logger_1.trace)(`=> ${response}`);
61
+ posthog("tool_invoked", { "ToolName": name, "Duration": duration }).then();
62
+ return {
63
+ content: [{ type: "text", text: response }],
64
+ };
65
+ }
66
+ catch (error) {
67
+ posthog("tool_failed", { "ToolName": name }).then();
68
+ if (error instanceof robot_1.ActionableError) {
69
+ return {
70
+ content: [{ type: "text", text: `${error.message}. Please fix the issue and try again.` }],
71
+ };
72
+ }
73
+ else {
74
+ // a real exception
75
+ (0, logger_1.trace)(`Tool '${description}' failed: ${error.message} stack: ${error.stack}`);
76
+ return {
77
+ content: [{ type: "text", text: `Error: ${error.message}` }],
78
+ isError: true,
79
+ };
80
+ }
81
+ }
82
+ }));
83
+ };
84
+ const posthog = async (event, properties) => {
85
+ if (process.env.MOBILEMCP_DISABLE_TELEMETRY) {
86
+ return;
87
+ }
88
+ try {
89
+ const url = "https://us.i.posthog.com/i/v0/e/";
90
+ const api_key = process.env.POSTHOG_API_KEY || "";
91
+ if (!api_key)
92
+ return;
93
+ const name = node_os_1.default.hostname() + process.execPath;
94
+ const distinct_id = node_crypto_1.default.createHash("sha256").update(name).digest("hex");
95
+ const systemProps = {
96
+ Platform: node_os_1.default.platform(),
97
+ Product: "android-test-pilot",
98
+ Version: (0, exports.getAgentVersion)(),
99
+ NodeVersion: process.version,
100
+ };
101
+ const clientName = getClientName();
102
+ if (clientName !== "unknown") {
103
+ systemProps.AgentName = clientName;
104
+ }
105
+ await fetch(url, {
106
+ method: "POST",
107
+ headers: {
108
+ "Content-Type": "application/json"
109
+ },
110
+ body: JSON.stringify({
111
+ api_key,
112
+ event,
113
+ properties: {
114
+ ...systemProps,
115
+ ...properties,
116
+ },
117
+ distinct_id,
118
+ })
119
+ });
120
+ }
121
+ catch (err) {
122
+ // ignore
123
+ }
124
+ };
125
+ const mobilecli = new mobilecli_1.Mobilecli();
126
+ const activeRecordings = new Map();
127
+ posthog("launch", {}).then();
128
+ const ensureMobilecliAvailable = () => {
129
+ try {
130
+ const version = mobilecli.getVersion();
131
+ if (version.startsWith("failed")) {
132
+ throw new Error("mobilecli version check failed");
133
+ }
134
+ }
135
+ catch (error) {
136
+ throw new robot_1.ActionableError(`mobilecli is not available or not working properly. Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki for installation instructions`);
137
+ }
138
+ };
139
+ const isAndroidRobot = (robot) => {
140
+ return robot instanceof android_1.AndroidRobot;
141
+ };
142
+ const getRobotFromDevice = (deviceId) => {
143
+ // from now on, we must have mobilecli working
144
+ ensureMobilecliAvailable();
145
+ // Check if it's an iOS device
146
+ const iosManager = new ios_1.IosManager();
147
+ const iosDevices = iosManager.listDevices();
148
+ const iosDevice = iosDevices.find(d => d.deviceId === deviceId);
149
+ if (iosDevice) {
150
+ return new ios_1.IosRobot(deviceId);
151
+ }
152
+ // Check if it's an Android device
153
+ const androidManager = new android_1.AndroidDeviceManager();
154
+ const androidDevices = androidManager.getConnectedDevices();
155
+ const androidDevice = androidDevices.find(d => d.deviceId === deviceId);
156
+ if (androidDevice) {
157
+ return new android_1.AndroidRobot(deviceId);
158
+ }
159
+ // Check if it's a simulator (will later replace all other device types as well)
160
+ const response = mobilecli.getDevices({
161
+ platform: "ios",
162
+ type: "simulator",
163
+ includeOffline: false,
164
+ });
165
+ if (response.status === "ok" && response.data && response.data.devices) {
166
+ for (const device of response.data.devices) {
167
+ if (device.id === deviceId) {
168
+ return new mobile_device_1.MobileDevice(deviceId);
169
+ }
170
+ }
171
+ }
172
+ throw new robot_1.ActionableError(`Device "${deviceId}" not found. Use the mobile_list_available_devices tool to see available devices.`);
173
+ };
174
+ 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.", {}, { readOnlyHint: true }, async ({}) => {
175
+ // from today onward, we must have mobilecli working
176
+ ensureMobilecliAvailable();
177
+ const iosManager = new ios_1.IosManager();
178
+ const androidManager = new android_1.AndroidDeviceManager();
179
+ const devices = [];
180
+ // Get Android devices with details
181
+ const androidDevices = androidManager.getConnectedDevicesWithDetails();
182
+ for (const device of androidDevices) {
183
+ devices.push({
184
+ id: device.deviceId,
185
+ name: device.name,
186
+ platform: "android",
187
+ type: "emulator",
188
+ version: device.version,
189
+ state: "online",
190
+ });
191
+ }
192
+ // Get iOS physical devices with details
193
+ try {
194
+ const iosDevices = iosManager.listDevicesWithDetails();
195
+ for (const device of iosDevices) {
196
+ devices.push({
197
+ id: device.deviceId,
198
+ name: device.deviceName,
199
+ platform: "ios",
200
+ type: "real",
201
+ version: device.version,
202
+ state: "online",
203
+ });
204
+ }
205
+ }
206
+ catch (error) {
207
+ // If go-ios is not available, silently skip
208
+ }
209
+ // Get iOS simulators from mobilecli (excluding offline devices)
210
+ const response = mobilecli.getDevices({
211
+ platform: "ios",
212
+ type: "simulator",
213
+ includeOffline: false,
214
+ });
215
+ if (response.status === "ok" && response.data && response.data.devices) {
216
+ for (const device of response.data.devices) {
217
+ devices.push({
218
+ id: device.id,
219
+ name: device.name,
220
+ platform: device.platform,
221
+ type: device.type,
222
+ version: device.version,
223
+ state: "online",
224
+ });
225
+ }
226
+ }
227
+ const out = { devices };
228
+ return JSON.stringify(out);
229
+ });
230
+ if (process.env.MOBILEFLEET_ENABLE === "1") {
231
+ tool("mobile_list_fleet_devices", "List Fleet Devices", "List devices available in the remote fleet", {}, { readOnlyHint: true }, async ({}) => {
232
+ ensureMobilecliAvailable();
233
+ const result = mobilecli.fleetListDevices();
234
+ return result;
235
+ });
236
+ tool("mobile_allocate_fleet_device", "Allocate Fleet Device", "Reserve a device from the remote fleet", {
237
+ platform: zod_1.z.enum(["ios", "android"]).describe("The platform to allocate a device for"),
238
+ }, { destructiveHint: true }, async ({ platform }) => {
239
+ ensureMobilecliAvailable();
240
+ const result = mobilecli.fleetAllocate(platform);
241
+ return result;
242
+ });
243
+ tool("mobile_release_fleet_device", "Release Fleet Device", "Release a device back to the remote fleet", {
244
+ device: zod_1.z.string().describe("The device identifier to release back to the fleet"),
245
+ }, { destructiveHint: true }, async ({ device }) => {
246
+ ensureMobilecliAvailable();
247
+ const result = mobilecli.fleetRelease(device);
248
+ return result;
249
+ });
250
+ }
251
+ tool("mobile_list_apps", "List Apps", "List all the installed apps on the device", {
252
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
253
+ }, { readOnlyHint: true }, async ({ device }) => {
254
+ const robot = getRobotFromDevice(device);
255
+ const result = await robot.listApps();
256
+ return `Found these apps on device: ${result.map(app => `${app.appName} (${app.packageName})`).join(", ")}`;
257
+ });
258
+ 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 list_apps_on_device.", {
259
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
260
+ packageName: zod_1.z.string().describe("The package name of the app to launch"),
261
+ locale: zod_1.z.string().optional().describe("Comma-separated BCP 47 locale tags to launch the app with (e.g., fr-FR,en-GB)"),
262
+ }, { destructiveHint: true }, async ({ device, packageName, locale }) => {
263
+ const robot = getRobotFromDevice(device);
264
+ await robot.launchApp(packageName, locale);
265
+ return `Launched app ${packageName}`;
266
+ });
267
+ tool("mobile_terminate_app", "Terminate App", "Stop and terminate an app on mobile device", {
268
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
269
+ packageName: zod_1.z.string().describe("The package name of the app to terminate"),
270
+ }, { destructiveHint: true }, async ({ device, packageName }) => {
271
+ const robot = getRobotFromDevice(device);
272
+ await robot.terminateApp(packageName);
273
+ return `Terminated app ${packageName}`;
274
+ });
275
+ tool("mobile_install_app", "Install App", "Install an app on mobile device", {
276
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
277
+ path: zod_1.z.string().describe("The path to the app file to install. For iOS simulators, provide a .zip file or a .app directory. For Android provide an .apk file. For iOS real devices provide an .ipa file"),
278
+ }, { destructiveHint: true }, async ({ device, path }) => {
279
+ const robot = getRobotFromDevice(device);
280
+ await robot.installApp(path);
281
+ return `Installed app from ${path}`;
282
+ });
283
+ tool("mobile_uninstall_app", "Uninstall App", "Uninstall an app from mobile device", {
284
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
285
+ bundle_id: zod_1.z.string().describe("Bundle identifier (iOS) or package name (Android) of the app to be uninstalled"),
286
+ }, { destructiveHint: true }, async ({ device, bundle_id }) => {
287
+ const robot = getRobotFromDevice(device);
288
+ await robot.uninstallApp(bundle_id);
289
+ return `Uninstalled app ${bundle_id}`;
290
+ });
291
+ tool("mobile_get_screen_size", "Get Screen Size", "Get the screen size of the mobile device in pixels", {
292
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
293
+ }, { readOnlyHint: true }, async ({ device }) => {
294
+ const robot = getRobotFromDevice(device);
295
+ const screenSize = await robot.getScreenSize();
296
+ return `Screen size is ${screenSize.width}x${screenSize.height} pixels`;
297
+ });
298
+ tool("mobile_click_on_screen_at_coordinates", "Click Screen", "Click on the screen at given x,y coordinates. If clicking on an element, use the list_elements_on_screen tool to find the coordinates.", {
299
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
300
+ x: zod_1.z.coerce.number().describe("The x coordinate to click on the screen, in pixels"),
301
+ y: zod_1.z.coerce.number().describe("The y coordinate to click on the screen, in pixels"),
302
+ }, { destructiveHint: true }, async ({ device, x, y }) => {
303
+ const robot = getRobotFromDevice(device);
304
+ await robot.tap(x, y);
305
+ return `Clicked on screen at coordinates: ${x}, ${y}`;
306
+ });
307
+ tool("mobile_double_tap_on_screen", "Double Tap Screen", "Double-tap on the screen at given x,y coordinates.", {
308
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
309
+ x: zod_1.z.coerce.number().describe("The x coordinate to double-tap, in pixels"),
310
+ y: zod_1.z.coerce.number().describe("The y coordinate to double-tap, in pixels"),
311
+ }, { destructiveHint: true }, async ({ device, x, y }) => {
312
+ const robot = getRobotFromDevice(device);
313
+ await robot.doubleTap(x, y);
314
+ return `Double-tapped on screen at coordinates: ${x}, ${y}`;
315
+ });
316
+ tool("mobile_long_press_on_screen_at_coordinates", "Long Press Screen", "Long press on the screen at given x,y coordinates. If long pressing on an element, use the list_elements_on_screen tool to find the coordinates.", {
317
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
318
+ x: zod_1.z.coerce.number().describe("The x coordinate to long press on the screen, in pixels"),
319
+ y: zod_1.z.coerce.number().describe("The y coordinate to long press on the screen, in pixels"),
320
+ duration: zod_1.z.coerce.number().min(1).max(10000).optional().describe("Duration of the long press in milliseconds. Defaults to 500ms."),
321
+ }, { destructiveHint: true }, async ({ device, x, y, duration }) => {
322
+ const robot = getRobotFromDevice(device);
323
+ const pressDuration = duration ?? 500;
324
+ await robot.longPress(x, y, pressDuration);
325
+ return `Long pressed on screen at coordinates: ${x}, ${y} for ${pressDuration}ms`;
326
+ });
327
+ tool("mobile_list_elements_on_screen", "List Screen Elements", "List elements on screen and their coordinates, with display text or accessibility label. Do not cache this result.", {
328
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
329
+ }, { readOnlyHint: true }, async ({ device }) => {
330
+ const robot = getRobotFromDevice(device);
331
+ const elements = await robot.getElementsOnScreen();
332
+ const result = elements.map(element => {
333
+ const out = {
334
+ type: element.type,
335
+ text: element.text,
336
+ label: element.label,
337
+ name: element.name,
338
+ value: element.value,
339
+ identifier: element.identifier,
340
+ coordinates: {
341
+ x: element.rect.x,
342
+ y: element.rect.y,
343
+ width: element.rect.width,
344
+ height: element.rect.height,
345
+ },
346
+ };
347
+ if (element.focused) {
348
+ out.focused = true;
349
+ }
350
+ return out;
351
+ });
352
+ return `Found these elements on screen: ${JSON.stringify(result)}`;
353
+ });
354
+ tool("mobile_press_button", "Press Button", "Press a button on device", {
355
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
356
+ 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)"),
357
+ }, { destructiveHint: true }, async ({ device, button }) => {
358
+ const robot = getRobotFromDevice(device);
359
+ await robot.pressButton(button);
360
+ return `Pressed the button: ${button}`;
361
+ });
362
+ tool("mobile_open_url", "Open URL", "Open a URL in browser on device", {
363
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
364
+ url: zod_1.z.string().describe("The URL to open"),
365
+ }, { destructiveHint: true }, async ({ device, url }) => {
366
+ const allowUnsafeUrls = process.env.MOBILEMCP_ALLOW_UNSAFE_URLS === "1";
367
+ if (!allowUnsafeUrls && !url.startsWith("http://") && !url.startsWith("https://")) {
368
+ throw new robot_1.ActionableError("Only http:// and https:// URLs are allowed. Set MOBILEMCP_ALLOW_UNSAFE_URLS=1 to allow other URL schemes.");
369
+ }
370
+ const robot = getRobotFromDevice(device);
371
+ await robot.openUrl(url);
372
+ return `Opened URL: ${url}`;
373
+ });
374
+ tool("mobile_swipe_on_screen", "Swipe Screen", "Swipe on the screen", {
375
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
376
+ direction: zod_1.z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
377
+ x: zod_1.z.coerce.number().optional().describe("The x coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
378
+ y: zod_1.z.coerce.number().optional().describe("The y coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
379
+ 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"),
380
+ }, { destructiveHint: true }, async ({ device, direction, x, y, distance }) => {
381
+ const robot = getRobotFromDevice(device);
382
+ if (x !== undefined && y !== undefined) {
383
+ // Use coordinate-based swipe
384
+ await robot.swipeFromCoordinate(x, y, direction, distance);
385
+ const distanceText = distance ? ` ${distance} pixels` : "";
386
+ return `Swiped ${direction}${distanceText} from coordinates: ${x}, ${y}`;
387
+ }
388
+ else {
389
+ // Use center-based swipe
390
+ await robot.swipe(direction);
391
+ return `Swiped ${direction} on screen`;
392
+ }
393
+ });
394
+ tool("mobile_type_keys", "Type Text", "Type text into the focused element", {
395
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
396
+ text: zod_1.z.string().describe("The text to type"),
397
+ submit: zod_1.z.boolean().describe("Whether to submit the text. If true, the text will be submitted as if the user pressed the enter key."),
398
+ }, { destructiveHint: true }, async ({ device, text, submit }) => {
399
+ const robot = getRobotFromDevice(device);
400
+ await robot.sendKeys(text);
401
+ if (submit) {
402
+ await robot.pressButton("ENTER");
403
+ }
404
+ return `Typed text: ${text}`;
405
+ });
406
+ tool("mobile_save_screenshot", "Save Screenshot", "Save a screenshot of the mobile device to a file", {
407
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
408
+ saveTo: zod_1.z.string().describe("The path to save the screenshot to. Filename must end with .png, .jpg, or .jpeg"),
409
+ }, { destructiveHint: true }, async ({ device, saveTo }) => {
410
+ (0, utils_1.validateFileExtension)(saveTo, ALLOWED_SCREENSHOT_EXTENSIONS, "save_screenshot");
411
+ (0, utils_1.validateOutputPath)(saveTo);
412
+ const robot = getRobotFromDevice(device);
413
+ const screenshot = await robot.getScreenshot();
414
+ node_fs_1.default.writeFileSync(saveTo, screenshot);
415
+ return `Screenshot saved to: ${saveTo}`;
416
+ });
417
+ server.registerTool("mobile_take_screenshot", {
418
+ title: "Take Screenshot",
419
+ 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.",
420
+ inputSchema: {
421
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
422
+ },
423
+ annotations: {
424
+ readOnlyHint: true,
425
+ },
426
+ }, async ({ device }) => {
427
+ try {
428
+ const robot = getRobotFromDevice(device);
429
+ const screenSize = await robot.getScreenSize();
430
+ let screenshot = await robot.getScreenshot();
431
+ let mimeType = "image/png";
432
+ // validate we received a png, will throw exception otherwise
433
+ const image = new png_1.PNG(screenshot);
434
+ const pngSize = image.getDimensions();
435
+ if (pngSize.width <= 0 || pngSize.height <= 0) {
436
+ throw new robot_1.ActionableError("Screenshot is invalid. Please try again.");
437
+ }
438
+ if ((0, image_utils_1.isScalingAvailable)()) {
439
+ (0, logger_1.trace)("Image scaling is available, resizing screenshot");
440
+ const image = image_utils_1.Image.fromBuffer(screenshot);
441
+ const beforeSize = screenshot.length;
442
+ screenshot = image.resize(Math.floor(pngSize.width / screenSize.scale))
443
+ .jpeg({ quality: 75 })
444
+ .toBuffer();
445
+ const afterSize = screenshot.length;
446
+ (0, logger_1.trace)(`Screenshot resized from ${beforeSize} bytes to ${afterSize} bytes`);
447
+ mimeType = "image/jpeg";
448
+ }
449
+ const screenshot64 = screenshot.toString("base64");
450
+ (0, logger_1.trace)(`Screenshot taken: ${screenshot.length} bytes`);
451
+ posthog("tool_invoked", {
452
+ "ToolName": "mobile_take_screenshot",
453
+ "ScreenshotFilesize": screenshot64.length,
454
+ "ScreenshotMimeType": mimeType,
455
+ "ScreenshotWidth": pngSize.width,
456
+ "ScreenshotHeight": pngSize.height,
457
+ }).then();
458
+ return {
459
+ content: [{ type: "image", data: screenshot64, mimeType }]
460
+ };
461
+ }
462
+ catch (err) {
463
+ (0, logger_1.error)(`Error taking screenshot: ${err.message} ${err.stack}`);
464
+ return {
465
+ content: [{ type: "text", text: `Error: ${err.message}` }],
466
+ isError: true,
467
+ };
468
+ }
469
+ });
470
+ tool("mobile_set_orientation", "Set Orientation", "Change the screen orientation of the device", {
471
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
472
+ orientation: zod_1.z.enum(["portrait", "landscape"]).describe("The desired orientation"),
473
+ }, { destructiveHint: true }, async ({ device, orientation }) => {
474
+ const robot = getRobotFromDevice(device);
475
+ await robot.setOrientation(orientation);
476
+ return `Changed device orientation to ${orientation}`;
477
+ });
478
+ tool("mobile_get_orientation", "Get Orientation", "Get the current screen orientation of the device", {
479
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
480
+ }, { readOnlyHint: true }, async ({ device }) => {
481
+ const robot = getRobotFromDevice(device);
482
+ const orientation = await robot.getOrientation();
483
+ return `Current device orientation is ${orientation}`;
484
+ });
485
+ tool("mobile_start_screen_recording", "Start Screen Recording", "Start recording the screen of a mobile device. The recording runs in the background until stopped with mobile_stop_screen_recording. Returns the path where the recording will be saved.", {
486
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
487
+ output: zod_1.z.string().optional().describe("The file path to save the recording to. Filename must end with .mp4. If not provided, a temporary path will be used."),
488
+ timeLimit: zod_1.z.coerce.number().optional().describe("Maximum recording duration in seconds. The recording will stop automatically after this time."),
489
+ }, { destructiveHint: true }, async ({ device, output, timeLimit }) => {
490
+ if (output) {
491
+ (0, utils_1.validateFileExtension)(output, ALLOWED_RECORDING_EXTENSIONS, "start_screen_recording");
492
+ (0, utils_1.validateOutputPath)(output);
493
+ }
494
+ getRobotFromDevice(device);
495
+ if (activeRecordings.has(device)) {
496
+ throw new robot_1.ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
497
+ }
498
+ const outputPath = output || node_path_1.default.join(node_os_1.default.tmpdir(), `screen-recording-${Date.now()}.mp4`);
499
+ const args = ["screenrecord", "--device", device, "--output", outputPath, "--silent"];
500
+ if (timeLimit !== undefined) {
501
+ args.push("--time-limit", String(timeLimit));
502
+ }
503
+ const child = mobilecli.spawnCommand(args);
504
+ const cleanup = () => {
505
+ activeRecordings.delete(device);
506
+ };
507
+ child.on("error", cleanup);
508
+ child.on("exit", cleanup);
509
+ activeRecordings.set(device, {
510
+ process: child,
511
+ outputPath,
512
+ startedAt: Date.now(),
513
+ });
514
+ return `Screen recording started. Output will be saved to: ${outputPath}`;
515
+ });
516
+ 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.", {
517
+ device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
518
+ }, { destructiveHint: true }, async ({ device }) => {
519
+ const recording = activeRecordings.get(device);
520
+ if (!recording) {
521
+ throw new robot_1.ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
522
+ }
523
+ const { process: child, outputPath, startedAt } = recording;
524
+ activeRecordings.delete(device);
525
+ child.kill("SIGINT");
526
+ await new Promise(resolve => {
527
+ const timeout = setTimeout(() => {
528
+ child.kill("SIGKILL");
529
+ resolve();
530
+ }, 5 * 60 * 1000);
531
+ child.on("close", () => {
532
+ clearTimeout(timeout);
533
+ resolve();
534
+ });
535
+ });
536
+ const durationSeconds = Math.round((Date.now() - startedAt) / 1000);
537
+ if (!node_fs_1.default.existsSync(outputPath)) {
538
+ return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
539
+ }
540
+ const stats = node_fs_1.default.statSync(outputPath);
541
+ const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2);
542
+ return `Recording stopped. File: ${outputPath} (${fileSizeMB} MB, ~${durationSeconds}s)`;
543
+ });
544
+ // ─── android-test-pilot: Tier 1 text-based tools ───────────────
545
+ tool("atp_dumpsys", "ATP Dumpsys", "Get current Activity or Window info via dumpsys. Text-based, fast, no screenshot needed.", {
546
+ device: zod_1.z.string().describe("The device identifier to use."),
547
+ type: zod_1.z.enum(["activity", "window"]).describe("Type of dumpsys query: 'activity' for current foreground Activity, 'window' for current focused window"),
548
+ }, { readOnlyHint: true }, async ({ device, type }) => {
549
+ const robot = getRobotFromDevice(device);
550
+ if (!isAndroidRobot(robot)) {
551
+ throw new robot_1.ActionableError("dumpsys is only supported on Android devices");
552
+ }
553
+ if (type === "activity") {
554
+ return robot.getDumpsysActivity();
555
+ }
556
+ else {
557
+ return robot.getDumpsysWindow();
558
+ }
559
+ });
560
+ tool("atp_logcat_start", "ATP Logcat Start", "Start a logcat streaming session. Collects ATP_ tagged logs in the background. Returns a session ID for reading/stopping.", {
561
+ device: zod_1.z.string().describe("The device identifier to use."),
562
+ tags: zod_1.z.array(zod_1.z.string()).default(["ATP_SCREEN", "ATP_RENDER", "ATP_API"])
563
+ .describe("Logcat tags to filter (default: ATP_SCREEN, ATP_RENDER, ATP_API)"),
564
+ durationSeconds: zod_1.z.coerce.number().int().min(10).max(300).default(60)
565
+ .describe("Max streaming duration in seconds. Auto-stops after this time. Default: 60"),
566
+ }, { readOnlyHint: true }, async ({ device, tags, durationSeconds }) => {
567
+ const robot = getRobotFromDevice(device);
568
+ if (!isAndroidRobot(robot)) {
569
+ throw new robot_1.ActionableError("logcat is only supported on Android devices");
570
+ }
571
+ const session = robot.startLogcat(tags, durationSeconds);
572
+ return JSON.stringify({
573
+ sessionId: session.id,
574
+ tags: session.tags,
575
+ maxDurationSeconds: durationSeconds,
576
+ message: `Logcat streaming started. Use atp_logcat_read with sessionId to read logs.`,
577
+ });
578
+ });
579
+ tool("atp_logcat_read", "ATP Logcat Read", "Read collected log lines from an active logcat session. Use 'since' for incremental reads.", {
580
+ device: zod_1.z.string().describe("The device identifier to use."),
581
+ sessionId: zod_1.z.string().describe("Session ID returned by atp_logcat_start"),
582
+ since: zod_1.z.coerce.number().int().min(0).optional()
583
+ .describe("Return only lines after this index (for incremental reads). Omit to get all lines."),
584
+ }, { readOnlyHint: true }, async ({ device, sessionId, since }) => {
585
+ const robot = getRobotFromDevice(device);
586
+ if (!isAndroidRobot(robot)) {
587
+ throw new robot_1.ActionableError("logcat is only supported on Android devices");
588
+ }
589
+ // Verify session belongs to this device
590
+ const session = android_1.AndroidRobot.getSession(sessionId);
591
+ if (session && session.deviceId !== device) {
592
+ throw new robot_1.ActionableError(`Logcat session "${sessionId}" belongs to a different device.`);
593
+ }
594
+ const result = robot.readLogcat(sessionId, since);
595
+ return JSON.stringify({
596
+ lines: result.lines,
597
+ lineCount: result.lineCount,
598
+ readFrom: since ?? 0,
599
+ message: `${result.lines.length} lines returned (total buffer: ${result.lineCount})`,
600
+ });
601
+ });
602
+ tool("atp_logcat_stop", "ATP Logcat Stop", "Stop an active logcat streaming session and return summary stats.", {
603
+ device: zod_1.z.string().describe("The device identifier to use."),
604
+ sessionId: zod_1.z.string().describe("Session ID returned by atp_logcat_start"),
605
+ }, { destructiveHint: true }, async ({ device, sessionId }) => {
606
+ const robot = getRobotFromDevice(device);
607
+ if (!isAndroidRobot(robot)) {
608
+ throw new robot_1.ActionableError("logcat is only supported on Android devices");
609
+ }
610
+ // Verify session belongs to this device (matches atp_logcat_read)
611
+ const session = android_1.AndroidRobot.getSession(sessionId);
612
+ if (session && session.deviceId !== device) {
613
+ throw new robot_1.ActionableError(`Logcat session "${sessionId}" belongs to a different device.`);
614
+ }
615
+ const stats = robot.stopLogcat(sessionId);
616
+ return JSON.stringify({
617
+ totalLines: stats.totalLines,
618
+ durationMs: stats.durationMs,
619
+ message: `Logcat session stopped. Collected ${stats.totalLines} lines over ${Math.round(stats.durationMs / 1000)}s.`,
620
+ });
621
+ });
622
+ // ─── android-test-pilot: Tier-based step execution ─────────────
623
+ const loadAppMap = () => {
624
+ const appMapDir = node_path_1.default.join(process.cwd(), ".claude", "app-map");
625
+ const empty = { navigationMap: "", apiScenarios: [], viewStateMap: [] };
626
+ try {
627
+ const navPath = node_path_1.default.join(appMapDir, "navigation_map.mermaid");
628
+ const apiPath = node_path_1.default.join(appMapDir, "api_scenarios.json");
629
+ const viewPath = node_path_1.default.join(appMapDir, "view_state_map.json");
630
+ return {
631
+ navigationMap: node_fs_1.default.existsSync(navPath) ? node_fs_1.default.readFileSync(navPath, "utf-8") : "",
632
+ apiScenarios: node_fs_1.default.existsSync(apiPath) ? JSON.parse(node_fs_1.default.readFileSync(apiPath, "utf-8")).apis ?? [] : [],
633
+ viewStateMap: node_fs_1.default.existsSync(viewPath) ? JSON.parse(node_fs_1.default.readFileSync(viewPath, "utf-8")).screens ?? [] : [],
634
+ };
635
+ }
636
+ catch {
637
+ return empty;
638
+ }
639
+ };
640
+ tool("atp_run_step", "ATP Run Step", "Execute a single test step using the 3-tier strategy (text → uiautomator → screenshot). Automatically falls back through tiers when a tier cannot determine the result.", {
641
+ device: zod_1.z.string().describe("The device identifier to use."),
642
+ action: zod_1.z.string().describe("The action to perform (e.g., 'tap login button', 'enter email')"),
643
+ verification: zod_1.z.string().describe("What to verify after the action (e.g., 'home screen appears')"),
644
+ expectedLogcat: zod_1.z.array(zod_1.z.object({
645
+ tag: zod_1.z.enum(["ATP_SCREEN", "ATP_RENDER", "ATP_API"]).describe("ATP log tag to match"),
646
+ pattern: zod_1.z.string().describe("Regex pattern to match against log lines"),
647
+ })).optional().describe("Expected logcat entries for Tier 1 text-based verification"),
648
+ tapTarget: zod_1.z.object({
649
+ resourceId: zod_1.z.string().optional().describe("Android resource-id to tap"),
650
+ x: zod_1.z.coerce.number().optional().describe("X coordinate to tap"),
651
+ y: zod_1.z.coerce.number().optional().describe("Y coordinate to tap"),
652
+ }).optional().describe("Element to tap during this step"),
653
+ }, { destructiveHint: true }, async ({ device, action, verification, expectedLogcat, tapTarget }) => {
654
+ // Ensure device is Android
655
+ const robot = getRobotFromDevice(device);
656
+ if (!isAndroidRobot(robot)) {
657
+ throw new robot_1.ActionableError("atp_run_step is only supported on Android devices");
658
+ }
659
+ const runner = new tier_runner_1.TierRunner([
660
+ new text_tier_1.TextTier(),
661
+ new uiautomator_tier_1.UiAutomatorTier(),
662
+ new screenshot_tier_1.ScreenshotTier(),
663
+ ]);
664
+ const context = {
665
+ deviceId: device,
666
+ step: {
667
+ action,
668
+ verification,
669
+ expectedLogcat: expectedLogcat?.map((e) => ({ tag: e.tag, pattern: e.pattern })),
670
+ tapTarget: tapTarget ? {
671
+ resourceId: tapTarget.resourceId,
672
+ coordinates: (tapTarget.x !== undefined && tapTarget.y !== undefined)
673
+ ? { x: tapTarget.x, y: tapTarget.y }
674
+ : undefined,
675
+ } : undefined,
676
+ },
677
+ appMap: loadAppMap(),
678
+ };
679
+ const result = await runner.run(context);
680
+ return JSON.stringify({
681
+ tier: result.tier,
682
+ status: result.status,
683
+ observation: result.observation,
684
+ verification: result.verification,
685
+ fallbackHint: result.fallbackHint,
686
+ error: result.error,
687
+ });
688
+ });
689
+ return server;
690
+ };
691
+ exports.createMcpServer = createMcpServer;
692
+ //# sourceMappingURL=server.js.map